<?php
declare(strict_types=1);

$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
if (str_starts_with($requestPath, '/api/')) {
    require __DIR__ . '/api/index.php';
    exit;
}
$_trimmedPath = rtrim($requestPath, '/');
if ($_trimmedPath === '/impressum') { require __DIR__ . '/impressum.php'; exit; }
if ($_trimmedPath === '/datenschutz') { require __DIR__ . '/datenschutz.php'; exit; }
unset($_trimmedPath);

define('ROOT_DIR', __DIR__);
require_once ROOT_DIR . '/config/app.php';

$dataDir = ROOT_DIR . '/data';

// ── Load data ──────────────────────────────────────────────────────────────────
$config      = json_decode(@file_get_contents($dataDir . '/config.json')     ?: '{}', true) ?: [];
$design      = json_decode(@file_get_contents($dataDir . '/design.json')     ?: '{}', true) ?: [];
$langsRaw    = json_decode(@file_get_contents($dataDir . '/languages.json')  ?: '{}', true) ?: [];
$allSections = json_decode(@file_get_contents($dataDir . '/sections.json')   ?: '[]', true) ?: [];
$galleryRaw  = json_decode(@file_get_contents($dataDir . '/gallery.json')    ?: '[]', true) ?: [];
$navRaw      = json_decode(@file_get_contents($dataDir . '/navigation.json') ?: '{}', true) ?: [];

// ── Language ───────────────────────────────────────────────────────────────────
$defaultLang = $langsRaw['default'] ?? 'de';
$activeLangs = array_column(
    array_filter($langsRaw['available'] ?? [], fn($l) => !empty($l['active'])),
    'code'
);
if (empty($activeLangs)) $activeLangs = [$defaultLang];

$lang = (isset($_GET['lang']) && preg_match('/^[a-z]{2}$/', $_GET['lang']))
    ? $_GET['lang'] : $defaultLang;
if (!in_array($lang, $activeLangs, true)) $lang = $defaultLang;

// ── Token / Guest lookup ───────────────────────────────────────────────────────
$guest    = null;
$rawToken = $_GET['g'] ?? '';
$token    = preg_replace('/[^a-f0-9]/', '', substr($rawToken, 0, 64));
if ($token !== '') {
    $guestsRaw = @json_decode(@file_get_contents($dataDir . '/guests.json'), true) ?: [];
    foreach ($guestsRaw['guests'] ?? [] as $g) {
        if (($g['token'] ?? '') === $token) {
            $guest = [
                'id'       => $g['id']       ?? '',
                'name'     => $g['name']     ?? '',
                'greeting' => $g['greeting'] ?? '',
                'email'    => $g['email']    ?? '',
                'language' => $g['language'] ?? '',
                'persons'  => (int)($g['persons'] ?? 1),
                'rsvp'     => $g['rsvp']     ?? 'pending',
                'meal'     => $g['meal']     ?? [],
                'token'    => $token,
            ];
            if ($guest['language'] && in_array($guest['language'], $activeLangs, true)) {
                $lang = $guest['language'];
            }
            break;
        }
    }
}

// ── Password protection ────────────────────────────────────────────────────────
$pp         = $config['password_protection'] ?? [];
$ppEnabled  = !empty($pp['enabled']);
$ppError    = false;
$showSplash = false;

// Admin preview: if backstage session is active, bypass frontend password splash
$isAdminPreview  = false;
$isEditorPreview = false;
if (!empty($_COOKIE['hw_session']) && ($ppEnabled || ($_GET['editor_preview'] ?? '') === '1')) {
    session_name('hw_session');
    session_start();
    $isAdminPreview  = !empty($_SESSION['hw_auth']);
    $isEditorPreview = $isAdminPreview && (($_GET['editor_preview'] ?? '') === '1');
    session_write_close();
}

if ($ppEnabled && !$isAdminPreview) {
    session_name('hw_frontend');
    session_set_cookie_params([
        'lifetime' => 0, 'path' => '/',
        'httponly' => true, 'samesite' => 'Lax',
        'secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    ]);
    session_start();

    if ($guest !== null) {
        // Personal invite link bypasses password
        $_SESSION['hw_frontend_unlocked'] = true;
    } elseif (!empty($_SESSION['hw_frontend_unlocked'])) {
        // Already unlocked
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hw_pw'])) {
        $hash = $pp['password_hash'] ?? '';
        if ($hash && password_verify($_POST['hw_pw'], $hash)) {
            $_SESSION['hw_frontend_unlocked'] = true;
            $loc = strtok($_SERVER['REQUEST_URI'], '?');
            if ($lang !== $defaultLang) $loc .= '?lang=' . urlencode($lang);
            header('Location: ' . $loc);
            exit;
        }
        $ppError    = true;
        $showSplash = true;
    } else {
        $showSplash = true;
    }
}

// ── Sections: only visible, sorted by order ────────────────────────────────────
if ($isEditorPreview) {
    $sections = array_values($allSections);
} else {
    $sections = array_values(array_filter($allSections, fn($s) => !empty($s['visible'])));
}
usort($sections, fn($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));

// Filter server-side sensitive data before embedding in public JS
require_once ROOT_DIR . '/api/Geschenketisch.php';
foreach ($sections as &$s) {
    if ($s['type'] === 'geschenketisch' && isset($s['data'])) {
        $s['data']['items'] = Geschenketisch::filterItemsForPublic($s['data']);
    }
}
unset($s);

// Check if any gallery-section is present (for conditional asset loading)
$hasGallerySection = !empty(array_filter($sections, fn($s) => $s['type'] === 'gallery-section'));

// Sort gallery images by order for frontend
if (!empty($galleryRaw['images'])) {
    usort($galleryRaw['images'], fn($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));
}

// ── Design tokens ─────────────────────────────────────────────────────────────
$colorPrimary   = $design['color_primary']   ?? '#B99954';
$colorSecondary = $design['color_secondary'] ?? '#EFB954';
$colorBg        = $design['color_bg']        ?? '#ffffff';
$colorHeadline  = $design['color_headline']  ?? '#1a1a1a';
$colorBody      = $design['color_body']      ?? '#444444';
$fontHeading    = preg_replace('/[^a-zA-Z0-9 ]/', '', $design['font_heading'] ?? 'Inter');
$fontBody       = preg_replace('/[^a-zA-Z0-9 ]/', '', $design['font_body']    ?? 'Inter');

// ── Page meta ─────────────────────────────────────────────────────────────────
$pageTitle = htmlspecialchars($config['couple_name'] ?? 'Hochzeitswebseite', ENT_QUOTES, 'UTF-8');

// ── HW_DATA (JSON for Vue) ────────────────────────────────────────────────────
$hwData = json_encode([
    'sections'        => $sections,
    'isEditorPreview' => $isEditorPreview,
    'design'          => $design,
    'config'   => [
        'couple_name'         => $config['couple_name']         ?? '',
        'wedding_date'        => $config['wedding_date']        ?? '',
        'wedding_time'        => $config['wedding_time']        ?? '',
        'surprise_mode_gifts' => !empty($config['surprise_mode_gifts']),
    ],
    'gallery'    => $galleryRaw,
    'guest'      => $guest,
    'lang'       => $lang,
    'base_url'   => rtrim(APP_URL, '/'),
    'navigation' => [
        'enabled' => !empty($navRaw['enabled']),
        'labels'  => $navRaw['labels'] ?? [],
    ],
    'langs'      => [
        'active'  => array_values(array_filter(
            $langsRaw['available'] ?? [],
            fn($l) => !empty($l['active'])
        )),
        'default' => $defaultLang,
    ],
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP);

// ── Helpers ───────────────────────────────────────────────────────────────────
function e(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

// ══════════════════════════════════════════════════════════════════════════════
// PASSWORD SPLASH (standalone page, no Vue)
// ══════════════════════════════════════════════════════════════════════════════
if ($showSplash):
    $splashHeadline = e($pp['headline'] ?? '');
    $splashText     = e($pp['text']     ?? '');
    $splashBgStyle  = '';
    if (!empty($pp['image'])) {
        $imgUrl = e(rtrim(APP_URL, '/') . '/' . ltrim($pp['image'], '/'));
        $splashBgStyle = " style=\"background-image:url('{$imgUrl}')\"";
    }
?>
<!DOCTYPE html>
<html lang="<?= e($lang) ?>" class="cf-theme-light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?></title>
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/css/core-framework.css">
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/css/frontend.css">
    <link rel="icon" href="<?= ASSETS_URL ?>/img/favicon.png">
    <style>
        :root {
            --primary:    <?= e($colorPrimary) ?>;
            --secondary:  <?= e($colorSecondary) ?>;
            --bg-body:    <?= e($colorBg) ?>;
            --text-title: <?= e($colorHeadline) ?>;
            --text-body:  <?= e($colorBody) ?>;
        }
    </style>
</head>
<body>
<div class="hw-splash"<?= $splashBgStyle ?>>
    <div class="hw-splash__overlay"></div>
    <div class="hw-splash__card card">
        <?php if ($splashHeadline): ?><h1 class="hw-splash__headline"><?= $splashHeadline ?></h1><?php endif; ?>
        <?php if ($splashText): ?><p class="hw-splash__text"><?= $splashText ?></p><?php endif; ?>
        <form method="POST" class="hw-splash__form" novalidate>
            <div class="hw-splash__field">
                <input type="password" name="hw_pw"
                    class="input hw-splash__input<?= $ppError ? ' hw-splash__input--error' : '' ?>"
                    placeholder="Passwort" autofocus>
            </div>
            <?php if ($ppError): ?>
            <p class="hw-splash__error">Falsches Passwort. Bitte erneut versuchen.</p>
            <?php endif; ?>
            <button type="submit" class="button hw-splash__btn">Eintreten</button>
        </form>
    </div>
</div>
</body>
</html>
<?php exit; endif; ?>
<!DOCTYPE html>
<html lang="<?= e($lang) ?>" class="cf-theme-light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?></title>
    <link rel="stylesheet" href="https://use.hugeicons.com/font/icons.css">
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/css/fonts.css">
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/css/core-framework.css">
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/css/frontend.css">
    <?php if ($hasGallerySection): ?>
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/vendor/glightbox/glightbox.min.css">
    <?php endif; ?>
    <link rel="icon" href="<?= ASSETS_URL ?>/img/favicon.png">
    <style>
        :root {
            --primary:       <?= e($colorPrimary) ?>;
            --secondary:     <?= e($colorSecondary) ?>;
            --bg-body:       <?= e($colorBg) ?>;
            --text-title:    <?= e($colorHeadline) ?>;
            --text-body:     <?= e($colorBody) ?>;
            --font-heading:  '<?= e($fontHeading) ?>', Georgia, serif;
            --font-body:     '<?= e($fontBody) ?>', system-ui, sans-serif;
        }
    </style>
    <?php if ($isEditorPreview): ?>
    <style>
        .hw-section--hidden-preview { position: relative; border: 2px dashed #5183ed; }
        .hw-editor-hidden-badge {
            position: absolute; top: 0; right: 0; z-index: 9999;
            background: #5183ed; width: 28px; height: 28px;
            display: flex; align-items: center; justify-content: center; border-bottom-left-radius: 4px;
        }
        .hw-editor-hidden-badge i { color: #fff; font-size: 20px; line-height: 1; }
    </style>
    <?php endif; ?>
</head>
<body>

<div id="hw-app"></div>

<footer class="hw-footer">
    <div class="hw-footer__inner">
        <span class="hw-footer__name"><?= $pageTitle ?></span>
        <div class="hw-footer__links">
            <a href="/impressum" class="hw-footer__link">Impressum</a>
            <a href="/datenschutz" class="hw-footer__link">Datenschutz</a>
        </div>
    </div>
</footer>

<script>window.HW_DATA = <?= $hwData ?>;</script>
<?php if ($hasGallerySection): ?>
<script src="<?= ASSETS_URL ?>/vendor/glightbox/glightbox.min.js"></script>
<?php endif; ?>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="<?= ASSETS_URL ?>/js/frontend-app.js"></script>

</body>
</html>
