<?php

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/utils.php';
require_once __DIR__ . '/persona.php';
require_once __DIR__ . '/mcp_token_auth.php';

header('Content-Type: application/json; charset=utf-8');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

familyHubApplyMcpTokenAuthIfConfigured();

/**
 * @return array<string, mixed>
 */
function readJsonBody(): array {
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') {
        return [];
    }
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function sendJson(array $payload, int $code = 200): void {
    http_response_code($code);
    echo json_encode($payload, familyHubJsonEncodeShellFlags());
    exit;
}

/**
 * @param array<int, array<string, mixed>> $people
 * @return array<string, mixed>
 */
function requireActivePerson(array $people): array {
    $p = getActivePerson($people);
    if ($p === null) {
        sendJson(['success' => false, 'error' => 'Select who is using the hub first.'], 403);
    }
    return $p;
}
