<?php
require_once __DIR__ . '/../config/jwt.php';
require_once __DIR__ . '/../helpers/Response.php';

class AuthMiddleware
{
    public static function authenticate()
    {
        $headers = apache_request_headers();
        $token = null;

        if (isset($headers['Authorization'])) {
            $matches = array();
            preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches);
            if (isset($matches[1])) {
                $token = $matches[1];
            }
        } else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { // Fallback for some server configs
            $matches = array();
            preg_match('/Bearer\s(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $matches);
            if (isset($matches[1])) {
                $token = $matches[1];
            }
        }

        // Fallback: Check Query Param or POST body (Last ditch effort)
        if (!$token && isset($_REQUEST['token'])) {
            $token = $_REQUEST['token'];
        }

        if (!$token) {
            Response::error("Unauthorized access. Token not found.", 401);
        }

        // In a real implementation with a JWT library, decode and verify the token.
        // For this boilerplate, we'll simulate verification.
        // Here you would use something like firebase/php-jwt

        // Simulation of token verification structure
        $decoded = self::verifyToken($token);

        if (!$decoded) {
            Response::error("Unauthorized access. Invalid token.", 401);
        }

        return $decoded;
    }

    private static function verifyToken($token)
    {
        // Simple simulation: token is base64 of "id:random"
        $decodedStr = base64_decode($token);
        if ($decodedStr && strpos($decodedStr, ':') !== false) {
            $parts = explode(':', $decodedStr);
            $userId = $parts[0];
            return (object) ["id" => $userId];
        }

        // Fallback for mock_token_for_dev
        if ($token === "mock_token_for_dev") {
            return (object) ["id" => 1];
        }

        return false;
    }
}
?>