<?php
namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\Database;

class APIAppMediaAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Get POST data using request helper
        $postData = request()->getPost();
        
        // If POST data is empty, try to get from JSON body
        if (empty($postData)) {
            $jsonData = request()->getJSON(true);
            if ($jsonData) {
                $postData = $jsonData;
            }
        }
        
        // Check if user_serial is not empty
        if (empty($postData['user_serial'])) {
            return response()->setJSON([
                'error' => 'user_serial is required and cannot be empty'
            ])->setStatusCode(400);
        }
        
        // Check if user_activation is not empty
        if (empty($postData['user_activation'])) {
            return response()->setJSON([
                'error' => 'user_activation is required and cannot be empty'
            ])->setStatusCode(400);
        }
        
        // Check if client_client_ref is not empty
        if (empty($postData['client_client_ref'])) {
            return response()->setJSON([
                'error' => 'client_client_ref is required and cannot be empty'
            ])->setStatusCode(400);
        }
        
        // If all three are not empty, check if record exists in database
        $db = Database::connect();
        
        // Query app_activation table to check if record exists with matching values
        $builder = $db->table('app_activation');
        $record = $builder->where('user_serial', $postData['user_serial'])
            ->where('user_activation', $postData['user_activation'])
            ->where('client_client_ref', $postData['client_client_ref'])
            ->get()
            ->getRow();
        
        if (empty($record)) {
            return response()->setJSON([
                'error' => 'No matching record found with the provided credentials'
            ])->setStatusCode(401);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No action needed after request
    }
}

