<?php

function hasPermission($perm): bool {
    global $pdo;

    if (!isset($_SESSION["user"]) || !isset($_SESSION["user"]["role_id"])) {
        return false;
    }

    $roleId = (int)$_SESSION["user"]["role_id"];
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM role_permissions rp
        JOIN permissions p ON rp.permission_id = p.id
        WHERE rp.role_id = ? AND p.name = ?
    ");
    $stmt->execute([$roleId, $perm]);

    return ((int)$stmt->fetchColumn()) > 0;
}

function requirePermission($perm, $asJson = true): void {
    if (!hasPermission($perm)) {
        if ($asJson) {
            http_response_code(403);
            header("Content-Type: application/json; charset=utf-8");
            echo json_encode(["success" => false, "error" => "forbidden"]);
        } else {
            http_response_code(403);
            echo "Forbidden";
        }
        exit;
    }
}
