<?php
require_once ROOT_PATH . 'api/core/response.php';

function getAuthorizationHeader(): string
{
    if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
        return $_SERVER['HTTP_AUTHORIZATION'];
    }

    if (function_exists('apache_request_headers')) {
        $headers = apache_request_headers();

        if (!empty($headers['Authorization'])) {
            return $headers['Authorization'];
        }

        if (!empty($headers['authorization'])) {
            return $headers['authorization'];
        }
    }

    return '';
}


/**
 * Middleware Auth Guard
 * return array player data
 */
function requireAuth(): array
{
    $authHeader = getAuthorizationHeader();

    if (!preg_match('/Bearer\s+(\S+)/', $authHeader, $m)) {
        throw new Exception('Unauthorized');
    }

    $token = $m[1];


    $row = fetchOne("
        SELECT p.*
        FROM auth_tokens t
        JOIN player p ON p.IDPlayer = t.IDPlayer
        WHERE t.token = :token
          AND t.expired_at > NOW()
        LIMIT 1
    ", ['token' => $token]);

    if (!$row) {
        throw new Exception('Invalid or expired token');
    }

    execute("
        UPDATE auth_tokens SET last_used_at = NOW()
        WHERE token = :token
    ", ['token' => $token]);

    return $row;
}
