<?php
// =============================================================
//  GET /api/v1/lessons/student_detail?unit_id=NN&rotation_id=NN
//
//  The calling student's own lesson points for one unit block, mirroring
//  app/student/my_lessons.php's form view. Returns an empty list (not an
//  error) when nothing's been submitted for this block yet.
// =============================================================

require_once __DIR__ . '/../_bootstrap.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 account type cannot access student lessons.');
}
$studentId  = $account->getId();
$unitId     = (int)($_GET['unit_id'] ?? 0);
$rotationId = (int)($_GET['rotation_id'] ?? 0);
if (!$unitId || !$rotationId) Api::error(422, 'ValidationError', 'unit_id and rotation_id are required');

$chk = $conn->prepare("
    SELECT COUNT(*) AS cnt
    FROM student_rotation_details srd
    JOIN clinical_rotations cr ON srd.clinical_rotation_id = cr.id
    WHERE srd.clinical_student_id = ? AND cr.id = ? AND srd.unit_id = ? AND srd.status != 'Cancelled'
    LIMIT 1
");
$chk->bind_param('iii', $studentId, $rotationId, $unitId);
$chk->execute();
$chkRow = $chk->get_result()->fetch_assoc();
$chk->close();
if (!$chkRow || (int)$chkRow['cnt'] === 0) {
    Api::error(404, 'NotFound', 'Unit block not found or does not belong to your account.');
}

$stmt = $conn->prepare("
    SELECT lesson_number, lesson_text
    FROM clinical_lessons
    WHERE clinical_student_id = ? AND clinical_rotation_id = ? AND unit_id = ?
    ORDER BY lesson_number ASC
");
$stmt->bind_param('iii', $studentId, $rotationId, $unitId);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

Api::success(['lessons' => array_map(fn($r) => $r['lesson_text'], $rows)]);
