<?php
/**
 * 动态 XML 站点地图（sitemap.xml），利于搜索引擎发现与收录。
 * 访问：/sitemap.php 或伪静态 /sitemap.xml
 * 支持 lastmod / changefreq / priority，并自动排除草稿/隐藏/未审核文章。
 */

const EMLOG_ROOT = __DIR__;
require_once EMLOG_ROOT . '/init.php';

header('Content-Type: application/xml; charset=utf-8');

$Log_Model = new Log_Model();
$Sort_Model = new Sort_Model();

$urls = [];

// 首页
$urls[] = [
    'loc' => BLOG_URL,
    'lastmod' => date('c'),
    'changefreq' => 'daily',
    'priority' => '1.0',
];

// 分类页
$sortData = $Sort_Model->getSorts();
foreach ($sortData as $sort) {
    if (empty($sort['sid'])) {
        continue;
    }
    $urls[] = [
        'loc' => Url::sort($sort['sid']),
        'lastmod' => date('c', (int)($sort['modified'] ?? time())),
        'changefreq' => 'daily',
        'priority' => '0.8',
    ];
}

// 文章页（仅已发布/已审核，最多 1000 条，按时间倒序）
$logs = $Log_Model->getLogsForSitemap(1000);
foreach ($logs as $log) {
    $urls[] = [
        'loc' => Url::log((int)$log['gid']),
        'lastmod' => date('c', (int)($log['date'] ?? time())),
        'changefreq' => 'weekly',
        'priority' => '0.6',
    ];
}

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";
    echo '    <loc>' . htmlspecialchars($u['loc'], ENT_XML1) . "</loc>\n";
    echo '    <lastmod>' . $u['lastmod'] . "</lastmod>\n";
    echo '    <changefreq>' . $u['changefreq'] . "</changefreq>\n";
    echo '    <priority>' . $u['priority'] . "</priority>\n";
    echo "  </url>\n";
}
echo '</urlset>';
