<?php
// =============================================================
//  POST /api/v1/admin_reference/specialty_toggle_status
//
//  Wraps app/specialties.php's toggle_status handler. Note the column
//  names here are deactivated_by/deactivation_reason/deactivated_at —
//  specialty's own naming, distinct from departments'/units' cancelled_*
//  columns (a pre-existing inconsistency in the schema, preserved
//  exactly rather than "fixed" here).
//
//  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_specialties');

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

if ($id <= 0) Api::error(422, 'ValidationError', 'A valid specialty 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 specialty SET status = 'Inactive', deactivated_by = ?, deactivation_reason = ?, deactivated_at = NOW() WHERE id = ?");
    $stmt->bind_param('ssi', $actingName, $reason, $id);
} else {
    $stmt = $conn->prepare("UPDATE specialty SET status = 'Active', deactivated_by = NULL, deactivation_reason = NULL, deactivated_at = NULL WHERE id = ?");
    $stmt->bind_param('i', $id);
}

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

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

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