<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Initialize session state storage mapping securely
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// --- LOGIC: GLOBAL LOGOUT TERMINAL PROCESSOR ---
if (isset($_GET['logout']) && $_GET['logout'] === 'true') {
    // Completely wipe out all tracking tokens
    $_SESSION = array();
    
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    
    session_destroy();
    header("Location: login.php");
    exit;
}

// --- LOGIC: SECURITY TRAFFIC ROUTER ---
if (isset($_SESSION['role'])) {
    $role = $_SESSION['role'];

    // Map permission tiers straight to their working environments
    if ($role === 'Admin') {
        header("Location: admin/dashboard.php");
        exit;
    } elseif ($role === 'Scheduler') {
        header("Location: scheduler/dashboard.php");
        exit;
    } elseif ($role === 'Editor') {
        header("Location: editor/dashboard.php");
        exit;
    }
}

// Fallback: If no security session matches, lock them behind the gatekeeper login
header("Location: login.php");
exit;
?>