<?php
// =============================================================
//  POST /api/v1/admin_reference/department_toggle_status
//
//  Wraps app/departments.php's toggle_status handler: deactivate requires
//  a reason (stored, same as desktop), activate clears it. cancelled_by
//  is the acting account's own full name, matching the desktop's
//  $_SESSION-derived $username — not an id, consistent with how this
//  column has always been populated.
//
//  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_departments');

$body = Api::body();
$id     = (int)($body['id'] ?? 0);
$action = (string)($body['action'] ?? '');

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

$actingName = $account->getFirstname() . ' ' . $account->getSurname();

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

    $stmt = $conn->prepare("UPDATE departments SET status = 'Inactive', cancelled_by = ?, cancelled_reason = ?, cancelled_at = NOW() WHERE id = ?");
    $stmt->bind_param('ssi', $actingName, $reason, $id);
} else {
    $stmt = $conn->prepare("UPDATE departments 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 department status. Please try again.');
}
if ($stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Department not found');
}
$stmt->close();

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

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