<?php
// =============================================================
//  POST /api/v1/lessons/student_save
//
//  Mobile equivalent of app/student/lessons_process.php — replaces all
//  existing lesson points for the (student, rotation, unit) block with
//  the new submission. Simpler than the nurse side: no draft state and
//  no end-date gate, just a minimum-count requirement, blocked once the
//  unit's assessment has been submitted/locked.
//
//  Body: { "unit_id": NN, "rotation_id": NN, "lessons": ["...", ...] }
// =============================================================

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

const MIN_LESSONS = 10;
const MAX_LESSONS = 100;

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

$account = api_authenticate();
if ($account->getTable() !== 'clinical_students') {
    Api::error(403, 'Forbidden', 'This account type cannot access student lessons.');
}
$studentId = $account->getId();

$body       = Api::body();
$unitId     = (int)($body['unit_id'] ?? 0);
$rotationId = (int)($body['rotation_id'] ?? 0);
if (!$unitId || !$rotationId) Api::error(422, 'ValidationError', 'unit_id and rotation_id are required');

$raw = is_array($body['lessons'] ?? null) ? $body['lessons'] : [];
$lessons = [];
foreach ($raw as $text) {
    $trimmed = trim((string)$text);
    if ($trimmed !== '') $lessons[] = $trimmed;
}

if (count($lessons) < MIN_LESSONS) {
    Api::error(422, 'ValidationError', 'At least ' . MIN_LESSONS . ' lesson points are required. You submitted ' . count($lessons) . '.');
}
if (count($lessons) > MAX_LESSONS) {
    Api::error(422, 'ValidationError', 'A maximum of ' . MAX_LESSONS . ' lesson points is allowed.');
}
foreach ($lessons as $idx => $text) {
    if (mb_strlen($text) > 1000) {
        Api::error(422, 'ValidationError', 'Lesson ' . ($idx + 1) . ' exceeds 1,000 characters. Please shorten it.');
    }
}

$blk = $conn->prepare("
    SELECT COUNT(*) AS cnt
    FROM student_rotation_details srd
    JOIN clinical_rotations cr ON srd.clinical_rotation_id = cr.id
    WHERE srd.clinical_student_id = ? AND cr.id = ? AND srd.unit_id = ? AND srd.status != 'Cancelled'
    LIMIT 1
");
$blk->bind_param('iii', $studentId, $rotationId, $unitId);
$blk->execute();
$blkRow = $blk->get_result()->fetch_assoc();
$blk->close();
if (!$blkRow || (int)$blkRow['cnt'] === 0) {
    Api::error(404, 'NotFound', 'Unit block not found or does not belong to your account.');
}

$asmnt = $conn->prepare("
    SELECT id FROM clinical_assessments
    WHERE clinical_student_id = ? AND clinical_rotation_id = ? AND unit_id = ?
      AND eval_status IN ('submitted','locked')
    LIMIT 1
");
$asmnt->bind_param('iii', $studentId, $rotationId, $unitId);
$asmnt->execute();
$asmntRow = $asmnt->get_result()->fetch_assoc();
$asmnt->close();
if ($asmntRow) {
    Api::error(409, 'Locked', 'Assessment has already been submitted for this unit — lessons can no longer be edited.');
}

$unitStmt = $conn->prepare("
    SELECT DISTINCT unit_name FROM student_rotation_details
    WHERE clinical_student_id = ? AND unit_id = ? AND clinical_rotation_id = ?
    LIMIT 1
");
$unitStmt->bind_param('iii', $studentId, $unitId, $rotationId);
$unitStmt->execute();
$unitRow  = $unitStmt->get_result()->fetch_assoc();
$unitStmt->close();
$unitName = $unitRow['unit_name'] ?? "Unit #{$unitId}";

$ip  = substr($_SERVER['REMOTE_ADDR'] ?? '', 0, 45);
$now = date('Y-m-d H:i:s');

$conn->begin_transaction();
try {
    $del = $conn->prepare('DELETE FROM clinical_lessons WHERE clinical_student_id = ? AND clinical_rotation_id = ? AND unit_id = ?');
    $del->bind_param('iii', $studentId, $rotationId, $unitId);
    $del->execute();
    $del->close();

    $ins = $conn->prepare("
        INSERT INTO clinical_lessons
            (clinical_student_id, clinical_rotation_id, unit_id, lesson_number, lesson_text, submitted_at, ip_address)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    foreach ($lessons as $idx => $text) {
        $lessonNumber = $idx + 1;
        $ins->bind_param('iiiisss', $studentId, $rotationId, $unitId, $lessonNumber, $text, $now, $ip);
        $ins->execute();
    }
    $ins->close();

    $conn->commit();
} catch (Throwable $e) {
    $conn->rollback();
    error_log('lessons/student_save error: ' . $e->getMessage());
    Api::error(500, 'ServerError', 'A database error occurred while saving your lessons. Please try again.');
}

$count = count($lessons);
Api::success([
    'message'      => "{$count} lesson point" . ($count !== 1 ? 's' : '') . " submitted for {$unitName}.",
    'lesson_count' => $count,
]);
