<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/JWTHelper.php';
require_once __DIR__ . '/response.php';

// Parse Authorization Header
$headers = apache_request_headers();
$auth_header = isset($headers['Authorization']) ? $headers['Authorization'] : (isset($headers['authorization']) ? $headers['authorization'] : null);

if (!$auth_header) {
    jsonError('Authorization header missing', 401);
}

if (!preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
    jsonError('Invalid authorization format', 401);
}

$token = $matches[1];
$payload = JWTHelper::validate($token);

if (!$payload) {
    jsonError('Invalid or expired token', 401);
}

// Set Global API User
$API_USER = $payload;
?>