<?php
// =============================================================
//  GET /api/v1/lessons/student_mine
//
//  Mobile equivalent of app/student/my_lessons.php's list view — every
//  unit block for the calling student, aggregated the same way (one row
//  per unit/rotation, collapsing student_rotation_details' one-row-per-day
//  shape via MIN/MAX), with the same live_status/can_edit/is_locked flags.
// =============================================================

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

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

const CS_MIN_LESSONS = 10;

$account = api_authenticate();
if ($account->getTable() !== 'clinical_students') {
    Api::error(403, 'Forbidden', 'This account type cannot access student lessons.');
}
$studentId = $account->getId();
$today     = date('Y-m-d');

$stmt = $conn->prepare("
    SELECT
        srd.unit_id,
        srd.unit_name,
        MAX(srd.supervisor_name)                            AS supervisor_name,
        MIN(srd.rotation_date)                              AS start_date,
        MAX(srd.rotation_date)                              AS end_date,
        CASE
            WHEN SUM(CASE WHEN srd.status = 'Ongoing'   THEN 1 ELSE 0 END) > 0 THEN 'Ongoing'
            WHEN SUM(CASE WHEN srd.status = 'Pending'   THEN 1 ELSE 0 END) > 0 THEN 'Pending'
            WHEN SUM(CASE WHEN srd.status = 'Completed' THEN 1 ELSE 0 END) > 0 THEN 'Completed'
            ELSE 'Pending'
        END                                                 AS block_status,
        MIN(srd.sequence_order)                             AS sequence_order,
        cr.id                                               AS rotation_id,
        cr.batch_name,
        COUNT(DISTINCT cl.id)                               AS lesson_count,
        MAX(cl.submitted_at)                                AS lessons_submitted_at,
        MAX(CASE WHEN ca.id IS NOT NULL THEN 1 ELSE 0 END)  AS is_assessed
    FROM student_rotation_details srd
    JOIN clinical_rotations cr ON srd.clinical_rotation_id = cr.id
    LEFT JOIN clinical_lessons cl
           ON cl.clinical_student_id = ? AND cl.clinical_rotation_id = cr.id AND cl.unit_id = srd.unit_id
    LEFT JOIN clinical_assessments ca
           ON ca.clinical_student_id = ? AND ca.clinical_rotation_id = cr.id AND ca.unit_id = srd.unit_id
              AND ca.eval_status IN ('submitted','locked')
    WHERE srd.clinical_student_id = ?
      AND srd.status != 'Cancelled'
    GROUP BY srd.unit_id, srd.unit_name, cr.id, cr.batch_name
    ORDER BY sequence_order ASC, start_date ASC
");
$stmt->bind_param('iii', $studentId, $studentId, $studentId);
$stmt->execute();
$blocks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

foreach ($blocks as &$b) {
    if ($b['block_status'] === 'Completed' || ($b['end_date'] && $b['end_date'] < $today)) {
        $b['live_status'] = 'Completed';
    } elseif ($b['block_status'] === 'Ongoing') {
        $b['live_status'] = 'Active';
    } elseif ($b['start_date'] && $b['start_date'] > $today) {
        $b['live_status'] = 'Upcoming';
    } else {
        $b['live_status'] = 'Active';
    }
    $b['lesson_count'] = (int)$b['lesson_count'];
    $b['is_assessed']  = (bool)$b['is_assessed'];
    $b['can_edit']     = !$b['is_assessed'];
    $b['is_locked']    = $b['is_assessed'];
    unset($b['block_status']);
}
unset($b);

Api::success([
    'blocks' => $blocks,
    'stats' => [
        'total'     => count($blocks),
        'submitted' => count(array_filter($blocks, fn($b) => $b['lesson_count'] >= CS_MIN_LESSONS)),
        'pending'   => count(array_filter($blocks, fn($b) => $b['lesson_count'] < CS_MIN_LESSONS && !$b['is_locked'] && $b['live_status'] !== 'Upcoming')),
        'locked'    => count(array_filter($blocks, fn($b) => $b['is_locked'])),
    ],
]);
