<?php
// =============================================================
//  GET /api/v1/lessons/staff_nurse_detail?nurse_id=NN&schedule_id=NN
//
//  Mobile equivalent of app/nurse_lessons.php's single-submission view —
//  a staff member (assess_students) reading one nurse's full lesson text
//  before starting Stage 1. No ownership/scope filter applied to the
//  fetch itself, matching the desktop (any assessor with the permission
//  can look up any nurse_id/schedule_id pair directly).
// =============================================================

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

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

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

$nurseId    = (int)($_GET['nurse_id'] ?? 0);
$scheduleId = (int)($_GET['schedule_id'] ?? 0);
if (!$nurseId || !$scheduleId) Api::error(422, 'ValidationError', 'nurse_id and schedule_id are required');

$stmt = $conn->prepare("
    SELECT nl.*, CONCAT(rn.firstname,' ',rn.surname) AS nurse_name,
           rn.specialty_name, rn.student_id AS nurse_number, rn.school_name
    FROM nurse_lessons nl
    JOIN rotation_nurses rn ON nl.rotation_nurse_id = rn.id
    WHERE nl.rotation_nurse_id = ? AND nl.nurse_rotation_schedule_id = ?
    LIMIT 1
");
$stmt->bind_param('ii', $nurseId, $scheduleId);
$stmt->execute();
$record = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$record) Api::error(404, 'NotFound', 'No lesson submission found for this nurse/unit block.');

$lessons = json_decode($record['lessons_json'], true) ?: [];
unset($record['lessons_json']);
$record['lesson_count'] = (int)$record['lesson_count'];

Api::success(['record' => $record, 'lessons' => array_values($lessons)]);
