<?php

/**
 * Check if the current user has a specific permission.
 * 
 * @param string $permission The permission key (e.g., 'leagues:view')
 * @return bool
 */
function hasPermission($permission) {
    // Ensure session is started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

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

    // Super Admin Bypass
    if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'super_admin') {
        return true;
    }

    // Cache permissions in session if not present
    if (!isset($_SESSION['user_permissions'])) {
        $permissionModel = new Permission();
        $_SESSION['user_permissions'] = $permissionModel->getUserPermissions($_SESSION['user_id']);
    }

    return in_array($permission, $_SESSION['user_permissions']);
}

/**
 * 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();
    }
}