<?php

declare(strict_types=1);

// php -S Router-Modus: existierende Dateien (Assets) direkt ausliefern.
if (PHP_SAPI === 'cli-server') {
    $file = __DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    if (is_file($file)) {
        return false;
    }
}

require dirname(__DIR__) . '/app/bootstrap.php';

$path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);

// Kanonisch ohne trailing slash (Root ausgenommen).
if ($path !== '/' && str_ends_with($path, '/')) {
    $query = $_SERVER['QUERY_STRING'] ?? '';
    header('Location: ' . rtrim($path, '/') . ($query !== '' ? '?' . $query : ''), true, 301);
    exit;
}

$slug = trim($path, '/');

// Formular-Submits.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $slug === 'kontakt-senden') {
    require APP_PATH . '/actions/contact-submit.php';
    exit;
}

$routes = require APP_PATH . '/routes.php';

// Sitemap aus dem Routen-Register generieren.
if ($slug === 'sitemap.xml') {
    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    foreach ($routes as $routeSlug => $route) {
        if (empty($route['sitemap'])) {
            continue;
        }
        $lastmod = date('Y-m-d', (int) filemtime(APP_PATH . '/pages/' . $route['file']));
        echo "  <url><loc>" . e(abs_url($routeSlug)) . "</loc><lastmod>{$lastmod}</lastmod></url>\n";
    }
    echo '</urlset>';
    exit;
}

if (isset($routes[$slug]) && $slug !== '404') {
    $current = $slug;
} else {
    http_response_code(404);
    $current = '404';
}

[$meta, $content] = render_page(APP_PATH . '/pages/' . $routes[$current]['file']);

require APP_PATH . '/layout.php';
