<?php
// =============================================================
//  POST /api/v1/admin_nurses/update
//
//  Edits a Rotation Nurse account — wraps app/edit_rotation_nurse.php's
//  no-photo UPDATE branch (no profile-photo upload from mobile, same
//  simplification as api/v1/staff/update.php). rotation_status accepts
//  the 6-value enum the desktop edit form itself allows (includes
//  "Reassigned", unlike the quick toggle_rotation action's 5-value set).
// =============================================================

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

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

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

$allowedRotationStatuses = ['Not_started', 'In_progress', 'Completed', 'On_hold', 'Cancelled', 'Reassigned'];

$body = json_decode(file_get_contents('php://input'), true) ?? [];

$editId = (int)($body['id'] ?? 0);
if (!$editId) Api::error(422, 'ValidationError', 'id is required');

$existing = $conn->prepare('SELECT id FROM rotation_nurses WHERE id = ?');
$existing->bind_param('i', $editId);
$existing->execute();
if (!$existing->get_result()->fetch_assoc()) {
    $existing->close();
    Api::error(404, 'NotFound', 'Rotation Nurse account not found');
}
$existing->close();

$firstname      = trim((string)($body['firstname'] ?? ''));
$surname        = trim((string)($body['surname'] ?? ''));
$email          = filter_var(trim((string)($body['email'] ?? '')), FILTER_SANITIZE_EMAIL);
$phone          = trim((string)($body['phone'] ?? ''));
$gender         = (string)($body['gender'] ?? '');
$studentId      = trim((string)($body['student_id'] ?? ''));
$schoolName     = trim((string)($body['school_name'] ?? ''));
$specialtyId    = (int)($body['specialty_id'] ?? 0);
$rotationStatus = (string)($body['rotation_status'] ?? 'Not_started');
$status         = in_array($body['status'] ?? '', ['Active', 'Inactive'], true) ? $body['status'] : 'Active';

if (!in_array($rotationStatus, $allowedRotationStatuses, true)) $rotationStatus = 'Not_started';

if ($firstname === '') Api::error(422, 'ValidationError', 'First name is required');
if ($surname === '') Api::error(422, 'ValidationError', 'Last name is required');
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) Api::error(422, 'ValidationError', 'A valid email is required');
if ($studentId === '') Api::error(422, 'ValidationError', 'Staff ID / Registration No. is required');
if ($schoolName === '') Api::error(422, 'ValidationError', 'Hospital / Facility is required');
if (!$specialtyId) Api::error(422, 'ValidationError', 'Specialty is required');
if ($phone !== '' && !preg_match('/^[0-9]{10,15}$/', $phone)) Api::error(422, 'ValidationError', 'Phone must be 10-15 digits');

if (checkTableDuplicate($conn, 'rotation_nurses', 'student_id', $studentId, $editId)) {
    Api::error(409, 'DuplicateStudentId', 'Staff ID already in use');
}
if ($dup = checkGlobalDuplicate($conn, 'email', $email, 'rotation_nurses', $editId)) {
    Api::error(409, 'DuplicateEmail', "This email is already used by another account ({$dup['name']}).");
}
if ($phone !== '' && ($dup = checkGlobalDuplicate($conn, 'phone', $phone, 'rotation_nurses', $editId))) {
    Api::error(409, 'DuplicatePhone', "This phone number is already used by another account ({$dup['name']}).");
}

$specStmt = $conn->prepare("SELECT name FROM specialty WHERE id = ? AND status = 'Active'");
$specStmt->bind_param('i', $specialtyId);
$specStmt->execute();
$specRow = $specStmt->get_result()->fetch_assoc();
$specStmt->close();
if (!$specRow) Api::error(422, 'ValidationError', 'Invalid or inactive specialty');
$specialtyName = $specRow['name'];

$phoneOrNull  = $phone !== '' ? $phone : null;
$genderOrNull = $gender !== '' ? $gender : null;

$stmt = $conn->prepare('
    UPDATE rotation_nurses SET firstname=?, surname=?, email=?, phone=?, gender=?,
        student_id=?, school_name=?, specialty_id=?, specialty_name=?, rotation_status=?, status=?
    WHERE id=?
');
$types = 'sssssss' . 'i' . 'sss' . 'i'; // firstname..school_name(7s) specialty_id(i) specialty_name,rotation_status,status(3s) edit_id(i) = 12 chars
$vals = [$firstname, $surname, $email, $phoneOrNull, $genderOrNull, $studentId, $schoolName,
    $specialtyId, $specialtyName, $rotationStatus, $status, $editId];

if (strlen($types) !== count($vals)) {
    error_log('admin_nurses/update.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the account record.');
}

$stmt->bind_param($types, ...$vals);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not update the account. Please try again.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'edit_user', 'rotation_nurses', $editId, null,
    json_encode(['status' => $status, 'rotation_status' => $rotationStatus, 'specialty' => $specialtyName]));

Api::success(['id' => $editId]);
