<?php

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

require_once __DIR__ . '/../lib/analytics.php';

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

try {
    $opened = qdb_open_read_or_fail();
    [$pdo, $tmpDb, $lockFp] = $opened;
    $coachID = trim((string)($_GET['coachID'] ?? ''));
    if ($coachID !== '' && !empty($_GET['recent'])) {
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;
        $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
        $recent = qdb_coach_recent_submissions($pdo, $tokenRec, $coachID, $limit, $offset);
        qdb_discard($tmpDb, $lockFp);
        json_success($recent);
    }

    $coaches = qdb_coach_activity_list($pdo, $tokenRec);
    qdb_discard($tmpDb, $lockFp);
    json_success(['coaches' => $coaches]);
} catch (Throwable $e) {
    qdb_handler_fail($e, 'Load coaches', null, $tmpDb ?? null, $lockFp ?? null);
}
