<?php
// =============================================================
//  POST /api/v1/admin_reference/unit_toggle_status
//
//  Wraps app/units.php's toggle_status handler — see
//  department_toggle_status.php's header comment, same pattern.
//
//  Body: { "id": 1, "action": "deactivate", "reason": "..." }
//     or { "id": 1, "action": "activate" }
// =============================================================

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);
$action = (string)($body['action'] ?? '');

if ($id <= 0) Api::error(422, 'ValidationError', 'A valid unit id is required');
if (!in_array($action, ['deactivate', 'activate'], true)) Api::error(422, 'ValidationError', 'action must be deactivate or activate');

if ($action === 'deactivate') {
    $reason = trim((string)($body['reason'] ?? ''));
    if ($reason === '') Api::error(422, 'ValidationError', 'A cancellation reason is required');

    // units.cancelled_by is int(11) (a FK to users.id) — unlike
    // departments.cancelled_by, which is varchar(150) and stores the name
    // directly (see department_toggle_status.php). This mirrors a real bug
    // just found and fixed in app/units.php: binding the name string here
    // silently truncated to 0 on every unit deactivation.
    $actingId = $account->getId();
    $stmt = $conn->prepare("UPDATE units SET status = 'Inactive', cancelled_by = ?, cancelled_reason = ?, cancelled_at = NOW() WHERE id = ?");
    $stmt->bind_param('isi', $actingId, $reason, $id);
} else {
    $stmt = $conn->prepare("UPDATE units SET status = 'Active', cancelled_by = NULL, cancelled_reason = NULL, cancelled_at = NULL WHERE id = ?");
    $stmt->bind_param('i', $id);
}

if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not update the unit status. Please try again.');
}
if ($stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Unit not found');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), $action . '_unit', 'unit', $id, null, json_encode(['action' => $action]));

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