<?php
// =============================================================
//  POST /api/v1/admin_nurses/create
//
//  Onboards a Rotation Nurse account — wraps app/add_rotation_nurse.
//  php's validation and insert logic. No profile-photo upload from
//  mobile and no SMS/email side effects (same simplification as
//  api/v1/staff/create.php and admin_students/create.php) — the
//  default password is returned in the response instead.
// =============================================================

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

const DEFAULT_STUDENT_PASSWORD = 'STHstudent123'; // same shared default as clinical students/staff onboarding

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

$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'] ?? ''));   // "Staff ID / Registration No."
$schoolName  = trim((string)($body['school_name'] ?? ''));  // "Hospital / Facility"
$specialtyId = (int)($body['specialty_id'] ?? 0);

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 name is required');
if (!$specialtyId) Api::error(422, 'ValidationError', 'Specialty / Program is required');
if ($phone !== '' && !preg_match('/^[0-9]{10,15}$/', $phone)) Api::error(422, 'ValidationError', 'Phone must be 10-15 digits');

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

// Global uniqueness — email/phone must not already belong to a staff or
// clinical-student account.
$otherTables = ['users', 'clinical_students'];
if ($dup = checkGlobalDuplicate($conn, 'email', $email, null, 0, $otherTables)) {
    Api::error(409, 'DuplicateEmail', "This email is already used by another account ({$dup['name']}).");
}
if ($phone !== '' && ($dup = checkGlobalDuplicate($conn, 'phone', $phone, null, 0, $otherTables))) {
    Api::error(409, 'DuplicatePhone', "This phone number is already used by another account ({$dup['name']}).");
}

$chk = $conn->prepare('SELECT id FROM rotation_nurses WHERE email = ? OR student_id = ?');
$chk->bind_param('ss', $email, $studentId);
$chk->execute();
$chk->store_result();
if ($chk->num_rows > 0) {
    $chk->close();
    Api::error(409, 'DuplicateUser', 'Email or Staff ID already exists in Rotation Nurses');
}
$chk->close();

$phoneOrNull  = $phone !== '' ? $phone : null;
$genderOrNull = $gender !== '' ? $gender : null;
$passwordHash = password_hash(DEFAULT_STUDENT_PASSWORD, PASSWORD_BCRYPT);
$createdById  = $account->getId();

$cols = ['firstname', 'surname', 'email', 'phone', 'gender', 'password', 'profile',
    'password_change_required', 'student_id', 'school_name', 'specialty_id', 'specialty_name',
    'rotation_status', 'status', 'created_by'];
$vals = [$firstname, $surname, $email, $phoneOrNull, $genderOrNull, $passwordHash, 'default.png',
    1, $studentId, $schoolName, $specialtyId, $specialtyName, 'Not_started', 'Active', $createdById];
$types = 'sssssss' . 'i' . 'ss' . 'i' . 's' . 'ss' . 'i'; // firstname..profile(7s) pcr(i) student_id,school_name(2s) specialty_id(i) specialty_name(s) rotation_status,status(2s) created_by(i)

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

$ph = implode(',', array_fill(0, count($vals), '?'));
$stmt = $conn->prepare('INSERT INTO rotation_nurses (' . implode(',', $cols) . ") VALUES ($ph)");
$stmt->bind_param($types, ...$vals);

if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not create the account. Please try again.');
}
$newId = $conn->insert_id;
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'create_user', 'rotation_nurse', $newId, null,
    json_encode(['email' => $email, 'student_id' => $studentId, 'specialty' => $specialtyName])
);

Api::success(['id' => $newId, 'default_password' => DEFAULT_STUDENT_PASSWORD]);
