<?php

/**
 * Global helper function to check user permissions.
 * 
 * @param string $permission The permission name (e.g., 'leagues:create')
 * @return bool True if the user has the permission, false otherwise.
 */
function hasPermission($permission) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_id'])) {
        return false;
    }

    // Request-level caching to prevent redundant DB queries
    static $cache = [];
    $user_id = $_SESSION['user_id'];
    $key = $user_id . '|' . $permission;

    if (isset($cache[$key])) {
        return $cache[$key];
    }

    $permissionModel = new Permission();
    $result = $permissionModel->userHasPermission($user_id, $permission);
    
    $cache[$key] = $result;
    return $result;
}

/**
 * Enforce a permission requirement. Redirects if permission is missing.
 * 
 * @param string $permission The permission name
 * @param string $redirectUrl URL to redirect to on failure (default: dashboard.php)
 */
function requirePermission($permission, $redirectUrl = 'dashboard.php') {
    if (!hasPermission($permission)) {
        $_SESSION['flash_error'] = 'You do not have permission to access this page.';
        header("Location: $redirectUrl");
        exit();
    }
}