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

if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}

if (!function_exists('admin_role')) {

function admin_role(): string {
    return $_SESSION['admin']['role'] ?? 'admin';
}

function is_admin_role(): bool {
    return admin_role() === 'admin';
}

/** Staff may scan/redeem/view; only admin may manage vouchers, users, branding. */
function require_admin_role(): void {
    if (is_admin_role()) {
        return;
    }

    $isJson = !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
        && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    $wantsJson = $isJson
        || (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false);

    http_response_code(403);
    if ($wantsJson) {
        header('Content-Type: application/json');
        die(json_encode(['success' => false, 'error' => 'Admin access required.']));
    }

    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
        . '<title>Access denied</title></head><body style="font-family:system-ui,sans-serif;max-width:420px;margin:48px auto;padding:0 20px;text-align:center">'
        . '<h1 style="font-size:1.25rem">Access denied</h1>'
        . '<p>Your account does not have permission for this action. Contact an administrator.</p>'
        . '<p><a href="dashboard.php">Back to dashboard</a></p>'
        . '</body></html>';
    exit;
}

}
