<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/csrf.php";
require_once "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");

requireApiAuth();

$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);
if (!hasPermission("manage_users") && $roleId !== 5) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "forbidden"]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "GET") {
    $stmt = $pdo->query("SELECT p.id, p.name, COUNT(rp.role_id) as roles_count FROM permissions p LEFT JOIN role_permissions rp ON p.id = rp.permission_id GROUP BY p.id ORDER BY p.name");
    echo json_encode(["success" => true, "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_allowed"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true) ?: [];
if (!requireCsrfFromPayload($data)) {
    http_response_code(419);
    echo json_encode(["success" => false, "error" => "csrf_failed"]);
    exit;
}

$action = trim((string)($data["action"] ?? ""));
$name = trim((string)($data["name"] ?? ""));
$permId = (int)($data["permission_id"] ?? 0);

$pdo->beginTransaction();
try {
    if ($action === 'delete') {
        if ($permId <= 0) {
            throw new Exception("invalid_permission");
        }
        $pdo->prepare("DELETE FROM role_permissions WHERE permission_id = ?")->execute([$permId]);
        $pdo->prepare("DELETE FROM permissions WHERE id = ?")->execute([$permId]);
        $pdo->commit();
        echo json_encode(["success" => true]);
        exit;
    }

    // add permission
    if (strlen($name) < 3 || strlen($name) > 50) {
        throw new Exception("invalid_name");
    }

    $ins = $pdo->prepare("INSERT INTO permissions (name) VALUES (?)");
    $ins->execute([$name]);
    $pdo->commit();
    echo json_encode(["success" => true, "data" => ["permission_id" => $pdo->lastInsertId()]]);
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(422);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
?>

