<?php
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path_parts = pathinfo($uri);

// ==================================================================
//  DIE NEUE, KUGELLSICHERE LOGIK
// ==================================================================

// REGEL 1: Wenn die Anfrage eine Dateiendung hat (.css, .js, .png etc.)
if (isset($path_parts['extension'])) {
    $file_path = __DIR__ . $uri;
    if (file_exists($file_path)) {
        // Finde den richtigen Content-Type für die Datei
        $mime_type = mime_content_type($file_path);
        header("Content-Type: $mime_type");
        // Lese die Datei und sende sie an den Browser
        readfile($file_path);
        exit; // Beende das Skript sofort
    }
}

// REGEL 2: Wenn die Anfrage mit /admin/ beginnt (und KEINE Datei ist)
if (strpos($uri, '/admin/') === 0) {
    // Finde die Zieldatei im Admin-Ordner
    $admin_target = __DIR__ . $uri;
    // Wenn es ein Verzeichnis ist, lade die index.php darin
    if (is_dir($admin_target)) {
        $admin_target = rtrim($admin_target, '/') . '/index.php';
    }
    // Wenn die Datei existiert, lade sie und beende
    if (file_exists($admin_target)) {
        require_once $admin_target;
        exit;
    }
}

// ==================================================================
//  DEINE BEKANNTE LOGIK FÜR DIE NORMALE WEBSEITE
//  (Wird nur ausgeführt, wenn die oberen Regeln nicht zutreffen)
// ==================================================================

$parts = explode('/', trim($uri, '/'));
$lang = $parts[0] ?? '';
$supported_langs = ['de', 'en'];
$default_lang = 'de';

if ($lang === '') {
    header("Location: /{$default_lang}/", true, 301);
    exit;
}
if (!in_array($lang, $supported_langs)) {
    http_response_code(404);
    echo "404 - Not Found (Language not supported)";
    exit;
}

$content_file = 'content/content.json';
$page_content = [];
$payment_methods_config = [];

if (file_exists($content_file)) {
    $json_data = file_get_contents($content_file);
    $all_content = json_decode($json_data, true);
    $page_content = $all_content[$lang] ?? [];
    $payment_methods_config = $all_content['payment_methods'] ?? [];
}

function loadContentWithBreaks($filepath) {
    if (file_exists($filepath)) {
        $text = file_get_contents($filepath);
        // nl2br fügt <br> ein, lässt aber HTML-Tags in Ruhe
        return nl2br($text);
    }
    return "";
}

// Wir laden den Inhalt nun direkt in Variablen, statt nur den Pfad zu speichern
$impressum_content   = loadContentWithBreaks("content/impressum.{$lang}.html");
$datenschutz_content = loadContentWithBreaks("content/datenschutz.{$lang}.html");
$agb_content         = loadContentWithBreaks("content/agb.{$lang}.html");

require_once 'template.php';
?>
