<?php
/**
 * sitemap.xml — 动态生成（Yandex / Google）
 */
require_once __DIR__ . '/includes/functions.php';
header('Content-Type: application/xml; charset=utf-8');

$urls = [];
function add_url(array &$urls, string $loc, string $priority = '0.7', string $changefreq = 'weekly'): void
{
    $urls[] = ['loc' => SITE_URL . '/' . ltrim($loc, '/'), 'priority' => $priority, 'changefreq' => $changefreq];
}

add_url($urls, '', '1.0', 'daily');
foreach (q("SELECT slug FROM bq_categories WHERE status=1") as $c) {
    add_url($urls, 'category.php?slug=' . urlencode($c['slug']), '0.9');
}
foreach (q("SELECT slug, created_at FROM bq_products WHERE status=1") as $p) {
    add_url($urls, 'product.php?slug=' . urlencode($p['slug']), '0.8');
    $urls[count($urls) - 1]['lastmod'] = date('c', strtotime($p['created_at']));
}
foreach (q("SELECT slug, created_at FROM bq_articles WHERE status=1") as $a) {
    add_url($urls, 'article.php?slug=' . urlencode($a['slug']), '0.7');
    $urls[count($urls) - 1]['lastmod'] = date('c', strtotime($a['created_at']));
}
add_url($urls, 'factory.php', '0.9');
add_url($urls, 'about.php', '0.6');
add_url($urls, 'blog.php', '0.7');
add_url($urls, 'contact.php', '0.8');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $u) {
    echo "<url>\n  <loc>" . e($u['loc']) . "</loc>\n";
    if (!empty($u['lastmod'])) echo '  <lastmod>' . e($u['lastmod']) . "</lastmod>\n";
    echo '  <changefreq>' . e($u['changefreq']) . "</changefreq>\n";
    echo '  <priority>' . e($u['priority']) . "</priority>\n</url>\n";
}
echo '</urlset>';
