<?php

namespace App\Middleware;

use App\Utils\JWT;
use App\Utils\Env;

class AuthMiddleware {
    public static $currentPayload = null;

    public static function authenticate() {
        $headers = function_exists('getallheaders') ? getallheaders() : [];
        $normalized = [];
        foreach ($headers as $k => $v) {
            $normalized[strtolower($k)] = $v;
        }

        $authHeader = isset($normalized['authorization']) ? $normalized['authorization'] : '';
        if (!preg_match('/Bearer\s*(\S+)/', $authHeader, $matches)) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            exit;
        }

        $token = $matches[1];

        // Allow Guest Tokens (Bypass JWT)
        if (strpos($token, 'guest:') === 0) {
            self::$currentPayload = ['sub' => $token, 'scope' => 'guest', 'raw' => $token];
            return $token;
        }

        $secret = Env::get('JWT_SECRET');
        $payload = JWT::decode($token, $secret);

        if (!$payload) {
            http_response_code(401);
            echo json_encode(['error' => 'Invalid Token']);
            
            // Log auth failure
            $logFile = __DIR__ . '/../../public/debug_log.txt';
            file_put_contents($logFile, "[AUTH] Invalid Token\n", FILE_APPEND);
            
            exit;
        }

        // Check expiration
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            http_response_code(401);
            echo json_encode(['error' => 'Token Expired']);
            
            // Log auth failure
            $logFile = __DIR__ . '/../../public/debug_log.txt';
            file_put_contents($logFile, "[AUTH] Token Expired\n", FILE_APPEND);
            
            exit;
        }
        
        self::$currentPayload = $payload;
        
        // Log success
        $logFile = __DIR__ . '/../../public/debug_log.txt';
        file_put_contents($logFile, "[AUTH] Success User: " . $payload['sub'] . "\n", FILE_APPEND);

        return $payload['sub']; // Return user ID
    }
}
