<?php

require_once __DIR__ . "/../config/jwt.php";

require_once __DIR__ . "/../lib/jwt/JWT.php";
require_once __DIR__ . "/../lib/jwt/Key.php";
require_once __DIR__ . "/../lib/jwt/ExpiredException.php";
require_once __DIR__ . "/../lib/jwt/SignatureInvalidException.php";
require_once __DIR__ . "/../lib/jwt/BeforeValidException.php";

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

function authenticate()
{
    global $jwt_secret;

    $headers = getallheaders();

    if (!isset($headers['Authorization'])) {
        http_response_code(401);
        echo json_encode(["error" => "Authorization header missing"]);
        exit;
    }

    $authHeader = $headers['Authorization'];

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

    $jwt = $matches[1];

    try {
        $decoded = JWT::decode($jwt, new Key($jwt_secret, 'HS256'));

        return $decoded; // return user data

    } catch (Exception $e) {
        http_response_code(401);
        echo json_encode(["error" => "Invalid or expired token"]);
        exit;
    }
}