<?php
require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php");
function getHost(bool $parent = false)
{
    $arHost = explode(":", $_SERVER["HTTP_HOST"]);
    $_SERVER["HTTP_HOST"] = $arHost[0];
    $hostname = $_SERVER['HTTP_HOST'];
    if ($parent) {
        $hostname_parts = explode('.', $hostname);
        if (count($hostname_parts) > 2) {
            array_shift($hostname_parts);
            $hostname = implode('.', $hostname_parts);
        }
    }
    return $hostname;
}
function echoTextFile($hostname)
{
    $rsSites = CSite::GetByID(SITE_ID);
    $arSite = $rsSites->Fetch();
    $path = $_SERVER['DOCUMENT_ROOT'];
    $filename = trim($_SERVER['REQUEST_URI'], '/');
    $filenameParts = explode('/', $filename);
    if (count($filenameParts) > 1) {
        $filename = $filenameParts[1];
    }
    $file = $path . "/" . $filename;
    if (!file_exists($file)) return false;
    if (!is_readable($file)) return false;
    if (!filesize($file)) return false;
    $timestamp = filemtime($file);
    $tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
    $etag = md5($file . $timestamp);
    $xml = file_get_contents($file);
    $xml = str_replace('https://', 'https://', $xml);
    $xml = str_replace('https://' . $arSite['SERVER_NAME'], 'https://' . getHost(), $xml);
    $xml = str_replace('sitemap-', 'sitemap-', $xml);
    $cities = [];
    if ($filename === 'sitemap.xml') {
        $cities = \Art\Content::getCities();
        // Парсим XML
        $originalXml = simplexml_load_string($xml);
        $originalXml->registerXPathNamespace('sm', 'https://www.sitemaps.org/schemas/sitemap-0.9');
        // Извлекаем все <loc>
        $originalUrls = [];
        foreach ($originalXml->xpath('//sm:sitemap-sm:loc') as $loc) {
            $originalUrls[] = (string)$loc;
        }
        // Извлекаем все <lastmod>
        $originalLastmods = [];
        foreach ($originalXml->xpath('//sm:sitemap-sm:lastmod') as $lastmod) {
            $originalLastmods[] = (string)$lastmod;
        }
        // Создаем новый XML sitemapindex
        $newXml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="https://www.sitemaps.org/schemas/sitemap-0.9"/>');
        $lastmod = date('c');
        // Добавляем ссылки для каждого города
        foreach ($cities as $city) {
            foreach ($originalUrls as $key => $url) {
                $parsedUrl = parse_url($url);
                if (in_array($parsedUrl['path'], [
                    '/sitemap-iblock-1.xml',
                    '/sitemap-iblock-5.xml',
                    '/sitemap-iblock-8.xml',
                ]) && $city['CODE'] !== 'russia') {
                    continue;
                }
                $cityUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . \Art\Content::getPrefixForCity($city) . $parsedUrl['path'];
                $sitemap = $newXml->addChild('sitemap');
                $sitemap->addChild('loc', $cityUrl);
                $sitemap->addChild('lastmod', $originalLastmods[$key] ?? $lastmod);
            }
        }
        $xml = $newXml->asXML();
    } elseif ($filename === 'sitemap-iblock-1.xml') {
        $cities = \Art\Content::getCities();
        $originalXml = simplexml_load_string($xml);
        $originalXml->registerXPathNamespace('sm', 'https://www.sitemaps.org/schemas/sitemap-0.9');
        $originalUrls = [];
        foreach ($originalXml->xpath('//sm:url/sm:loc') as $loc) {
            $originalUrls[] = (string)$loc;
        }
        $originalLastmods = [];
        foreach ($originalXml->xpath('//sm:url/sm:lastmod') as $lastmod) {
            $originalLastmods[] = (string)$lastmod;
        }
        $newXml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="https://www.sitemaps.org/schemas/sitemap-0.9"/>');
        $lastmod = date('c');
        $disabledCookieDirs = \Art\Content::getDisabledCookieDirs();
        foreach ($originalUrls as $key => $url) {
            foreach ($cities as $city) {
                $parsedUrl = parse_url($url);
                foreach ($disabledCookieDirs as $dir) {
                    if (mb_strpos($parsedUrl['path'], $dir) === 0) {
                        $sitemap = $newXml->addChild('url');
                        $sitemap->addChild('loc', $url);
                        $sitemap->addChild('lastmod', $originalLastmods[$key] ?? $lastmod);
                        break 2;
                    }
                }
                // Проверяем, нужно ли исключать URL для данного города
                if (in_array($parsedUrl['path'], [
                        '/sitemap-iblock-1.xml',
                        '/sitemap-iblock-5.xml',
                        '/sitemap-iblock-8.xml',
                    ]) && $city['CODE'] !== 'russia') {
                    continue;
                }
                $cityPrefix = \Art\Content::getPrefixForCity($city);
                if ($parsedUrl['path'] === '/index/') {
                    $parsedUrl['path'] = '/';
                }
                $cityUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $cityPrefix . $parsedUrl['path'];
                $sitemap = $newXml->addChild('url');
                $sitemap->addChild('loc', $cityUrl);
                $sitemap->addChild('lastmod', $originalLastmods[$key] ?? $lastmod);
            }
        }
        $xml = $newXml->asXML();
    } elseif (count($filenameParts) > 1) {
        $prefix = \Art\Content::getCurrentCityPrefix();
        $xml = preg_replace_callback(
            '/<loc>(.*?)<\/loc>/i',
            function($matches) use ($prefix) {
                $url = $matches[1];
                $parsedUrl = parse_url($url);
                $url = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $prefix . $parsedUrl['path'];
                return '<loc>' . $url . '</loc>';
            },
            $xml
        );
    }
    header('Content-Type: application/xml');
    header('Content-Length: ' . mb_strlen($xml));
    header("Last-Modified: $tsstring");
    header("ETag: \"{$etag}\"");
    echo $xml;
    return true;
}
if (!echoTextFile(getHost()) && !echoTextFile(getHost(true))) {
    header('HTTP/1.0 404 Not Found');
}