<?php
// =============================================================
//  POST /api/v1/staff/delete  { "id": 5 }
//
//  Deletes a staff account — wraps app/manage_staffs.php's delete_user
//  action exactly: same permission, same self-guard, same scoping to
//  the five staff usertypes.
// =============================================================

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

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

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

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$userId = (int)($body['id'] ?? 0);
if (!$userId) Api::error(422, 'ValidationError', 'id is required');
if ($userId === $account->getId()) {
    Api::error(403, 'Forbidden', 'You cannot delete your own account');
}

$stmt = $conn->prepare("DELETE FROM users WHERE id = ? AND usertype IN ('Admin','Chief_Preceptor','Preceptor','Nurse_Manager','In_Charge')");
$stmt->bind_param('i', $userId);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not delete the account. Please try again.');
}
$deleted = $stmt->affected_rows > 0;
$stmt->close();

if (!$deleted) {
    Api::error(404, 'NotFound', 'Staff account not found');
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'delete_user', 'user', $userId);

Api::success(['id' => $userId, 'deleted' => true]);
