<?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") {
    $rows = $pdo->query("SELECT role_id, permission_id FROM role_permissions")->fetchAll(PDO::FETCH_ASSOC);
    $data = [];
    foreach ($rows as $r) {
        $rid = (int)$r["role_id"];
        $pid = (int)$r["permission_id"];
        if (!isset($data[$rid])) $data[$rid] = [];
        $data[$rid][] = $pid;
    }
    echo json_encode(["success" => true, "data" => $data]);
    exit;
}

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

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

$roleId = (int)($payload["role_id"] ?? 0);
$permissionId = (int)($payload["permission_id"] ?? 0);
$grant = !empty($payload["grant"]);

if ($roleId <= 0 || $permissionId <= 0) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_payload"]);
    exit;
}

// Moderator restriction: cannot have manage_users
if ($roleId === 5) {
    $permStmt = $pdo->prepare("SELECT name FROM permissions WHERE id = ? LIMIT 1");
    $permStmt->execute([$permissionId]);
    $permName = (string)$permStmt->fetchColumn();
    if ($permName === "manage_users" && $grant) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "moderator_cannot_manage_users"]);
        exit;
    }
}

$pdo->beginTransaction();
try {
    if ($grant) {
        $ins = $pdo->prepare("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        $ins->execute([$roleId, $permissionId]);
    } else {
        $del = $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?");
        $del->execute([$roleId, $permissionId]);
    }
    $pdo->commit();
    echo json_encode(["success" => true]);
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(["success" => false, "error" => "server_error"]);
}
?>
