<?php
// =============================================================
//  GET /api/v1/lessons/nurse_detail?schedule_id=NN
//
//  The calling nurse's own lesson points for one unit block (decoded from
//  nurse_lessons.lessons_json), mirroring app/nurse/my_lessons.php's form
//  view. Returns an empty list (not an error) when nothing's been saved
//  for this block yet — that's the normal "new submission" state.
// =============================================================

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

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

$account = api_authenticate();
if ($account->getTable() !== 'rotation_nurses') {
    Api::error(403, 'Forbidden', 'This account type cannot access nurse lessons.');
}
$nurseId    = $account->getId();
$scheduleId = (int)($_GET['schedule_id'] ?? 0);
if (!$scheduleId) Api::error(422, 'ValidationError', 'schedule_id is required');

// Ownership check — the schedule must belong to this nurse.
$chk = $conn->prepare("
    SELECT nrs.id
    FROM nurse_rotation_schedules nrs
    JOIN nurse_rotations nr ON nrs.nurse_rotation_id = nr.id
    WHERE nrs.id = ? AND nr.nurse_id = ?
    LIMIT 1
");
$chk->bind_param('ii', $scheduleId, $nurseId);
$chk->execute();
if (!$chk->get_result()->fetch_assoc()) {
    $chk->close();
    Api::error(404, 'NotFound', 'Unit block not found.');
}
$chk->close();

$stmt = $conn->prepare('SELECT lessons_json FROM nurse_lessons WHERE rotation_nurse_id = ? AND nurse_rotation_schedule_id = ?');
$stmt->bind_param('ii', $nurseId, $scheduleId);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

$lessons = [];
if ($row) {
    $lessons = json_decode($row['lessons_json'], true) ?: [];
}

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