<?php
// index.php
// Main entry point for the LMS prototype.

// Use output buffering to prevent header errors, especially with sessions/redirects.
ob_start();

// Ensure session is started at the very beginning.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 🟢 STEP 1: INCLUDE PERSISTENT LOGIN CHECK (CRUCIAL FIX)
// This script will check for the 'persistent_login' cookie. 
// If found and valid, it sets the session, rotates the token, and performs an 
// IMMEDIATE REDIRECT (with exit()), bypassing the rest of this router file.
require_once 'check_persistent_login.php'; 


// --- CONFIGURATION: Define the page mappings for each user role ---
$page_mappings = [
    'guest' => [
        'home',
        'login',
        'register',
        'register_admin',
        '404' // Allow everyone to see the 404 page
    ],
    'student' => [
        'student_dashboard',
        'student_profile',
        'edit_student_profile',
        'my_courses',
        'course_schedule_details',
        'my_monthly_payments',
        'submit_payment_page',
        'submit_monthly_payment_page',
        'notifications',
        'mark_as_read',
        'enrollment_request',
        'course_batches',
    ],
    'admin' => [
        'admin_dashboard',
        'admin_course_batches',
        'admin_landing',
        'admin_verify_payments',
        'admin_financial_dashboard',
        'admin_financial_report_print',
        'register_user',
        'create_course',
        'create_batch',
        'manage_batches',
        'edit_batch',
        'delete_batch',
        'edit_user',
        'delete_user',
        'batch_details',
        'manage_enrollments',
        'enrollment_verification', // This is a VIEW page
        'enrollment_verification_logic',
        'create_schedule',
        'manage_course_schedule',
        'create_batch_schedule',
        'manage_batch_schedule',
        'manage_users', 
        'manage_courses', 
        'edit_course', 
        'delete_course', 
    ],
    'instructor' => [
        'admin_dashboard', // Instructors use the admin dashboard as their main hub
        'create_course',
        'create_batch',
        'manage_batches',
        'edit_batch', // Allow instructor to edit their own batches
        'batch_details',
        'manage_enrollments',
        'enrollment_verification', // This is a VIEW page
        'create_schedule',
        'manage_course_schedule',
        'create_batch_schedule',
        'manage_batch_schedule',
    ]
];

// --- INITIALIZATION AND AUTHENTICATION LOGIC ---
$page = $_GET['page'] ?? 'home';
// Re-initialize these variables as the persistent check might have changed the session.
$is_logged_in = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true; 
$user_role = $_SESSION['user_role'] ?? 'guest';

// Handle logout separately since it's a global action.
if ($page === 'logout') {
    include 'logout.php';
    exit();
}

// Redirect logged-in users from public pages to their respective dashboards.
// This check now acts as a fallback if the persistent check didn't already redirect.
if ($is_logged_in && in_array($page, ['home', 'login', 'register', 'register_admin'])) {
    if ($user_role === 'student') {
        header("Location: index.php?page=student_dashboard");
    } else { // admin or instructor
        header("Location: index.php?page=admin_dashboard");
    }
    exit();
}

// Handle action-based pages (like delete, mark as read) that perform logic and redirect.
$action_pages = ['mark_as_read', 'delete_course', 'delete_batch', 'delete_user']; 
if (in_array($page, $action_pages)) {
    // These files handle their own logic and redirection.
    $file_path = "$page.php";
    if (file_exists($file_path)) {
        include $file_path;
        exit(); // Exit immediately after running a redirecting action script
    }
    // If the action file is missing, execution continues to the 404 check below.
}

// --- PERMISSION CHECK ---
$is_valid_page = false;

// 1. Check if the page is in the current user's role mapping
if (isset($page_mappings[$user_role]) && in_array($page, $page_mappings[$user_role])) {
    $is_valid_page = true;
} 
// 2. Check if the page is a global public page (guest)
elseif (in_array($page, $page_mappings['guest'])) {
    $is_valid_page = true;
}


// --- REDIRECTION LOGIC ---

// If the page is invalid, redirect to the appropriate dashboard/login page.
if (!$is_valid_page) {
    if ($is_logged_in) {
        // Redirect to user's dashboard if logged in
        $redirect_page = $user_role === 'student' ? 'student_dashboard' : 'admin_dashboard';
        $_SESSION['message'] = "Access denied: You do not have permission to view '$page'.";
        $_SESSION['is_error'] = true;
        header("Location: index.php?page=$redirect_page");
    } else {
        // Redirect to login if not logged in
        header("Location: index.php?page=login");
    }
    exit();
}


// --- CONTENT INCLUSION AND TEMPLATE LOGIC ---

// Pages that should not use the header/footer template (e.g., printable reports)
$no_template_pages = ['admin_financial_report_print'];
$is_special_page = in_array($page, $no_template_pages);

if (!$is_special_page) {
    require_once 'includes/header.php';
}

// Include the selected page content.
$file_path = "$page.php";
if (file_exists($file_path)) {
    include $file_path;
} else {
    // Fallback to 404 page if the file is missing
    include '404.php'; 
}

if (!$is_special_page) {
    require_once 'includes/footer.php';
}

ob_end_flush();
?>