<?php
require_once __DIR__ . '/lib/bootstrap.php';
require_once __DIR__ . '/lib/hubs.php';

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

$rows = $pdo->query("SELECT slug, COALESCE(published_at, updated_at) AS dt FROM articles WHERE status='published' ORDER BY dt DESC LIMIT 500")->fetchAll() ?: [];
$hubs = $pdo->query("SELECT slug, updated_at AS dt FROM hubs WHERE is_active=1 ORDER BY updated_at DESC")->fetchAll() ?: [];
$base = rtrim($BASE_URL,'/');

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc><?=h($base.'/')?></loc>
    <changefreq>hourly</changefreq>
  </url>
  <url>
    <loc><?=h($base.'/hubs.php')?></loc>
    <changefreq>weekly</changefreq>
  </url>
  <?php foreach ($hubs as $h): ?>
    <url>
      <loc><?=h($base.'/hub.php?slug='.urlencode((string)$h['slug']))?></loc>
      <lastmod><?=h(gmdate('c', strtotime((string)$h['dt'])))?></lastmod>
      <changefreq>weekly</changefreq>
    </url>
  <?php endforeach; ?>
  <?php foreach ($rows as $r): ?>
    <url>
      <loc><?=h($base.'/story.php?slug='.urlencode((string)$r['slug']))?></loc>
      <lastmod><?=h(gmdate('c', strtotime((string)$r['dt'])))?></lastmod>
      <changefreq>weekly</changefreq>
    </url>
  <?php endforeach; ?>
</urlset>
