<?php
// =============================================================
//  POST /api/v1/staff/toggle_status  { "id": 5, "status": "Inactive" }
//
//  Activates/deactivates a staff account — wraps app/manage_staffs.php's
//  toggle_status action exactly: same permission, same self-guard, same
//  scoping to the five staff usertypes (defence in depth against ever
//  targeting a non-staff row through this endpoint), same deactivation
//  email notification via the shared sendAccountEmail() helper.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/account_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_permission('deactivate_user');

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$userId = (int)($body['id'] ?? 0);
$newStatus = (string)($body['status'] ?? '');

if (!$userId) Api::error(422, 'ValidationError', 'id is required');
if (!in_array($newStatus, ['Active', 'Inactive'], true)) Api::error(422, 'ValidationError', 'status must be Active or Inactive');
if ($userId === $account->getId()) {
    Api::error(403, 'Forbidden', 'You cannot change your own status');
}

$prevStmt = $conn->prepare("SELECT firstname, email, status FROM users WHERE id = ? AND usertype IN ('Admin','Chief_Preceptor','Preceptor','Nurse_Manager','In_Charge')");
$prevStmt->bind_param('i', $userId);
$prevStmt->execute();
$prev = $prevStmt->get_result()->fetch_assoc();
$prevStmt->close();
if (!$prev) {
    Api::error(404, 'NotFound', 'Staff account not found');
}

$stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ? AND usertype IN ('Admin','Chief_Preceptor','Preceptor','Nurse_Manager','In_Charge')");
$stmt->bind_param('si', $newStatus, $userId);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not update status. Please try again.');
}
$stmt->close();

if ($prev['status'] === 'Active' && $newStatus === 'Inactive' && !empty($prev['email'])) {
    sendAccountEmail($prev['email'], 'Your STH NRMS Account Has Been Deactivated', 'Account Deactivated', [
        "Hello <strong>{$prev['firstname']}</strong>,",
        'Your STH NRMS account has been deactivated by an administrator.',
        'If you believe this is a mistake, please contact your administrator.',
    ]);
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'toggle_status', 'user', $userId, json_encode(['status' => $prev['status']]), json_encode(['status' => $newStatus]));

Api::success(['id' => $userId, 'status' => $newStatus]);
