<?php
// school_admission/includes/auth_check.php

// Prevent direct access to this file
if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
    die("Access denied!");
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Function to check if a user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Function to check if a user has a specific role
function hasRole($required_role) {
    return isset($_SESSION['role']) && $_SESSION['role'] === $required_role;
}

// Function to check if a user has one of the specified roles
function hasAnyRole($required_roles = []) {
    // Ensure user is logged in first
    if (!isLoggedIn()) {
        return false;
    }
    // Check if the user's role is in the list of allowed roles
    return in_array($_SESSION['role'], $required_roles);
}


// Redirect to login if not logged in
function requireLogin() {
    if (!isLoggedIn()) {
        redirect('login.php'); // Redirect to the direct login file
    }
}

// Redirect to forbidden page if role is not allowed
function requireRole($allowed_roles = []) {
    if (!isLoggedIn()) {
        redirect('login.php'); // Redirect to the direct login file
    }
    if (!hasAnyRole($allowed_roles)) {
        redirect('forbidden.php'); // Redirect to the direct forbidden file
    }
}

// --- Diagnostic Line (Can be removed after fix) ---
// error_log("auth_check.php has been loaded successfully and functions defined!");
?>