<?php

/**
 * Permission system for:
 * full  = full access
 * view  = read-only
 * none  = blocked
 *
 * Master admin always has full access.
 */

function requirePermission($pageKey, $mode = 'full') {
    // Load master admin
    $master = include __DIR__ . '/../config/master_admin.php';

    // If master admin is logged in → always allow
    if (isset($_SESSION['user']) && $_SESSION['user'] === $master['username']) {
        return;
    }

    // Load user roles from session
    $roles = $_SESSION['roles'] ?? [];

    // If page not defined → block
    if (!isset($roles[$pageKey])) {
        denyAccess();
    }

    $level = $roles[$pageKey];

    /**
     * FULL MODE CHECK
     * - "full" required
     * - "view" is NOT enough
     * - "none" is blocked
     */
    if ($mode === 'full') {
        if ($level !== 'full') {
            denyAccess();
        }
        return;
    }

    /**
     * VIEW MODE CHECK
     * - "full" allowed
     * - "view" allowed
     * - "none" blocked
     */
    if ($mode === 'view') {
        if ($level === 'none') {
            denyAccess();
        }
        return;
    }

    // If mode unknown → block
    denyAccess();
}

/**
 * Helper: Block access with a clean message
 */
function denyAccess() {
    echo "<div class='content-box center-text'>
            <h2>Access Denied</h2>
            <p>You do not have permission to access this page.</p>
          </div>";
    include __DIR__ . '/footer.php';
    exit;
}
