<?php
/**
 * Future SEO public entrypoint for AI templates.
 *
 * This file is intentionally outside the legacy /public tree. It only exposes
 * sitemap XML assembled from active seo_pages/seo_routes rows.
 */

define('ROOT_PATH', dirname(__DIR__));

spl_autoload_register(function ($class) {
    $paths = [
        ROOT_PATH . '/src/',
        ROOT_PATH . '/src/Services/',
        ROOT_PATH . '/src/Repositories/',
    ];

    foreach ($paths as $path) {
        $file = $path . $class . '.php';
        if (file_exists($file)) {
            require_once $file;
            return;
        }
    }
});

require_once ROOT_PATH . '/src/rb.php';

function seo_public_sitemap_lang_from_request(): string
{
    $queryLang = strtolower(trim((string) ($_GET['lang'] ?? '')));
    if (in_array($queryLang, ['ru', 'en'], true)) {
        return $queryLang;
    }

    foreach (['REQUEST_URI', 'SCRIPT_NAME', 'PHP_SELF', 'REDIRECT_URL'] as $serverKey) {
        $path = parse_url((string) ($_SERVER[$serverKey] ?? ''), PHP_URL_PATH);
        if (!is_string($path) || $path === '') {
            continue;
        }
        if (preg_match('#(?:^|/)sitemap-(ru|en)\.xml$#i', $path, $matches) === 1) {
            return strtolower((string) $matches[1]);
        }
    }

    return '';
}

try {
    $config = Config::getInstance();
    R::setup($config->getDbDsn(), $config->getDbUser(), $config->getDbPass());
    $config->applyDatabaseSessionSettings();
    \RedBeanPHP\Util\DispenseHelper::setEnforceNamingPolicy(false);
    R::freeze(true);

    $lang = seo_public_sitemap_lang_from_request();
    $baseUrl = trim((string) $config->get('ai_templates_seo_base_url', 'https://neuro.primerka-ai.ru'));
    $service = new AiTemplateSeoService();

    header('Content-Type: application/xml; charset=utf-8');
    echo $lang === ''
        ? $service->buildSitemapIndexXml($baseUrl)
        : $service->buildSitemapXml($lang, $baseUrl);
} catch (Throwable $e) {
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Sitemap is temporarily unavailable.';
}
