<?php
/**
 * GeoGraSim — Front Controller
 * Alle Requests laufen ueber diese Datei (via .htaccess Rewrite).
 */

require_once __DIR__ . '/php/config/app.php';
require_once __DIR__ . '/php/lib/Database.php';
require_once __DIR__ . '/php/lib/Session.php';
require_once __DIR__ . '/php/lib/Response.php';
require_once __DIR__ . '/php/templates/_scripts.php';

Session::start();

// Request-Pfad parsen
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$basePath = BASE_PATH;
$path = parse_url($requestUri, PHP_URL_PATH);

// Base-Path entfernen
if (strpos($path, $basePath) === 0) {
    $path = substr($path, strlen($basePath));
}
$path = trim($path, '/');
if ($path === '') $path = 'index';

// API-Routen
if (strpos($path, 'api/') === 0) {
    $apiFile = preg_replace('/[^a-z0-9\-]/', '', substr($path, 4));
    $apiPath = __DIR__ . '/php/api/' . $apiFile . '.php';
    if (file_exists($apiPath)) {
        require $apiPath;
        exit;
    }
    Response::error('API-Endpunkt nicht gefunden', 404);
}

// Seiten-Routen
$page = preg_replace('/[^a-z0-9\-]/', '', $path);
$pageFile = __DIR__ . '/pages/' . $page . '.php';

if (file_exists($pageFile)) {
    require $pageFile;
    exit;
}

// Fallback: Original HTML-Dateien (Uebergangsphase)
$htmlFile = __DIR__ . '/' . $page . '.html';
if (file_exists($htmlFile)) {
    readfile($htmlFile);
    exit;
}

// 404
http_response_code(404);
echo '<!DOCTYPE html><html><body><h1>404 — Seite nicht gefunden</h1><p><a href="' . BASE_PATH . '/">Zur&uuml;ck zur Startseite</a></p></body></html>';
