<?php

require_once __DIR__ . '/../includes/api_bootstrap.php';
require_once __DIR__ . '/../includes/family_settings.php';
require_once __DIR__ . '/../includes/calendar_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendJson(['success' => false, 'error' => 'Method not allowed'], 405);
}

$people = normalizePeopleList(readJsonFile('people.json'));
requireActivePerson($people);

$familySettings = loadFamilySettings();
$from = isset($_GET['from']) ? trim((string) $_GET['from']) : '';
$to = isset($_GET['to']) ? trim((string) $_GET['to']) : '';

if ($from === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) {
    [$from, $to] = hubCalendarDefaultAgendaRange($familySettings);
} else {
    if ($to === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
        sendJson(['success' => false, 'error' => 'to must be YYYY-MM-DD when from is set'], 400);
    }
}

if ($from > $to) {
    sendJson(['success' => false, 'error' => 'from must be on or before to'], 400);
}

[, $tzLocal] = familyHubCalendarContext($familySettings);
$today = familyHubTodayYmdInTz($tzLocal);
$events = hubCalendarAgendaEvents($from, $to, $people, $familySettings);

sendJson([
    'success' => true,
    'events' => $events,
    'rangeStart' => $from,
    'rangeEnd' => $to,
    'today' => $today,
]);
