<?php

// namespace App\Filters;

// use CodeIgniter\HTTP\RequestInterface;
// use CodeIgniter\HTTP\ResponseInterface;
// use CodeIgniter\Filters\FilterInterface;
// use Firebase\JWT\JWT;
// use Firebase\JWT\Key;

// class JwtAuthFilter implements FilterInterface
// {
//     public function before(RequestInterface $request, $arguments = null)
//     {
//         helper('jwt_helper');
//         $header = $request->getHeaderLine('Authorization');

//         if (!$header || !preg_match('/Bearer\s(\S+)/', $header, $matches)) {
//             return service('response')->setJSON(['status' => 401, 'message' => 'Token required'])->setStatusCode(401);
//         }

//         $decodedToken = validateJWT($matches[1]);

//         if (!$decodedToken) {
//             return service('response')->setJSON(['status' => 401, 'message' => 'Invalid or expired token'])->setStatusCode(401);
//         }

//         return;
//     }

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




namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Config\Services;

class JwtAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        helper('jwt_helper');
        $response = Services::response();
        $header = $request->getHeaderLine('Authorization');

        // ✅ 1. Check for Bearer token
        if (!$header || !preg_match('/Bearer\s(\S+)/', $header, $matches)) {
            return $response->setJSON([
                'status' => false,
                'message' => 'Authorization token required'
            ])->setStatusCode(401);
        }

        // ✅ 2. Validate and decode the JWT
        // $decodedToken = validateJWT($matches[1]);
        $decodedToken = JWT::decode($matches[1], new Key(getenv('JWT_SECRET'), 'HS256'));


        if (!$decodedToken) {
            return $response->setJSON([
                'status' => false,
                'message' => 'Invalid or expired token'
            ])->setStatusCode(401);
        }

        // If token mismatch → user logged out elsewhere
        $userId = $decodedToken->data->user_id ?? null;
        if (!$userId) {
            return false;
        }
        $userModel = new \App\Models\UserModel();
        $user = $userModel->find($userId);
        if ($user['current_token'] !== $matches[1]) {
            return $response->setJSON([
                'status' => false,
                'message' => 'Access denied. Your token changed.'
            ])->setStatusCode(403);
        }

        // print_r($decodedToken);
        // echo $decodedToken->data->role;
        // die;

        // ✅ 3. Store decoded user data in request
        $request->user = $decodedToken;

        // ✅ 4. Role-based restriction (if $arguments are passed)
        if ($arguments && isset($decodedToken->data->role)) {
            $allowedRoles = array_map('strtolower', array_map('trim', $arguments));
            $userRole = strtolower(trim($decodedToken->data->role));
        
            if (!in_array($userRole, $allowedRoles)) {
                return $response->setJSON([
                    'status' => false,
                    'message' => 'Access denied. You do not have permission.'
                ])->setStatusCode(403);
            }
        }

        return; // All good — proceed to controller
    }

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