<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function require_right($right_name) {
    global $conn;

    if (!isset($_SESSION['role_id'])) {
        show_access_denied("Not logged in.");
    }

    $role_id = $_SESSION['role_id'];

    $query = $conn->prepare("
        SELECT 1 FROM role_rights 
        JOIN rights ON role_rights.right_id = rights.id 
        WHERE role_rights.role_id = ? AND LOWER(rights.name) = LOWER(?)
        LIMIT 1
    ");
    $query->bind_param("is", $role_id, $right_name);
    $query->execute();
    $query->store_result();

    if ($query->num_rows === 0) {
        show_access_denied("You don't have access to this page.");
    }
}

function show_access_denied($message) {
    echo <<<HTML
<!DOCTYPE html>
<html>
<head>
    <title>Access Denied</title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }
        .access-denied-box {
            padding: 40px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="access-denied-box">
        <h2>Access Denied</h2>
        <p>{$message}</p>
        <a href="index.php" class="btn btn-primary mt-3">Back to Dashboard</a>
    </div>
</body>
</html>
HTML;
    exit;
}
