<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/functions.php';

header('Content-Type: application/xml; charset=utf-8');

$base = rtrim(SITE_URL, '/');
$now = date('c');

$urls = [];
$add = function(string $loc, string $lastmod = null, string $changefreq = 'weekly', string $priority = '0.7') use (&$urls) {
    $urls[] = compact('loc','lastmod','changefreq','priority');
};

$add($base . '/index.php', $now, 'weekly', '1.0');
$add($base . '/shop.php', $now, 'daily', '0.9');
$add($base . '/about.php', $now, 'monthly', '0.6');
$add($base . '/contact.php', $now, 'monthly', '0.6');

try {
    $cats = db()->query("SELECT slug, created_at FROM categories WHERE is_active=1")->fetchAll();
    foreach ($cats as $c) {
        $add($base . '/category.php?category=' . urlencode((string)$c['slug']), (string)$c['created_at'], 'weekly', '0.8');
    }
    $prods = db()->query("SELECT slug, updated_at, created_at FROM products WHERE is_active=1")->fetchAll();
    foreach ($prods as $p) {
        $lm = (string)($p['updated_at'] ?: $p['created_at']);
        $add($base . '/product.php?slug=' . urlencode((string)$p['slug']), $lm, 'weekly', '0.8');
    }
} catch (Throwable $e) {}

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($urls as $u): ?>
  <url>
    <loc><?= e($u['loc']) ?></loc>
    <?php if (!empty($u['lastmod'])): ?><lastmod><?= e((string)$u['lastmod']) ?></lastmod><?php endif; ?>
    <changefreq><?= e((string)$u['changefreq']) ?></changefreq>
    <priority><?= e((string)$u['priority']) ?></priority>
  </url>
<?php endforeach; ?>
</urlset>

