<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once("public/connection.php");
require_once("public/functions.php");

// 1. Inactivity Session Timeout (30 minutes)
$timeout_duration = 1800;
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: ../index.php?timeout=1");
    exit();
}
$_SESSION['last_activity'] = time();

// 2. Ensure role is set
if (!isset($_SESSION['role'])) {
    header("Location: ../index.php");
    exit();
}

$role_id = (int)($_SESSION['role'] ?? 0);
$request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$current_page = basename($request_path);
$current_page = preg_replace('/\.php$/i', '', $current_page);

// Exclude static assets or non-page requests
$path_ext = strtolower(pathinfo($request_path, PATHINFO_EXTENSION));
if (!empty($path_ext) && $path_ext !== 'php') {
    return;
}

// Extract module action if routed through modules.php or teacher_dashboard.php
if (in_array(strtolower($current_page), ['modules', 'teacher_dashboard'])) {
    if (!empty($_SERVER['QUERY_STRING'])) {
        $query_keys = array_keys($_GET);
        if (!empty($query_keys) && !empty($query_keys[0])) {
            $candidate_page = preg_replace('/[^a-zA-Z0-9_-]/', '', $query_keys[0]);
            if (!empty($candidate_page)) {
                $current_page = $candidate_page;
            }
        }
    }
}

// Pages that never require permission checks
$exclude_pages = ['admin', 'dashboard', 'index', 'portal', 'logout', 'modules', 'teacher_dashboard', 'download_student_template', 'export_students_excel', ''];

// Skip permission check for excluded pages
if (!in_array(strtolower($current_page), $exclude_pages)) {

    // Get role name
    $stmt_role = $connection->prepare("SELECT role_name FROM role WHERE id = ?");
    $stmt_role->bind_param("i", $role_id);
    $stmt_role->execute();
    $stmt_role->bind_result($role_name);
    $stmt_role->fetch();
    $stmt_role->close();

    $role_lower = strtolower(trim($role_name ?? ''));

    // Skip permission check for Super Admin, Proprietor, Director, and Administrators
    $is_admin_user = (
        $role_id === 11 ||
        $role_id === 3 ||
        $role_id === 1 || 
        $role_id === 2 || 
        strpos($role_lower, 'super') !== false || 
        strpos($role_lower, 'director') !== false || 
        strpos($role_lower, 'proprietor') !== false || 
        strpos($role_lower, 'admin') !== false ||
        $role_lower === 'administrator'
    );

    if (!$is_admin_user) {
        $stmt = $connection->prepare("
            SELECT 1 FROM role_permissions 
            JOIN permissions ON role_permissions.permission_id = permissions.id 
            WHERE role_permissions.role_id = ? AND permissions.permission_name = ?
        ");
        $stmt->bind_param("is", $role_id, $current_page);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $_SESSION['msg'] = "Access denied: You do not have permission to access the '{$current_page}' page.";
            $_SESSION['type'] = "error";
            $redirect_dest = (strpos($role_lower, 'teacher') !== false) ? "teacher_dashboard.php" : "dashboard.php";
            header("Location: {$redirect_dest}");
            exit();
        }

        $stmt->close();
    }
}
?>

