<?php
// Enable errors for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Base path
define('BASE_PATH', dirname(__DIR__));

// Autoload for phpdotenv and other packages
require BASE_PATH . '/vendor/autoload.php';

// Load environment variables
$dotenv = Dotenv\Dotenv::createImmutable(BASE_PATH);
$dotenv->load();

$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if ($requestUri !== '/' && str_ends_with($requestUri, '/')) {
    $cleanedUri = rtrim($requestUri, '/');
    header("Location: $cleanedUri", true, 301);
    exit;
}

$routeKey = "{$requestMethod} {$requestUri}";

$routes = require BASE_PATH . '/routes/web.php';

if (isset($routes[$routeKey])) {
    $handler = $routes[$routeKey];
    if (is_callable($handler)) {
        $handler();
        exit;
    }

    require BASE_PATH . '/views/pages/' . $handler;
    exit;
}

// Not Found fallback
http_response_code(404);
echo "<h1>404 Not Found</h1><p>No route defined for <code>$requestUri</code></p>";
