<?php
/**
 * 动态生成sitemap.xml - SEO优化版
 * 新增：image扩展、lastmod完善、文章列表页分页、优先级细化
 */
require_once 'config.php';

header('Content-Type: application/xml; charset=utf-8');

$siteURL = siteURL();

// 获取已发布文章
$db = getDB();
$articles = $db->query("SELECT id, title, cover, updated_at FROM articles WHERE is_published = 1 ORDER BY id DESC")->fetchAll();

// 获取文章总页数
$totalArticles = count($articles);
$totalPages = ceil($totalArticles / ARTICLES_PER_PAGE);

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
    <!-- 首页 -->
    <url>
        <loc><?php echo $siteURL; ?>/</loc>
        <lastmod><?php echo date('c'); ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>1.0</priority>
        <image:image>
            <image:loc><?php echo $siteURL; ?>/images/banner1.jpg</image:loc>
            <image:title>淘客鸟助手 - 本地生活与电商购物一键高返查询助手</image:title>
        </image:image>
    </url>

    <!-- 文章列表页（所有分页） -->
    <?php for ($p = 1; $p <= $totalPages; $p++): ?>
    <url>
        <loc><?php echo $siteURL; ?>/articles/<?php if ($p > 1) echo '?page=' . $p; ?></loc>
        <changefreq>daily</changefreq>
        <priority><?php echo $p === 1 ? '0.8' : '0.6'; ?></priority>
    </url>
    <?php endfor; ?>

    <!-- 文章详情页 -->
    <?php foreach ($articles as $a): ?>
    <url>
        <loc><?php echo $siteURL; ?>/article/<?php echo $a['id']; ?>.html</loc>
        <lastmod><?php echo date('c', strtotime($a['updated_at'])); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
        <?php if ($a['cover']): ?>
        <image:image>
            <image:loc><?php echo e($a['cover']); ?></image:loc>
            <image:title><?php echo e($a['title']); ?></image:title>
        </image:image>
        <?php endif; ?>
    </url>
    <?php endforeach; ?>
</urlset>
