<?php
// =============================================================
//  POST /api/v1/admin_reference/unit_update
//
//  Wraps app/edit_unit.php field-for-field: same duplicate-name check
//  excluding the row being edited, same minimum-3-characters rule
//  (enforced server-side there, unlike create_unit.php's create path).
//
//  Body: { "id": 1, "unit_name": "...", "in_charge": "..." }
// =============================================================

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();
$id       = (int)($body['id'] ?? 0);
$unitName = trim((string)($body['unit_name'] ?? ''));
$inCharge = trim((string)($body['in_charge'] ?? ''));

if ($id <= 0) Api::error(422, 'ValidationError', 'A valid unit id is required');
if (strlen($unitName) < 3) Api::error(422, 'ValidationError', 'Unit name must be at least 3 characters');
if ($inCharge === '') Api::error(422, 'ValidationError', 'Person In-Charge is required');

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

$check = $conn->prepare("SELECT id FROM units WHERE LOWER(unit_name) = LOWER(?) AND id != ?");
$check->bind_param('si', $unitName, $id);
$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 = 'ssii';
$vals  = [$unitName, $inCharge, $account->getId(), $id];
if (strlen($types) !== count($vals)) {
    error_log('unit_update.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the unit record.');
}

$stmt = $conn->prepare("UPDATE units SET unit_name = ?, in_charge = ?, updated_by = ? WHERE id = ?");
$updatedById = $account->getId();
$stmt->bind_param($types, $unitName, $inCharge, $updatedById, $id);

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

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

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