<?php

// Extract the page from the URL
$requestUri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
$segments = explode('/', $requestUri);
$page = end($segments);

// Handle logout before rendering anything
if ($page === 'logout') {
    session_unset();
    session_destroy();
    header("Location: ../login.php");
    exit;
}

// Set default page if URL is /admin or empty
if ($page === 'portal' || $page === '') {
    $page = 'dashboard'; // default fallback page
}

$pageFile = __DIR__ . "/pages/{$page}.php";

// DEBUG INFO — You can comment this out later
// echo "<pre>";
// echo "Request URI: " . $_SERVER['REQUEST_URI'] . "\n";
// echo "Parsed Page: " . $page . "\n";
// echo "Looking for: pages/{$page}.php\n";
// echo "Full Path: {$pageFile}\n";
// echo "</pre>";

// Include header
include 'header.php';
include 'check_permission.php';

// Include the page if it exists
if (file_exists($pageFile)) {
   
    require $pageFile;
} else {
    echo "<h3 style='color:red;'>404 - Page '{$page}' Not Found</h3>";
}

// Include footer
include 'footer.php';
?>
