<?php
// =============================================================
//  POST /api/v1/admin_reference/department_update
//
//  Wraps app/edit_department.php field-for-field: same duplicate-name
//  check excluding the row being edited, same three editable fields.
//
//  Body: { "id": 1, "department_name": "...", "nurse_manager": "...", "preceptor": "..." }
// =============================================================

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

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

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

$body = Api::body();
$id             = (int)($body['id'] ?? 0);
$departmentName = trim((string)($body['department_name'] ?? ''));
$nurseManager   = trim((string)($body['nurse_manager'] ?? ''));
$preceptor      = trim((string)($body['preceptor'] ?? ''));

if ($id <= 0) Api::error(422, 'ValidationError', 'A valid department id is required');
if ($departmentName === '') Api::error(422, 'ValidationError', 'Department name is required');
if ($nurseManager === '')   Api::error(422, 'ValidationError', 'Nurse Manager is required');
if ($preceptor === '')      Api::error(422, 'ValidationError', 'Preceptor is required');

$exists = $conn->prepare("SELECT id FROM departments WHERE id = ?");
$exists->bind_param('i', $id);
$exists->execute();
$exists->store_result();
if ($exists->num_rows === 0) {
    $exists->close();
    Api::error(404, 'NotFound', 'Department not found');
}
$exists->close();

$check = $conn->prepare("SELECT id FROM departments WHERE LOWER(department_name) = LOWER(?) AND id != ?");
$check->bind_param('si', $departmentName, $id);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    Api::error(409, 'DuplicateDepartment', 'A department with this name already exists');
}
$check->close();

$types = 'sssi';
$vals  = [$departmentName, $nurseManager, $preceptor, $id];
if (strlen($types) !== count($vals)) {
    error_log('department_update.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the department record.');
}

$stmt = $conn->prepare("UPDATE departments SET department_name = ?, nurse_manager = ?, preceptor = ? WHERE id = ?");
$stmt->bind_param($types, $departmentName, $nurseManager, $preceptor, $id);

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

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'update_department', 'department', $id, null, json_encode(['department_name' => $departmentName]));

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