<?php
// =============================================================
//  POST /api/v1/admin_rbac/roles_create
//
//  Wraps app/roles.php's create_role handler field-for-field: same
//  name-format expectations (letters/underscores only, enforced here
//  server-side since there's no HTML pattern= attribute on mobile),
//  same case-sensitive duplicate check on the system name, same
//  is_system = 0 (custom roles only — system roles are seeded by the
//  installer, never created here or there).
//
//  Body: { "role_name": "Clinical_Instructor", "display_name": "Clinical Instructor", "description": "..." }
// =============================================================

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

if ($roleName === '' || $displayName === '') {
    Api::error(422, 'ValidationError', "Both 'Role Name' and 'Display Name' are required to create a role.");
}
if (!preg_match('/^[A-Za-z_]+$/', $roleName)) {
    Api::error(422, 'ValidationError', 'Role Name must use only letters and underscores — no spaces or numbers.');
}

$check = $conn->prepare("SELECT id FROM roles WHERE name = ?");
$check->bind_param('s', $roleName);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    Api::error(409, 'DuplicateRole', "A role named \"$roleName\" already exists. Please choose a different name.");
}
$check->close();

$types = 'sss';
$vals  = [$roleName, $displayName, $description];
if (strlen($types) !== count($vals)) {
    error_log('roles_create.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the role record.');
}

$stmt = $conn->prepare("INSERT INTO roles (name, display_name, description, is_system, created_at) VALUES (?, ?, ?, 0, NOW())");
$stmt->bind_param($types, ...$vals);

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

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'create_role', 'role', $newId, null, json_encode(['role_name' => $roleName, 'display_name' => $displayName]));

Api::success(['id' => $newId], [], 201);
