<?php
// sitemap.xml — Mapa de sitio dinámico
require_once __DIR__ . '/includes/config.php';

header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: public, max-age=3600');

$base = rtrim(SITE_URL, '/');

$articles = db()->query(
    'SELECT slug, published_at FROM articles
     WHERE status="published"
     ORDER BY published_at DESC
     LIMIT 5000'
)->fetchAll();

$cats = db()->query('SELECT slug FROM categories')->fetchAll();

function sx(string $s): string { return htmlspecialchars($s, ENT_XML1, 'UTF-8'); }

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// Páginas estáticas
$statics = [
    ['/', 'hourly', '1.0'],
    ['/noticias', 'hourly', '0.9'],
    ['/quienes-somos', 'monthly', '0.5'],
    ['/contacto', 'monthly', '0.5'],
];
foreach ($statics as [$path, $freq, $pri]) {
    echo "  <url><loc>" . sx($base . $path) . "</loc><changefreq>$freq</changefreq><priority>$pri</priority></url>\n";
}

// Categorías
foreach ($cats as $cat) {
    echo "  <url>\n";
    echo "    <loc>" . sx($base . '/categoria/' . $cat['slug']) . "</loc>\n";
    echo "    <changefreq>hourly</changefreq><priority>0.8</priority>\n";
    echo "  </url>\n";
}

// Artículos
foreach ($articles as $art) {
    echo "  <url>\n";
    echo "    <loc>" . sx($base . '/noticia/' . $art['slug']) . "</loc>\n";
    echo "    <lastmod>" . sx(substr($art['published_at'], 0, 10)) . "</lastmod>\n";
    echo "    <changefreq>weekly</changefreq><priority>0.7</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>' . "\n";
