<?php

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/persona.php';

/**
 * If MCP_API_TOKEN is set in .env and the request sends a matching Bearer token,
 * establish session as MCP_ACTOR_PERSON_ID (must be an existing Head of household).
 * Browser requests without Authorization are unchanged.
 */
function familyHubApplyMcpTokenAuthIfConfigured(): void {
    $configured = Env::get('MCP_API_TOKEN', '');
    if ($configured === '') {
        return;
    }

    $header = familyHubAuthorizationHeader();
    if ($header === null || !preg_match('/^\s*Bearer\s+(\S+)\s*$/i', $header, $matches)) {
        return;
    }

    $presented = $matches[1];
    if (!hash_equals($configured, $presented)) {
        return;
    }

    $actorId = trim((string) Env::get('MCP_ACTOR_PERSON_ID', ''));
    if ($actorId === '') {
        return;
    }

    $people = normalizePeopleList(readJsonFile('people.json'));
    $person = findPersonById($people, $actorId);
    if ($person === null || ($person['role'] ?? '') !== ROLE_HEAD) {
        return;
    }

    setSessionPerson($actorId, true);
}

function familyHubAuthorizationHeader(): ?string {
    if (isset($_SERVER['HTTP_AUTHORIZATION']) && is_string($_SERVER['HTTP_AUTHORIZATION']) && $_SERVER['HTTP_AUTHORIZATION'] !== '') {
        return $_SERVER['HTTP_AUTHORIZATION'];
    }
    if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && is_string($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] !== '') {
        return $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    }
    if (function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
        if (is_array($headers)) {
            foreach ($headers as $name => $value) {
                if (strcasecmp((string) $name, 'Authorization') === 0 && is_string($value) && $value !== '') {
                    return $value;
                }
            }
        }
    }
    return null;
}
