<?php
/**
 * 动态 Sitemap XML 生成
 * 使用方式：在伪静态中重写 /sitemap.xml → sitemap.xml
 */
define('IN_FORUM', true);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

if (needInstall()) { http_response_code(503); exit; }

$siteUrl = rtrim(site('site_url'), '/');

header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// 首页
echo "  <url><loc>{$siteUrl}/</loc><changefreq>daily</changefreq><priority>1.0</priority></url>\n";

// 版块
try {
    $boards = db()->select("SELECT slug, updated_at FROM `" . db()->table('boards') . "` WHERE status=1 ORDER BY sort_order ASC");
    foreach ($boards as $b) {
        $loc = $siteUrl . '/forum/' . urlencode($b['slug']);
        $date = date('Y-m-d', strtotime($b['updated_at'] ?? 'now'));
        echo "  <url><loc>{$loc}</loc><changefreq>daily</changefreq><priority>0.8</priority><lastmod>{$date}</lastmod></url>\n";
    }
} catch (Exception $e) {}

// 帖子
try {
    $threads = db()->select("SELECT id, updated_at FROM `" . db()->table('threads') . "` WHERE status=1 ORDER BY updated_at DESC LIMIT 500");
    foreach ($threads as $t) {
        $loc = $siteUrl . '/thread/' . $t['id'];
        $date = date('Y-m-d', strtotime($t['updated_at'] ?? 'now'));
        echo "  <url><loc>{$loc}</loc><changefreq>weekly</changefreq><priority>0.6</priority><lastmod>{$date}</lastmod></url>\n";
    }
} catch (Exception $e) {}

echo '</urlset>';
