<?php
require 'config.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

function getAuthorizationHeader() {
    $headers = null;

    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER['HTTP_AUTHORIZATION']);
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        foreach ($requestHeaders as $key => $value) {
            if (strtolower($key) === 'authorization') {
                $headers = trim($value);
                break;
            }
        }
    }
    return $headers;
}

function authUser() {
    $authHeader = getAuthorizationHeader();

    if (!$authHeader) {
        http_response_code(401);
        exit(json_encode(["error" => "Authorization token missing"]));
    }

    if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        http_response_code(401);
        exit(json_encode(["error" => "Invalid authorization format"]));
    }

    $token = $matches[1];

    try {
        $decoded = JWT::decode($token, new Key(JWT_SECRET, JWT_ALGO));
        $GLOBALS['currentUser'] = $decoded;
        return $decoded;
    } catch (\Firebase\JWT\ExpiredException $e) {
        http_response_code(401);
        exit(json_encode(["error" => "Token expired"]));
    } catch (\Exception $e) {
        http_response_code(401);
        exit(json_encode(["error" => "Invalid token: " . $e->getMessage()]));
    }
}
