<?php
/** @var array $config */

function bearer_token(): ?string
{
    $header = $_SERVER['HTTP_AUTHORIZATION']
        ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION']
        ?? null;

    if ($header === null && function_exists('getallheaders')) {
        foreach (getallheaders() as $name => $value) {
            if (strcasecmp($name, 'Authorization') === 0) {
                $header = $value;
                break;
            }
        }
    }

    if ($header && preg_match('/^Bearer\s+(.+)$/i', $header, $m)) {
        return $m[1];
    }
    return null;
}

// Returns the decoded token payload for a valid admin session, or null.
function current_admin(array $config): ?array
{
    $token = bearer_token();
    if (!$token) return null;
    return jwt_decode($token, $config['jwt_secret']);
}

// Ends the request with 401 unless a valid admin token is present.
function require_admin(array $config): array
{
    $user = current_admin($config);
    if (!$user) json_error('No autorizado.', 401);
    return $user;
}
