<?php
// =============================================================
//  GET /api/v1/lessons/nurse_mine
//
//  Mobile equivalent of app/nurse/my_lessons.php's list view — every unit
//  block assigned to the calling nurse, with the same derived state flags
//  (can_draft/can_submit/can_edit/is_locked) computed from live dates and
//  assessment status, faithfully ported from that file's own PHP logic.
// =============================================================

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();
$today   = date('Y-m-d');

$stmt = $conn->prepare("
    SELECT
        nrs.id AS schedule_id,
        nrs.unit_id, nrs.unit_name,
        nrs.department_id, nrs.department_name,
        nrs.start_week, nrs.end_week, nrs.duration_weeks,
        nrs.status AS block_status,
        nr.start_date,
        nl.id           AS lesson_id,
        nl.lesson_count,
        nl.status       AS lesson_status,
        nl.submitted_at,
        na.id           AS assessment_id,
        na.stage1_status
    FROM nurse_rotation_schedules nrs
    JOIN nurse_rotations nr ON nrs.nurse_rotation_id = nr.id
    LEFT JOIN nurse_lessons nl
           ON nl.rotation_nurse_id = ? AND nl.nurse_rotation_schedule_id = nrs.id
    LEFT JOIN nurse_assessments na
           ON na.rotation_nurse_id = nr.nurse_id AND na.nurse_rotation_schedule_id = nrs.id
    WHERE nr.nurse_id = ?
      AND nrs.status != 'Missed'
    ORDER BY nrs.start_week ASC
");
$stmt->bind_param('ii', $nurseId, $nurseId);
$stmt->execute();
$blocks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

foreach ($blocks as &$b) {
    if ($b['start_date']) {
        $origin        = strtotime($b['start_date']);
        $b['date_from'] = date('Y-m-d', $origin + ($b['start_week'] - 1) * 7 * 86400);
        $b['date_to']   = date('Y-m-d', $origin + ($b['end_week'] * 7 * 86400) - 86400);
        $b['live_status'] = $b['date_to'] < $today ? 'Completed' : ($b['date_from'] > $today ? 'Upcoming' : 'Active');
    } else {
        $b['date_from'] = $b['date_to'] = null;
        $b['live_status'] = $b['block_status'];
    }
    $b['end_passed']     = ($b['date_to'] !== null && $b['date_to'] < $today);
    $b['assess_started'] = (!empty($b['stage1_status']) && $b['stage1_status'] !== 'pending');
    $b['can_draft']      = ($b['live_status'] !== 'Upcoming');
    $b['can_submit']     = ($b['end_passed'] && !$b['assess_started']);
    $b['can_edit']       = ($b['lesson_status'] === 'submitted' && !$b['assess_started']);
    $b['is_locked']      = ($b['lesson_status'] === 'submitted' && $b['assess_started']);
    $b['lesson_count']   = (int)($b['lesson_count'] ?? 0);
    unset($b['stage1_status'], $b['block_status']);
}
unset($b);

Api::success([
    'blocks' => $blocks,
    'stats' => [
        'total'     => count($blocks),
        'submitted' => count(array_filter($blocks, fn($b) => $b['lesson_status'] === 'submitted')),
        'draft'     => count(array_filter($blocks, fn($b) => $b['lesson_status'] === 'draft')),
        'pending'   => count(array_filter($blocks, fn($b) => !$b['lesson_id'] && $b['live_status'] !== 'Upcoming')),
    ],
]);
