<?php
// =============================================================
//  GET /api/v1/assessments/student_mine
//
//  The authenticated Clinical Student's own unit assessments + final
//  result — same query app/student/my_evaluations.php uses. Read-only
//  (see assessments/nurse_mine.php's header comment for why submission
//  stays desktop-side for now).
// =============================================================

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();

$stmt = $conn->prepare("
    SELECT
        ca.id, ca.unit_name, ca.assessment_date, ca.eval_status,
        ca.total_score, ca.max_possible_score, ca.percentage_score, ca.grade,
        ca.comments, ca.ward_supervisor_name, ca.ward_supervisor_rank, ca.submitted_by_role,
        srd.start_date AS unit_start, srd.end_date AS unit_end,
        cr.batch_name
    FROM clinical_assessments ca
    JOIN student_rotation_details srd
        ON srd.clinical_student_id = ca.clinical_student_id
       AND srd.unit_id = ca.unit_id
       AND srd.clinical_rotation_id = ca.clinical_rotation_id
    JOIN clinical_rotations cr ON ca.clinical_rotation_id = cr.id
    WHERE ca.clinical_student_id = ?
      AND ca.eval_status IN ('submitted','locked')
    GROUP BY ca.id
    ORDER BY ca.assessment_date DESC
");
$stmt->bind_param('i', $studentId);
$stmt->execute();
$assessments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$final = getStudentFinalAssessment($conn, $studentId);

Api::success(['assessments' => $assessments, 'final_assessment' => $final]);
