<?php
// ═══════════════════════════════════════════════════════════════════════════
// Router — Johannes Wurfbaum Coaching
// Handles clean URLs via .htaccess rewrite
// ═══════════════════════════════════════════════════════════════════════════

require_once __DIR__ . '/api/helpers.php';

$path = getCurrentPath();

// ── API Routes ────────────────────────────────────────────────────────────────
if (str_starts_with($path, '/api/')) {
    $endpoint = substr($path, 5);
    // Spezialfälle mit Bindestrich im Namen
    if ($endpoint === 'stripe-webhook') {
        require __DIR__ . '/api/stripe_webhook.php';
        exit;
    }
    if ($endpoint === 'smtp-test') {
        require __DIR__ . '/api/smtp_test_api.php';
        exit;
    }
    if ($endpoint === 'stripe-test') {
        require __DIR__ . '/api/stripe_test.php';
        exit;
    }
    $file = __DIR__ . '/api/' . basename($endpoint) . '.php';
    if (file_exists($file)) {
        require $file;
    } else {
        jsonResponse(['error' => 'Not found'], 404);
    }
    exit;
}

// ── Admin Routes ──────────────────────────────────────────────────────────────
if (str_starts_with($path, '/admin')) {
    require __DIR__ . '/_admin/router.php';
    exit;
}

// ── Public Routes ─────────────────────────────────────────────────────────────
$routes = [
    '/'          => 'main',
    '/coaching'  => 'coaching',
    '/impressum' => 'legal',
    '/datenschutz' => 'legal',
    '/agb'       => 'legal',
    '/widerruf'  => 'legal',
    '/danke'     => 'danke',
];

$template = $routes[$path] ?? null;

if ($template === null) {
    http_response_code(404);
    $template = '404';
}

// Determine legal page ID
$legalId = match($path) {
    '/impressum'   => 'impressum',
    '/datenschutz' => 'datenschutz',
    '/agb'         => 'agb',
    '/widerruf'    => 'widerruf',
    default        => null,
};

$settings = getAllSettings();

// ── Render ────────────────────────────────────────────────────────────────────
$tplFile = __DIR__ . '/templates/' . $template . '.php';
if (file_exists($tplFile)) {
    require $tplFile;
} else {
    http_response_code(404);
    echo '<!DOCTYPE html><html><body><h1>404 — Seite nicht gefunden</h1><a href="/">Zurück zur Startseite</a></body></html>';
}
