<?php
// =============================================================
//  GET /api/v1/rotations/student_mine
//
//  The authenticated Clinical Student's own full schedule — same data
//  app/student/my_rotation.php shows, via the shared
//  include/RotationScheduleHelpers.php helpers.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/RotationScheduleHelpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Api::error(405, 'MethodNotAllowed', 'Use GET');
}

$account = api_authenticate();
if ($account->getTable() !== 'clinical_students') {
    Api::error(403, 'Forbidden', 'This endpoint is for Clinical Students only');
}

$studentId = $account->getId();
$raw       = getStudentScheduleWithLiveStatus($conn, $studentId);
$byBatch   = groupStudentScheduleByBatch($raw);
$final     = getStudentFinalAssessment($conn, $studentId);

$total     = count($raw);
$ongoing   = count(array_filter($raw, fn($b) => $b['live'] === 'Ongoing'));
$completed = count(array_filter($raw, fn($b) => $b['live'] === 'Completed'));
$upcoming  = count(array_filter($raw, fn($b) => $b['live'] === 'Upcoming'));

Api::success([
    'units_flat' => $raw,
    'batches'    => $byBatch,
    'final_assessment' => $final,
    'summary' => [
        'total_units'      => $total,
        'ongoing'          => $ongoing,
        'completed'        => $completed,
        'upcoming'         => $upcoming,
        'progress_percent' => $total > 0 ? round(($completed / $total) * 100) : 0,
    ],
]);
