<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/seo.php';

$routes = seo_public_routes();
$limit = 50000;
$part = isset($_GET['part']) ? max(1, (int) $_GET['part']) : null;
$totalParts = max(1, (int) ceil(count($routes) / $limit));

header('Content-Type: application/xml; charset=UTF-8');

if ($totalParts > 1 && $part === null) {
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
    for ($i = 1; $i <= $totalParts; $i++) {
        echo "  <sitemap>\n";
        echo '    <loc>' . htmlspecialchars(SEO_BASE_URL . '/sitemap.xml?part=' . $i, ENT_XML1, 'UTF-8') . "</loc>\n";
        echo '    <lastmod>' . gmdate('Y-m-d') . "</lastmod>\n";
        echo "  </sitemap>\n";
    }
    echo "</sitemapindex>\n";
    exit;
}

$selectedPart = $part ?? 1;
$routes = array_slice($routes, ($selectedPart - 1) * $limit, $limit);

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
foreach ($routes as $route) {
    echo "  <url>\n";
    echo '    <loc>' . htmlspecialchars($route['loc'], ENT_XML1, 'UTF-8') . "</loc>\n";
    echo '    <lastmod>' . htmlspecialchars($route['lastmod'], ENT_XML1, 'UTF-8') . "</lastmod>\n";
    echo '    <changefreq>' . htmlspecialchars($route['changefreq'], ENT_XML1, 'UTF-8') . "</changefreq>\n";
    echo '    <priority>' . htmlspecialchars($route['priority'], ENT_XML1, 'UTF-8') . "</priority>\n";
    echo "  </url>\n";
}
echo "</urlset>\n";
