<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* STRICT ROOT CONTROL */
if ($user['role'] !== 'super_admin') {
    json_response(false, 'Access denied.', [], 403);
}

/* RBAC */
require_permission($user, 'rsps', 'create', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['name'])) {
    json_response(false, 'RSP name required.', [], 400);
}

$name = trim($input['name']);

/* VALIDATION */
if (strlen($name) < 3 || strlen($name) > 100) {
    json_response(false, 'RSP name must be between 3 and 100 characters.', [], 400);
}

/* NORMALIZE */
$normalized = strtolower($name);

/* DUPLICATE CHECK */
$stmt = $pdo->prepare("
    SELECT id 
    FROM rsps 
    WHERE LOWER(name) = ?
    LIMIT 1
");
$stmt->execute([$normalized]);

if ($stmt->fetch()) {
    json_response(false, 'RSP with this name already exists.', [], 409);
}

$pdo->beginTransaction();

try {

    $stmt = $pdo->prepare("
        INSERT INTO rsps (name, status, created_at)
        VALUES (?, 'active', NOW())
    ");

    $stmt->execute([$name]);

    $rsp_id = (int)$pdo->lastInsertId();

    /* AUDIT */
    log_admin_action(
        $pdo,
        (int)$user['id'],
        'rsps',
        'create',
        $rsp_id
    );

    $pdo->commit();

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, 'Failed to create RSP.', [], 500);
}

/* RESPONSE */
json_response(true, 'RSP created successfully.', [
    'rsp_id' => $rsp_id,
    'name'   => $name
]);