<?php
// =============================================================
//  POST /api/v1/lessons/nurse_save
//
//  Mobile equivalent of app/nurse/my_lessons.php's POST handler — same
//  rules, faithfully ported:
//    1. DRAFT   — can save any time after the unit block starts
//    2. SUBMIT  — final submission only allowed after the unit end date
//    3. EDIT    — after submitting, can edit until Stage 1 assessment starts
//    4. LOCKED  — once Stage 1 begins, lessons are read-only (enforced here
//                 as a 409, same as the desktop's redirect-with-error)
//
//  Body: { "schedule_id": NN, "lessons": ["...", ...], "action": "save"|"submit" }
// =============================================================

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

const MIN_LESSONS = 10;
const MAX_LESSONS = 20;

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

$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');

$body       = Api::body();
$scheduleId = (int)($body['schedule_id'] ?? 0);
$action     = ($body['action'] ?? 'save') === 'submit' ? 'submit' : 'save';

$raw = is_array($body['lessons'] ?? null) ? $body['lessons'] : [];
$lessons = [];
foreach ($raw as $pt) {
    $pt = trim((string)$pt);
    if ($pt !== '') $lessons[] = mb_substr($pt, 0, 1000);
}
$count = count($lessons);

if (!$scheduleId) Api::error(422, 'ValidationError', 'Invalid unit block.');
if ($count > MAX_LESSONS) Api::error(422, 'ValidationError', 'Maximum ' . MAX_LESSONS . ' lesson points allowed.');
if ($action === 'save' && $count === 0) Api::error(422, 'ValidationError', 'Please add at least one lesson point before saving.');
if ($action === 'submit' && $count < MIN_LESSONS) {
    Api::error(422, 'ValidationError', 'You must provide at least ' . MIN_LESSONS . ' lesson points to submit.');
}

$chk = $conn->prepare("
    SELECT nrs.id, nrs.nurse_rotation_id, nrs.unit_id, nrs.unit_name,
           nrs.department_id, nrs.department_name, nrs.start_week, nrs.end_week,
           nr.start_date
    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();
$sched = $chk->get_result()->fetch_assoc();
$chk->close();
if (!$sched) Api::error(404, 'NotFound', 'Unit block not found.');

$endDate   = null;
$endPassed = false;
if ($sched['start_date']) {
    $endDate   = date('Y-m-d', strtotime($sched['start_date']) + ((int)$sched['end_week'] * 7 * 86400) - 86400);
    $endPassed = $endDate < $today;
}

if ($action === 'submit' && !$endPassed) {
    $endLabel = $endDate ? date('d M Y', strtotime($endDate)) : 'not set';
    Api::error(409, 'TooEarly', "Final submission is only allowed after the unit ends ({$endLabel}). You can save a draft in the meantime.");
}

$exStmt = $conn->prepare('SELECT id, status FROM nurse_lessons WHERE rotation_nurse_id = ? AND nurse_rotation_schedule_id = ?');
$exStmt->bind_param('ii', $nurseId, $scheduleId);
$exStmt->execute();
$existing = $exStmt->get_result()->fetch_assoc();
$exStmt->close();

$assessStarted = false;
if ($existing) {
    $aStmt = $conn->prepare("
        SELECT id FROM nurse_assessments
        WHERE rotation_nurse_id = ? AND nurse_rotation_schedule_id = ? AND stage1_status != 'pending'
        LIMIT 1
    ");
    $aStmt->bind_param('ii', $nurseId, $scheduleId);
    $aStmt->execute();
    $assessStarted = $aStmt->get_result()->fetch_assoc() !== null;
    $aStmt->close();
}
if ($assessStarted) {
    Api::error(409, 'Locked', 'Assessment has already started — lessons can no longer be edited.');
}

$lessonsJson = json_encode(array_values($lessons), JSON_UNESCAPED_UNICODE);
$submittedAt = $action === 'submit' ? date('Y-m-d H:i:s') : null;
$status      = $action === 'submit' ? 'submitted' : 'draft';
$ip          = $_SERVER['REMOTE_ADDR'] ?? null;
$wasSubmittedBefore = $existing && $existing['status'] === 'submitted';

if ($existing) {
    $updId = (int)$existing['id'];
    $upd = $conn->prepare("
        UPDATE nurse_lessons
        SET lessons_json = ?, lesson_count = ?, status = ?, submitted_at = ?,
            ip_address = ?, last_edited_at = NOW(), updated_at = NOW()
        WHERE id = ?
    ");
    $upd->bind_param('sisssi', $lessonsJson, $count, $status, $submittedAt, $ip, $updId);
    $upd->execute();
    $upd->close();
} else {
    $ins = $conn->prepare("
        INSERT INTO nurse_lessons
            (rotation_nurse_id, nurse_rotation_id, nurse_rotation_schedule_id,
             unit_id, unit_name, department_id, department_name,
             start_week, end_week, lessons_json, lesson_count, status, submitted_at, ip_address)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ");
    $ins->bind_param(
        'iiiisisiisisss',
        $nurseId,
        $sched['nurse_rotation_id'],
        $scheduleId,
        $sched['unit_id'],
        $sched['unit_name'],
        $sched['department_id'],
        $sched['department_name'],
        $sched['start_week'],
        $sched['end_week'],
        $lessonsJson,
        $count,
        $status,
        $submittedAt,
        $ip
    );
    $ins->execute();
    $ins->close();
}

if ($action === 'submit') {
    $message = $wasSubmittedBefore
        ? "Lessons for {$sched['unit_name']} updated successfully."
        : "Lessons for {$sched['unit_name']} submitted — your In Charge can now begin the assessment.";
} else {
    $endLabel = $endDate ? date('d M Y', strtotime($endDate)) : 'the unit end date';
    $message  = "Draft saved ({$count} point" . ($count !== 1 ? 's' : '') . "). You can submit after {$endLabel}.";
}

Api::success(['message' => $message, 'status' => $status, 'lesson_count' => $count]);
