<?php

namespace App\Filters;

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

class AuthFilter implements FilterInterface
{
    protected function addCorsHeaders($response)
    {
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        $allowedOrigins = [
            'http://localhost:5173',
            'http://localhost',
            'https://clqms01.services-summit.my.id',
        ];
        
        if (in_array($origin, $allowedOrigins)) {
            $response->setHeader('Access-Control-Allow-Origin', $origin);
            $response->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
            $response->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin, Cache-Control, Pragma');
            $response->setHeader('Access-Control-Allow-Credentials', 'true');
        }
        
        return $response;
    }

    public function before(RequestInterface $request, $arguments = null)
    {
        $key   = getenv('JWT_SECRET');
        $token = $request->getCookie('token'); // ambil dari cookie

        if (!$token) {
            $cookieHeader = $request->getHeaderLine('Cookie');
            if (!empty($cookieHeader)) {
                foreach (explode(';', $cookieHeader) as $cookie) {
                    $cookie = trim($cookie);
                    if (str_starts_with($cookie, 'token=')) {
                        $token = substr($cookie, strlen('token='));
                        break;
                    }
                }
            }
        }

        if (!$token) {
            $authHeader = $request->getHeaderLine('Authorization');
            if (!empty($authHeader) && str_starts_with($authHeader, 'Bearer ')) {
                $token = substr($authHeader, 7);
            }
        }

        // Check if this is an API request or a page request
        $isApiRequest = strpos($request->getUri()->getPath(), '/api/') !== false 
                     || $request->isAJAX();

        // Kalau tidak ada token
        if (!$token) {
            if ($isApiRequest) {
                return Services::response()
                    ->setStatusCode(401)
                    ->setJSON([
                        'status'  => 'failed',
                        'message' => 'Unauthorized: Token not found'
                    ]);
            }
            // Redirect to login for page requests
            return redirect()->to('/v2/login');
        }

        try {
            // Decode JWT : jika error maka akan mentrigger catch
            $decoded = JWT::decode($token, new Key($key, 'HS256'));

            file_put_contents(WRITEPATH . 'logs/tokens.log', date('Y-m-d H:i:s') . ' - ' . $token . PHP_EOL, FILE_APPEND);
            
            // Kalau mau, bisa inject user info ke request
            // $request->userData = $decoded;

        } catch (\Exception $e) {
            if ($isApiRequest) {
                return Services::response()
                    ->setStatusCode(401)
                    ->setJSON([
                        'status'  => 'failed',
                        'message' => 'Unauthorized: ' . $e->getMessage()
                    ]);
            }
            // Redirect to login for page requests
            return redirect()->to('/v2/login');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Tidak perlu apa-apa
    }
}
