<?php
/**
 * ===================================================================================
 * Admin Helper Functions (Corrected)
 * ===================================================================================
 *
 * File: admin_helpers.php
 * Location: /homework_portal/admin/admin_helpers.php
 *
 * Purpose:
 * 1. Contains corrected, reusable functions for the admin portal.
 * 2. The check_permission function now reliably uses session data.
 */

// This function must be called at the top of every secure admin page.
function check_permission($required_permission) {
    // First, ensure the user is logged in at all.
    if (!isset($_SESSION['admin_id'])) {
        header('Location: login.php');
        exit();
    }

    // A super_admin (from session) has access to everything.
    if (isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin'] === true) {
        return; // Access granted
    }

    // For a sub_admin, check if their permissions array (from session) contains the required permission.
    if (isset($_SESSION['admin_permissions']) && in_array($required_permission, $_SESSION['admin_permissions'])) {
        return; // Access granted
    }

    // If neither condition is met, deny access.
    header('Location: dashboard.php?error=Access Denied. You do not have permission to view that page.');
    exit();
}

// This function can be used to selectively show/hide links and buttons in the UI.
function has_permission($key) {
    if (isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin']) {
        return true; 
    }
    if (isset($_SESSION['admin_permissions']) && is_array($_SESSION['admin_permissions']) && in_array($key, $_SESSION['admin_permissions'])) {
        return true;
    }
    return false;
}
?>
