<?php
require_once 'config.php';

maintenance_guard('html');   // 维护模式：生效中则输出维护页并终止

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

/**
 * SEO 修复后的站点地图（v2.7，v2.9.5 调整）：
 *  - 仅收录真实内容页：首页 / API列表 / 状态 / 统计 / 友链 / 赞助 / 免责声明
 *  - v2.9.5：接口测试页 test_api.php 全站 noindex（工具型薄内容页，SEO P0 修复1），
 *    因此站点地图同步移除其 URL —— 站点地图中不得出现 noindex 页面，
 *    否则 Search Console 会报「已提交网址标记为 noindex」，浪费抓取配额并产生负面信号
 *  - 移除 /api/*.php 数据端点（接口端点不属于文档页，且与 robots.txt 冲突）
 *  - 移除搜索/分类参数页（薄内容 + 与 api_list.php canonical 冲突）
 *  - lastmod 使用真实内容更新时间（接口创建/更新时间、数据文件修改时间），
 *    不再用当前时间伪装新鲜度
 */
function generateEnhancedSitemap() {
    // 注意：必须使用 SITE_URL（站点根 URL，优先取后台配置的固定域名），
    // 否则从 admin/、user/、api/ 子目录加载时生成错误 URL。
    $base_url = SITE_URL;
    $settings = loadData('settings');
    $apis = loadData('apis');

    // 数据最后更新时间：取全部接口中最新的 created_at，兜底用数据库文件 mtime
    $latest = 0;
    foreach ($apis as $api) {
        $t = strtotime((string)($api['created_at'] ?? ''));
        if ($t && $t > $latest) $latest = $t;
    }
    if (!$latest && file_exists(DATA_DIR . 'db.sqlite')) {
        $latest = filemtime(DATA_DIR . 'db.sqlite');
    }
    $latest = $latest ?: time();
    $lastmod_data = date('c', $latest);

    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

    // 主要页面（系统实际入口文件；后台 / 用户中心 / 接口端点一律不进 sitemap）
    $pages = [
        '' => [
            'priority' => '1.0',
            'changefreq' => 'daily',
            'lastmod' => $lastmod_data,
        ],
        'api_list.php' => [
            'priority' => '0.9',
            'changefreq' => 'daily',
            'lastmod' => $lastmod_data,
        ],
        'status.php' => [
            'priority' => '0.7',
            'changefreq' => 'hourly',
            'lastmod' => $lastmod_data,
        ],
        'stats.php' => [
            'priority' => '0.5',
            'changefreq' => 'daily',
            'lastmod' => $lastmod_data,
        ],
        'links.php' => [
            'priority' => '0.8',
            'changefreq' => 'weekly',
            'lastmod' => $lastmod_data,
        ],
        'sponsor.php' => [
            'priority' => '0.6',
            'changefreq' => 'weekly',
            'lastmod' => $lastmod_data,
        ],
        'disclaimer.php' => [
            'priority' => '0.3',
            'changefreq' => 'monthly',
            'lastmod' => $lastmod_data,
        ],
    ];

    foreach ($pages as $page => $info) {
        $page_url = $base_url . '/' . $page;
        $sitemap .= "  <url>\n";
        $sitemap .= "    <loc>" . htmlspecialchars($page_url, ENT_XML1, 'UTF-8') . "</loc>\n";
        $sitemap .= "    <lastmod>{$info['lastmod']}</lastmod>\n";
        $sitemap .= "    <changefreq>{$info['changefreq']}</changefreq>\n";
        $sitemap .= "    <priority>{$info['priority']}</priority>\n";
        $sitemap .= "  </url>\n";
    }

    // v2.9.5：接口测试页（test_api.php?api=ID）已全站 noindex（P0 修复1），
    // 不再写入站点地图 —— 站点地图只列允许收录的内容页。

    $sitemap .= '</urlset>';

    // 同时保存到文件
    @file_put_contents(__DIR__ . '/sitemap.xml', $sitemap);
    return $sitemap;
}

$sitemap_content = generateEnhancedSitemap();
echo $sitemap_content;
