<?php
// =============================================================
//  GET /api/v1/lessons/staff_student_detail?student_id=NN&rotation_id=NN&unit_id=NN
//
//  Mobile equivalent of app/clinical_lessons_ajax.php's view_student_evaluations
//  branch — a staff member reading one student's full lesson text before
//  assessing them. (The self-service branch of that same desktop endpoint
//  is covered separately by lessons/student_detail.php.)
// =============================================================

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

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

$account = api_authenticate();
api_require_permission('view_student_evaluations');

$studentId  = (int)($_GET['student_id'] ?? 0);
$rotationId = (int)($_GET['rotation_id'] ?? 0);
$unitId     = (int)($_GET['unit_id'] ?? 0);
if (!$studentId || !$rotationId || !$unitId) {
    Api::error(422, 'ValidationError', 'student_id, rotation_id and unit_id are required');
}

$stmt = $conn->prepare("
    SELECT lesson_number, lesson_text, submitted_at
    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),
    'submitted_at' => $rows[0]['submitted_at'] ?? null,
]);
