<?php
// =============================================================
//  POST /api/v1/admin_reference/department_create
//
//  Wraps app/create_department.php field-for-field: same duplicate-name
//  check (case-insensitive), same free-text nurse_manager/preceptor
//  values (matched by full name elsewhere in the system — see
//  include/session_setup.php's scope resolution — not a foreign key),
//  same default status 'Active'.
//
//  Body: { "department_name": "...", "nurse_manager": "Firstname Surname", "preceptor": "Firstname Surname" }
// =============================================================

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();
$departmentName = trim((string)($body['department_name'] ?? ''));
$nurseManager   = trim((string)($body['nurse_manager'] ?? ''));
$preceptor      = trim((string)($body['preceptor'] ?? ''));

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

$check = $conn->prepare("SELECT id FROM departments WHERE LOWER(department_name) = LOWER(?)");
$check->bind_param('s', $departmentName);
$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 = 'siss';
$vals  = [$departmentName, $account->getId(), $nurseManager, $preceptor];
if (strlen($types) !== count($vals)) {
    error_log('department_create.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the department record.');
}

$stmt = $conn->prepare("INSERT INTO departments (department_name, created_by, nurse_manager, preceptor, status) VALUES (?, ?, ?, ?, 'Active')");
$createdById = $account->getId();
$stmt->bind_param($types, $departmentName, $createdById, $nurseManager, $preceptor);

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

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

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