<?php
// 1. DOMAIN ERMITTELN & IDN / PUNYCODE HANDLING
$host = $_SERVER['HTTP_HOST'] ?? '';
$host = strtolower($host);
$host = preg_replace('/:\d+$/', '', $host);
$host = preg_replace('/^www\./', '', $host);

$utf8Host  = $host;
$asciiHost = $host;

if (function_exists('idn_to_utf8')) {
    $convertedUtf8 = idn_to_utf8($host, 0, INTL_IDNA_VARIANT_UTS46);
    if ($convertedUtf8 !== false) {
        $utf8Host = $convertedUtf8;
    }
}

if (function_exists('idn_to_ascii')) {
    $convertedAscii = idn_to_ascii($host, 0, INTL_IDNA_VARIANT_UTS46);
    if ($convertedAscii !== false) {
        $asciiHost = $convertedAscii;
    }
}

// Punycode Fallback-Map (falls PHP intl-Erweiterung auf dem Server fehlt)
if (strpos($host, 'xn--') === 0) {
    $punyMap = [
        'xn--gnstige-rasierer-jzb.de'       => 'günstige-rasierer.de',
        'xn--wellnesshotel-in-der-nhe-xbc.de' => 'wellnesshotel-in-der-nähe.de',
        'xn--schweizerbanken-2vb.de'          => 'schweizerbanken.de',
		'xn--dealprfer-v9a.de' => 'dealprüfer.de',
    ];
    if (isset($punyMap[$host])) {
        $utf8Host = $punyMap[$host];
    }
}

$domain = $utf8Host;

// 2. STRIKTE ISOLATION: CUSTOM TEMPLATES FÜR SPEZIELLE DOMAINS
// Routing für dealprüfer.de
if (
    $utf8Host === 'dealprüfer.de' ||
    $asciiHost === 'xn--dealprfer-v9a.de'
) {
    $templateFile = __DIR__ . '/templates/dealpruefer/index.php';

    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    }
}
if ($utf8Host === 'schweizerbanken.de' || $asciiHost === 'xn--schweizerbanken-2vb.de') {
    $templateFile = __DIR__ . '/templates/schweizerbanken.php';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    }
}

// Routing für schweizerbanken.com
if ($utf8Host === 'schweizerbanken.com') {
    $templateFile = __DIR__ . '/templates/schweizerbanken-com.php';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    }
}

// Routing für prep-shop.de
if ($utf8Host === 'prep-shop.de' || $asciiHost === 'prep-shop.de') {
    $templateFile = __DIR__ . '/templates/prepshop.php';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    }
}

// Routing für prepforum.de
if ($utf8Host === 'prepforum.de' || $asciiHost === 'prepforum.de') {
    $templateFile = __DIR__ . '/templates/prepforum.php';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    }
}

// 3. JSON-DATEN LADEN (FÜR ALLE NORMALEN DOMAINS)
$jsonFile = __DIR__ . '/domains.json';

if (!file_exists($jsonFile)) {
    die('domains.json wurde nicht gefunden.');
}

$jsonData = file_get_contents($jsonFile);
$domains  = json_decode($jsonData, true);

if (!is_array($domains)) {
    die('Fehler in domains.json: ' . json_last_error_msg());
}

// Match Domain in domains.json
$data = $domains[$utf8Host] 
     ?? $domains[$asciiHost] 
     ?? $domains[$host] 
     ?? $domains['www.' . $utf8Host] 
     ?? null;

if (!$data) {
    $data = [
        'title'          => 'Willkommen auf ' . $domain,
        'description'    => 'Hier entsteht ein neues Informations- und Angebote-Portal für ' . $domain . '.',
        'h1'             => 'Willkommen auf ' . $domain,
        'intro'          => 'Informieren Sie sich über aktuelle Angebote, Vergleiche und Empfehlungen.',
        'category'       => 'Allgemein',
        'theme'          => 'blue',
        'affiliate_link' => '#',
        'button_text'    => 'Mehr erfahren'
    ];
}

function e($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

$title         = $data['title'] ?? 'Willkommen auf ' . $domain;
$description   = $data['description'] ?? $data['text'] ?? '';
$h1            = $data['h1'] ?? $title;
$intro         = $data['intro'] ?? $description;
$affiliateLink = $data['affiliate_link'] ?? $data['button_url'] ?? '#';
$buttonText    = $data['button_text'] ?? 'Angebote ansehen';
$canonical     = 'https://' . $domain . '/';
$faqList       = $data['faq'] ?? [];
$themeKey      = $data['theme'] ?? 'blue';
$matomoId      = $data['matomo_id'] ?? null;

// SCHEMA.ORG (FAQ JSON-LD)
$schemaFaqData = [];
if (!empty($faqList) && is_array($faqList)) {
    foreach ($faqList as $item) {
        $q = $item['question'] ?? $item['q'] ?? '';
        $a = $item['answer'] ?? $item['a'] ?? '';
        if ($q && $a) {
            $schemaFaqData[] = [
                '@type' => 'Question',
                'name' => $q,
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => strip_tags($a)
                ]
            ];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title><?= e($title); ?></title>
    <meta name="description" content="<?= e($description); ?>">
    <meta name="robots" content="index,follow">
    <link rel="canonical" href="<?= e($canonical); ?>">

    <link rel="stylesheet" href="style.css?v=10">

    <!-- Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-WNZE6ZF6B2"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'G-WNZE6ZF6B2');
    </script>

    <!-- Matomo Analytics -->
    <?php if ($matomoId): ?>
    <script>
        var _paq = window._paq = window._paq || [];
        _paq.push(['trackPageView']);
        _paq.push(['enableLinkTracking']);
        (function () {
            var u = "//analytics.madlilly.de/";
            _paq.push(['setTrackerUrl', u + 'matomo.php']);
            _paq.push(['setSiteId', '<?= e($matomoId); ?>']);
            var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
            g.async = true; g.src = u + 'matomo.js'; s.parentNode.insertBefore(g, s);
        })();
    </script>
    <?php endif; ?>

    <?php if (!empty($data['awin_verification'])): ?>
        <meta name="verification" content="<?= e($data['awin_verification']); ?>">
    <?php endif; ?>

    <?php if (!empty($schemaFaqData)): ?>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      "mainEntity": <?= json_encode($schemaFaqData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ?>
    }
    </script>
    <?php endif; ?>
</head>
<body data-theme="<?= e($themeKey); ?>" class="theme-<?= e($themeKey); ?>">

<header class="hero">
    <div class="hero-inner">
        <h1><?= e($h1); ?></h1>
        <p><?= e($intro); ?></p>
        <?php if ($affiliateLink !== '#'): ?>
            <a href="<?= e($affiliateLink); ?>" class="cta" target="_blank" rel="nofollow sponsored">
                <?= e($buttonText); ?>
            </a>
        <?php endif; ?>
    </div>
</header>

<main class="container">

    <?php if (!empty($data['seo_text'])): ?>
        <section class="seo-section">
            <?= $data['seo_text']; ?>
        </section>
    <?php endif; ?>

    <?php if (!empty($data['sections']) && is_array($data['sections'])): ?>
        <?php foreach ($data['sections'] as $section): ?>
            <section>
                <?php if (!empty($section['heading'])): ?>
                    <h2><?= e($section['heading']); ?></h2>
                <?php endif; ?>

                <?php if (!empty($section['text'])): ?>
                    <?php $paragraphs = preg_split('/\n\s*\n/', trim($section['text'])); ?>
                    <?php foreach ($paragraphs as $paragraph): ?>
                        <p><?= nl2br(e($paragraph)); ?></p>
                    <?php endforeach; ?>
                <?php endif; ?>

                <?php if (!empty($section['bullets'])): ?>
                    <ul>
                        <?php foreach ($section['bullets'] as $bullet): ?>
                            <li><?= e($bullet); ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>

                <?php if (!empty($section['button'])): ?>
                    <div class="cta-center">
                        <a href="<?= e($affiliateLink); ?>" class="cta" target="_blank" rel="nofollow sponsored">
                            <?= e($section['button']); ?>
                        </a>
                    </div>
                <?php endif; ?>
            </section>
        <?php endforeach; ?>

    <?php elseif (empty($data['seo_text'])): ?>
        <section>
            <h2>Über <?= e($domain); ?></h2>
            <p><?= e($description); ?></p>
            <p>Finden Sie die besten Optionen, Angebote und Vergleiche direkt übersichtlich zusammengefasst.</p>
            <?php if ($affiliateLink !== '#'): ?>
                <div class="cta-center" style="margin-top: 20px;">
                    <a href="<?= e($affiliateLink); ?>" class="cta" target="_blank" rel="nofollow sponsored">
                        <?= e($buttonText); ?>
                    </a>
                </div>
            <?php endif; ?>
        </section>
    <?php endif; ?>

    <?php if (!empty($faqList) && is_array($faqList)): ?>
        <section class="faq-section">
            <h2>Häufig gestellte Fragen (FAQ)</h2>
            <?php foreach ($faqList as $faq): ?>
                <?php 
                    $q = $faq['question'] ?? $faq['q'] ?? '';
                    $a = $faq['answer'] ?? $faq['a'] ?? '';
                ?>
                <?php if ($q && $a): ?>
                    <details class="faq-item">
                        <summary>
                            <h3><?= e($q); ?></h3>
                        </summary>
                        <div class="faq-answer">
                            <p><?= e($a); ?></p>
                        </div>
                    </details>
                <?php endif; ?>
            <?php endforeach; ?>
        </section>
    <?php endif; ?>

    <?php if ($affiliateLink !== '#'): ?>
        <section style="text-align:center;">
            <h2>Jetzt passende Angebote entdecken</h2>
            <p>Vergleichen Sie verfügbare Optionen und sichern Sie sich die besten Konditionen.</p>
            <a href="<?= e($affiliateLink); ?>" class="cta" target="_blank" rel="nofollow sponsored">
                <?= e($buttonText); ?>
            </a>
        </section>
    <?php endif; ?>

    <?php if (!empty($data['affiliate_notice'])): ?>
        <div class="notice">
            <?= e($data['affiliate_notice']); ?>
        </div>
    <?php endif; ?>

</main>

<footer>
    &copy; <?= date('Y'); ?> <?= e($domain); ?> &nbsp;|&nbsp; 
    <a href="/impressum.php">Impressum</a> &nbsp;|&nbsp; 
    <a href="/datenschutz.php">Datenschutz</a>
</footer>

<?php if ($affiliateLink !== '#'): ?>
    <div class="mobile-sticky-bar">
        <a href="<?= e($affiliateLink); ?>" class="cta" target="_blank" rel="nofollow sponsored">
            <?= e($buttonText); ?>
        </a>
    </div>
<?php endif; ?>

</body>
</html>