<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 1. Check if logged in
if (!isset($_SESSION['user_id'])) {
    // Redirect to login (assuming this file is included from a subfolder like /admin/)
    header("Location: ../login.php"); 
    exit();
}

// 2. Role & Path Security
$current_path = $_SERVER['PHP_SELF'];
$role = isset($_SESSION['role']) ? $_SESSION['role'] : '';

// --- SECURITY FOR ADMIN FOLDER ---
if (strpos($current_path, '/admin/') !== false) {
    
    // CASE A: Support User
    if ($role === 'support') {
        // Only allow access to support.php
        if (basename($current_path) !== 'support.php') {
            // If they try to access dashboard or users, force them back to support
            header("Location: support.php");
            exit();
        }
        // If it IS support.php, let them pass
        return;
    }

    // CASE B: Agent User (Trying to access Admin)
    if ($role === 'agent') {
        header("Location: ../agent/index.php");
        exit();
    }

    // CASE C: Player User (Trying to access Admin)
    if ($role === 'player') {
        header("Location: ../index.php");
        exit();
    }

    // CASE D: Admin User
    if ($role === 'admin') {
        // Allowed everywhere in /admin/
        return;
    }

    // Default Deny for unknown roles
    header("Location: ../login.php");
    exit();
}

// --- SECURITY FOR AGENT FOLDER ---
if (strpos($current_path, '/agent/') !== false) {
    
    // Only Agents allowed
    if ($role !== 'agent') {
        // If Admin, maybe redirect to Admin Dashboard
        if ($role === 'admin') {
            header("Location: ../admin/dashboard.php");
            exit();
        }
        // Support or Players -> Redirect to Player Index
        header("Location: ../index.php");
        exit();
    }
}
?>