<?php

/**

 * Minimalus įėjimas – tik nukreipia srautą.

 * Root (/) → index.html (8k eilučių landing, nepaliestas).

 * Slug URL (pvz. /pigus-internetas-vilniuje) → seo-page.php (SEO variklis).

 */

require_once __DIR__ . '/api/gl-ai-seo-corpus.lib.php';

if (is_file(__DIR__ . '/seo/bot_tracker.php')) {
    define('GL_BOT_TRACKER_NO_AUTORUN', true);
    require_once __DIR__ . '/seo/bot_tracker.php';
}

$uri = trim(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH), '/');

$slug = trim($_GET['slug'] ?? $uri, '/ ');

if ($slug !== '' && $slug !== 'index.html') {
    require_once __DIR__ . '/seo/gl-seo-lv-redirects.lib.php';
    gl_seo_lv_maybe_redirect_slug($slug);
    require_once __DIR__ . '/seo/gl-seo-request-guard.lib.php';
    gl_seo_request_guard_enforce();
    require_once __DIR__ . '/seo/gl-seo-page-cache.lib.php';
    $langForCache = strtolower(trim((string) ($_GET['lang'] ?? '')));
    $cachedHtml = gl_seo_page_cache_try_serve($slug, $langForCache);
    if ($cachedHtml !== null) {
        echo $cachedHtml;
        exit;
    }
    if (function_exists('trackAIBots') && bot_tracker_detect_current() !== null) {
        trackAIBots();
    }
}



if ($slug === '' || $slug === 'index.html') {

    $landing = __DIR__ . '/index.html';

    if (file_exists($landing)) {

        $html = file_get_contents($landing);

        if ($html !== false) {

            $corpus = glLoadAiSeoCorpusFragment();

            if ($corpus !== '') {

                if (stripos($html, 'glAiSeoCorpus') !== false) {

                    $html = preg_replace(
                        '#(?:<!--[^>]*?AI[^>]*?-->\s*)?<div\s+id="glAiSeoCorpus"[^>]*>[\s\S]*?</div>\s*#i',
                        "\n<!-- AI / SEO / LLM corpus -->\n" . $corpus . "\n",
                        $html,
                        1
                    );

                } elseif (stripos($html, '</body>') !== false) {

                    $html = preg_replace('/<\/body>/i', "\n<!-- AI / SEO / LLM corpus -->\n" . $corpus . "\n</body>", $html, 1);

                }

            }

            header('Content-Type: text/html; charset=utf-8');

            echo $html;

            exit;

        }

    }

    header('Location: /');

    exit;

}



require __DIR__ . '/seo/seo-page.php';

