<?php
/**
 * PHP Built-in Server Router
 * Routes all requests to the public/ directory while handling URL rewrites.
 */

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

// Serve static assets directly
if (preg_match('/\.(css|js|png|jpg|jpeg|gif|ico|woff|woff2|ttf|svg)$/', $uri)) {
    $file = __DIR__ . $uri;
    if (file_exists($file)) {
        return false; // Let the server handle it
    }
}

// Map URI to public/ directory
$publicDir = __DIR__ . '/public';

// Strip leading slash
$path = ltrim($uri, '/');

// Default to index.php
if ($path === '' || $path === '/') {
    $path = 'index.php';
}

// Resolve to public file
$file = $publicDir . '/' . $path;

// If exact file exists, include it
if (file_exists($file) && !is_dir($file)) {
    // Set document root context for includes
    $_SERVER['DOCUMENT_ROOT'] = $publicDir;
    chdir($publicDir);
    include $file;
    return;
}

// Try adding .php extension
if (file_exists($file . '.php')) {
    $_SERVER['DOCUMENT_ROOT'] = $publicDir;
    chdir($publicDir);
    include $file . '.php';
    return;
}

// 404
http_response_code(404);
echo '404 Not Found';