<?php
// =============================================================
//  POST /api/v1/admin_reference/unit_create
//
//  Wraps app/create_unit.php field-for-field: same case-insensitive
//  duplicate-name check, same free-text in_charge value (matched by
//  full name elsewhere in the system, not a foreign key).
//
//  Body: { "unit_name": "...", "in_charge": "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_units');

$body = Api::body();
$unitName = trim((string)($body['unit_name'] ?? ''));
$inCharge = trim((string)($body['in_charge'] ?? ''));

if ($unitName === '') Api::error(422, 'ValidationError', 'Unit name is required');
if ($inCharge === '') Api::error(422, 'ValidationError', 'Person In-Charge is required');

$check = $conn->prepare("SELECT id FROM units WHERE LOWER(unit_name) = LOWER(?)");
$check->bind_param('s', $unitName);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    Api::error(409, 'DuplicateUnit', 'A unit with this name already exists');
}
$check->close();

$types = 'sis';
$vals  = [$unitName, $account->getId(), $inCharge];
if (strlen($types) !== count($vals)) {
    error_log('unit_create.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the unit record.');
}

$stmt = $conn->prepare("INSERT INTO units (unit_name, created_by, in_charge, status) VALUES (?, ?, ?, 'Active')");
$createdById = $account->getId();
$stmt->bind_param($types, $unitName, $createdById, $inCharge);

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

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'create_unit', 'unit', $newId, null, json_encode(['unit_name' => $unitName]));

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