<?php
/**
 * 动态生成 sitemap.xml
 */
header('Content-Type: application/xml; charset=utf-8');
require_once 'config.php';
$db = getDB();

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://ichenxun.cn/</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>https://ichenxun.cn/tools.php</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>
    <url>
        <loc>https://ichenxun.cn/articles.php</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
<?php
// 工具页
$stmt = $db->query("SELECT slug, updated_at FROM tools WHERE is_active = 1 ORDER BY updated_at DESC");
while ($tool = $stmt->fetch()) {
    $date = $tool['updated_at'] ? date('Y-m-d', strtotime($tool['updated_at'])) : date('Y-m-d');
    echo "    <url>\n";
    echo "        <loc>https://ichenxun.cn/tool.php?slug=" . htmlspecialchars($tool['slug']) . "</loc>\n";
    echo "        <lastmod>$date</lastmod>\n";
    echo "        <changefreq>weekly</changefreq>\n";
    echo "        <priority>0.8</priority>\n";
    echo "    </url>\n";
}

// 文章页
$stmt = $db->query("SELECT id, updated_at FROM articles WHERE is_published = 1 ORDER BY updated_at DESC");
while ($article = $stmt->fetch()) {
    $date = $article['updated_at'] ? date('Y-m-d', strtotime($article['updated_at'])) : date('Y-m-d');
    echo "    <url>\n";
    echo "        <loc>https://ichenxun.cn/article.php?id=" . $article['id'] . "</loc>\n";
    echo "        <lastmod>$date</lastmod>\n";
    echo "        <changefreq>weekly</changefreq>\n";
    echo "        <priority>0.7</priority>\n";
    echo "    </url>\n";
}
?>
</urlset>
