<?php
// =============================================================
//  POST /api/v1/admin_rbac/permissions_delete
//
//  Wraps app/manage_permission.php's delete_permission handler,
//  including its one safety rule: a permission still assigned to one
//  or more roles cannot be deleted — it must be unchecked from every
//  role first (via role_permissions_update.php), same as the desktop
//  page's own instruction to visit Roles & Permissions first.
//
//  Body: { "id": 12 }
// =============================================================

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

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

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

$body = Api::body();
$id   = (int)($body['id'] ?? 0);
if ($id <= 0) Api::error(422, 'ValidationError', 'A valid id is required.');

$perm = $conn->prepare("SELECT name FROM permissions WHERE id = ?");
$perm->bind_param('i', $id);
$perm->execute();
$row = $perm->get_result()->fetch_assoc();
$perm->close();
if (!$row) Api::error(404, 'NotFound', 'Permission not found.');

$chk = $conn->prepare("SELECT COUNT(*) AS cnt FROM role_permissions WHERE permission_id = ?");
$chk->bind_param('i', $id);
$chk->execute();
$cnt = (int)$chk->get_result()->fetch_assoc()['cnt'];
$chk->close();

if ($cnt > 0) {
    Api::error(409, 'PermissionInUse', "Cannot delete — this permission is currently assigned to $cnt role(s). Remove it from all roles first, then come back to delete it.");
}

$stmt = $conn->prepare("DELETE FROM permissions WHERE id = ?");
$stmt->bind_param('i', $id);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Database error while deleting: ' . $stmt->error);
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'delete_permission', 'permission', $id, json_encode(['name' => $row['name']]), null);

Api::success(['message' => 'Permission deleted successfully.']);
