<?php
declare(strict_types=1);
require_once __DIR__ . '/config.php';

header('Content-Type: application/xml; charset=UTF-8');

$projects = db()->query("SELECT slug, updated_at FROM projects ORDER BY updated_at DESC")->fetchAll();
$chapters = db()->query("SELECT c.id, c.slug, c.updated_at, p.slug AS project_slug
    FROM chapters c JOIN projects p ON p.id = c.project_id
    WHERE c.is_published = 1 ORDER BY c.updated_at DESC")->fetchAll();

function sitemapDate(?string $s): string
{
    $ts = $s ? strtotime($s) : time();
    return date('Y-m-d', $ts ?: time());
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?= e(BASE_URL) ?>/</loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc><?= e(BASE_URL) ?>/projects</loc>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
    <url>
        <loc><?= e(BASE_URL) ?>/oneshots</loc>
        <changefreq>weekly</changefreq>
        <priority>0.6</priority>
    </url>
    <?php foreach ($projects as $p): ?>
    <url>
        <loc><?= e(BASE_URL) ?>/project?slug=<?= urlencode($p['slug']) ?></loc>
        <lastmod><?= sitemapDate($p['updated_at']) ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endforeach; ?>
    <?php foreach ($chapters as $c): ?>
    <url>
        <loc><?= e(BASE_URL) ?>/<?= urlencode($c['project_slug']) ?>/<?= urlencode($c['slug'] ?: (string)$c['id']) ?></loc>
        <lastmod><?= sitemapDate($c['updated_at']) ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <?php endforeach; ?>
</urlset>