<?php
// =============================================================
//  POST /api/v1/admin_rbac/permissions_update
//
//  Wraps app/manage_permission.php's edit_permission handler. The
//  system `name` is intentionally NOT editable here either — it's
//  referenced throughout the codebase via api_require_permission()
//  and PermissionManager::sessionCan() string literals, so renaming
//  it after creation would silently break every gate that checks it.
//  Only display_name, description, and module can change.
//
//  Body: { "id": 12, "display_name": "...", "description": "...", "module": "..." }
// =============================================================

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);
$description = trim((string)($body['description'] ?? ''));
$module      = trim((string)($body['module'] ?? '')) ?: 'general';
$displayName = trim((string)($body['display_name'] ?? ''));

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

$exists = $conn->prepare("SELECT id FROM permissions WHERE id = ?");
$exists->bind_param('i', $id);
$exists->execute();
$exists->store_result();
if ($exists->num_rows === 0) {
    $exists->close();
    Api::error(404, 'NotFound', 'Permission not found.');
}
$exists->close();

// display_name is only overwritten when a non-empty value was supplied,
// matching the desktop page's own "only update columns that were
// actually filled in" intent (there implemented as skipping the SET
// fragment entirely when display_name arrives blank).
if ($displayName !== '') {
    $stmt = $conn->prepare("UPDATE permissions SET description = ?, module = ?, display_name = ? WHERE id = ?");
    $stmt->bind_param('sssi', $description, $module, $displayName, $id);
} else {
    $stmt = $conn->prepare("UPDATE permissions SET description = ?, module = ? WHERE id = ?");
    $stmt->bind_param('ssi', $description, $module, $id);
}

if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Database error while updating: ' . $stmt->error);
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'update_permission', 'permission', $id, null, json_encode(['display_name' => $displayName, 'module' => $module]));

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