<?php
// =============================================================
//  POST /api/v1/admin_rbac/permissions_create
//
//  Wraps app/manage_permission.php's add_permission handler: same
//  lowercase-letters-and-underscores name format, same duplicate
//  check, same auto-generated display name when one isn't supplied.
//  Unlike the desktop page this skips its legacy pre-display_name-
//  column schema fallback — every environment this API runs against
//  already has the modern permissions schema (display_name, module),
//  same assumption every other admin_* endpoint in this API makes.
//
//  Body: { "name": "manage_allocations", "display_name": "...", "description": "...", "module": "allocations" }
// =============================================================

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

if ($name === '') Api::error(422, 'ValidationError', 'Permission name is required. Example: manage_allocations');
if (!preg_match('/^[a-z_]+$/', $name)) {
    Api::error(422, 'ValidationError', 'Permission name must use lowercase letters and underscores only. Example: manage_allocations');
}

$check = $conn->prepare("SELECT id FROM permissions WHERE name = ?");
$check->bind_param('s', $name);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    Api::error(409, 'DuplicatePermission', "A permission named \"$name\" already exists. Permission names must be unique.");
}
$check->close();

$types = 'ssss';
$vals  = [$name, $displayName, $description, $module];
if (strlen($types) !== count($vals)) {
    error_log('permissions_create.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the permission record.');
}

$stmt = $conn->prepare("INSERT INTO permissions (name, display_name, description, module) VALUES (?, ?, ?, ?)");
$stmt->bind_param($types, ...$vals);

if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Database error while saving: ' . $stmt->error);
}
$newId = $conn->insert_id;
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'create_permission', 'permission', $newId, null, json_encode(['name' => $name, 'module' => $module]));

Api::success(['id' => $newId, 'message' => "Permission \"$name\" was created successfully."], [], 201);
