<?php

$tokenRec = require_valid_token_web();
require_role(['admin', 'supervisor'], $tokenRec);

if ($method !== 'GET') {
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}

try {
    $opened = qdb_open_read_or_fail();
    [$pdo, $tmpDb, $lockFp] = $opened;

    require_once __DIR__ . '/../lib/session_schedule.php';
    $entries = qdb_list_session_schedules_scoped($pdo, $tokenRec);

    $byDate = [];
    foreach ($entries as $entry) {
        $date = $entry['scheduledDate'];
        $byDate[$date][] = $entry;
    }

    qdb_discard($tmpDb, $lockFp);

    json_success([
        'entries' => $entries,
        'byDate'  => $byDate,
    ]);
} catch (Throwable $e) {
    qdb_handler_fail($e, 'Load schedule', null, $tmpDb ?? null, $lockFp ?? null);
}
