<?php
/**
 * Serves /sitemap.xml.
 *
 * Indexed:
 *   - Homepage
 *   - Static info pages: /about, /contact, /privacy
 *   - Every category page
 *   - Every template detail page
 *
 * Excluded:
 *   - /admin/*
 *   - /search.php (infinite URL combinations)
 *   - /templates.php with filter/sort params (canonical points elsewhere)
 *
 * Routed at /sitemap.xml via the rewrite rule in public/.htaccess.
 */
declare(strict_types=1);

require_once __DIR__ . '/../app/includes/static_bootstrap.php';
require_once __DIR__ . '/../app/models/Category.php';

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

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

$rows = [];

// Static pages
foreach ([
    ['',                1.0, 'daily'],
    ['/templates.php',  0.9, 'daily'],
    ['/categories.php', 0.8, 'weekly'],
    ['/about.php',      0.5, 'monthly'],
    ['/contact.php',    0.4, 'monthly'],
    ['/privacy.php',    0.3, 'yearly'],
] as [$path, $prio, $freq]) {
    $rows[] = [
        'loc'        => $base . $path,
        'lastmod'    => gmdate('Y-m-d'),
        'changefreq' => $freq,
        'priority'   => $prio,
    ];
}

// Categories
try {
    foreach (Category::all() as $c) {
        $rows[] = [
            'loc'        => $base . '/category.php?slug=' . rawurlencode((string) $c['slug']),
            'lastmod'    => substr((string) $c['updated_at'], 0, 10),
            'changefreq' => 'weekly',
            'priority'   => 0.7,
        ];
    }
} catch (Throwable $e) {
    // soft fail — sitemap still valid without categories
}

// Templates — pull lightweight columns only
try {
    $stmt = db()->query(
        'SELECT slug, updated_at FROM templates ORDER BY updated_at DESC'
    );
    foreach ($stmt->fetchAll() as $t) {
        $rows[] = [
            'loc'        => $base . '/template.php?slug=' . rawurlencode((string) $t['slug']),
            'lastmod'    => substr((string) $t['updated_at'], 0, 10),
            'changefreq' => 'monthly',
            'priority'   => 0.6,
        ];
    }
} catch (Throwable $e) {
    // soft fail
}

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