<?php
// =============================================================
//  POST /api/v1/admin_students/update
//
//  Edits a Clinical Student account — wraps app/edit_clinical_student.
//  php's UPDATE branch (no profile-photo upload from mobile, same
//  simplification as api/v1/staff/update.php). rotation_status here
//  accepts the same 5-value enum as the desktop edit form (no
//  "Reassigned" — that value is edit-form-only on the Rotation Nurse
//  side, never on Clinical Student).
// =============================================================

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

$clinicalLevels = [
    'Year 1', 'Year 2', 'Year 3', 'Year 4',
    'HND 1', 'HND 2',
    'Degree 1', 'Degree 2', 'Degree 3', 'Degree 4',
    'Postgraduate',
];
$allowedRotationStatuses = ['Not_started', 'In_progress', 'Completed', 'On_hold', 'Cancelled'];

$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 clinical_students WHERE id = ?');
$existing->bind_param('i', $editId);
$existing->execute();
if (!$existing->get_result()->fetch_assoc()) {
    $existing->close();
    Api::error(404, 'NotFound', 'Clinical Student 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'] ?? ''));
$level          = trim((string)($body['level'] ?? ''));
$programme      = trim((string)($body['programme'] ?? ''));
$supervisor     = trim((string)($body['supervisor'] ?? ''));
$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', 'Student ID is required');
if ($schoolName === '') Api::error(422, 'ValidationError', 'School / Institution is required');
if (!in_array($level, $clinicalLevels, true)) Api::error(422, 'ValidationError', 'A valid Level / Year is required');
if ($phone !== '' && !preg_match('/^[0-9]{10,15}$/', $phone)) Api::error(422, 'ValidationError', 'Phone must be 10-15 digits');

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

$phoneOrNull      = $phone !== '' ? $phone : null;
$genderOrNull     = $gender !== '' ? $gender : null;
$programmeOrNull  = $programme !== '' ? $programme : null;
$supervisorOrNull = $supervisor !== '' ? $supervisor : null;

$stmt = $conn->prepare('
    UPDATE clinical_students SET firstname=?, surname=?, email=?, phone=?, gender=?,
        student_id=?, school_name=?, level=?, programme=?, supervisor_name=?, rotation_status=?, status=?
    WHERE id=?
');
$types = 'ssssssssssssi'; // 12 strings + edit_id(i) = 13 chars
$vals = [$firstname, $surname, $email, $phoneOrNull, $genderOrNull, $studentId, $schoolName,
    $level, $programmeOrNull, $supervisorOrNull, $rotationStatus, $status, $editId];

if (strlen($types) !== count($vals)) {
    error_log('admin_students/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', 'clinical_students', $editId, null,
    json_encode(['status' => $status, 'rotation_status' => $rotationStatus, 'level' => $level]));

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