<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// router.php

// Get the requested URI and parse it to remove the query string
$requestUri = $_SERVER['REQUEST_URI'];
$requestPath = parse_url($requestUri, PHP_URL_PATH);

// Get the absolute path of the project root
$projectRoot = __DIR__;

// Handle the root path request (e.g., http://localhost:8000/)
if ($requestPath === '/') {
    if (file_exists($projectRoot . '/index.phtml')) {
        require_once $projectRoot . '/index.phtml';
        exit;
    }
}

// Prevent directory traversal attacks by checking for '..'
if (strpos($requestPath, '..') !== false) {
    http_response_code(400); // Bad Request
    echo "<h1>400 Bad Request</h1>";
    echo "<p>Invalid request path.</p>";
    exit;
}

// Construct the potential file path by removing the leading slash
$filePath = ltrim($requestPath, '/');

// Define the potential file extensions
$potentialFiles = [
    $projectRoot . '/' . $filePath . '.phtml',
    $projectRoot . '/' . $filePath . '.php',
    $projectRoot . '/' . $filePath . '.html',
    $projectRoot . '/' . $filePath // Also check for direct file match without extension
];

// Check if a file exists and serve it
foreach ($potentialFiles as $file) {
    // Use realpath to resolve the absolute path and prevent security issues
    $realFilePath = realpath($file);

    // Ensure the resolved path is within the project directory
    if ($realFilePath && strpos($realFilePath, $projectRoot) === 0 && is_file($realFilePath)) {
        // Determine the file's extension to set the correct content type
        $extension = pathinfo($realFilePath, PATHINFO_EXTENSION);

        if ($extension === 'php' || $extension === 'phtml') {
            // Execute PHP and PHTML files
            require_once $realFilePath;
        } else {
            // Serve other files (like .html) with the appropriate MIME type
            $mimeType = mime_content_type($realFilePath);
            header("Content-Type: " . $mimeType);
            readfile($realFilePath);
        }
        exit;
    }
}

// If no file was found, return a 404 response
http_response_code(404);
if (file_exists($projectRoot . '/404-error.html')) {
    readfile($projectRoot . '/404-error.html');
} else {
    echo "<h1>404 Not Found</h1>";
    echo "<p>The requested page was not found.</p>";
}

