<?php
// Динамический sitemap: статические страницы + документы из админки.
require_once 'includes/config.php';
require_once 'includes/content.php';
require_once 'includes/seo.php';

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

// Канонический адрес берём из конфига, а не дублируем строкой в коде.
$origin = rtrim((string)(getenv('CANONICAL_ORIGIN') ?: RC_CANONICAL_ORIGIN), '/');
$today  = date('Y-m-d');

// url, changefreq, priority
$pages = [
    '/'             => ['weekly',    '1.0'],
    '/wiki'         => ['daily',     '0.8'],
    '/rules'        => ['weekly',    '0.7'],
    '/masks'        => ['weekly',    '0.9'],
    '/donate'       => ['monthly',   '0.6'],
    '/documents'    => ['monthly',   '0.4'],
];

try {
    $docKeys = getDocumentKeys();
    foreach ($docKeys as $key) {
        if (preg_match('/^[a-z0-9_-]+$/i', (string)$key)) {
            $pages['/documents/' . $key] = ['monthly', '0.4'];
        }
    }
} catch (Throwable $e) {
    error_log('Sitemap documents listing failed: ' . $e->getMessage());
}

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