<?php
/**
 * 动态站点地图：根据计算器配置生成，始终与内容同步。
 */
require_once __DIR__ . '/lib/safety.php';
require_once __DIR__ . '/lib/settings.php';
require_once __DIR__ . '/lib/seo.php';          // 提供 lingke_url()
require_once __DIR__ . '/config/calculators.php';

$base = rtrim(lingke_setting('site_base'), '/');

/**
 * lastmod：取「计算器配置 + 模板 + 本文件」中最新的修改时间。
 * 只有内容真正变化（配置文件被改动）时 lastmod 才会变，避免每次请求都刷新日期。
 */
$stamp = 0;
$watch = array_merge(
    glob(__DIR__ . '/config/*.php') ?: [],
    glob(__DIR__ . '/templates/*.php') ?: []
);
$watch[] = __FILE__;
foreach ($watch as $f) {
    $m = @filemtime($f);
    if ($m && $m > $stamp) $stamp = $m;
}
if (!$stamp) $stamp = time();
$lastmod = gmdate('Y-m-d', $stamp);

$urls = [];
$urls[] = ['loc' => $base . '/', 'priority' => '1.0', 'changefreq' => 'daily'];
$urls[] = ['loc' => $base . '/about', 'priority' => '0.6', 'changefreq' => 'monthly'];
$urls[] = ['loc' => $base . '/privacy', 'priority' => '0.3', 'changefreq' => 'yearly'];
foreach (lingke_calculators() as $c) {
    $urls[] = ['loc' => $base . lingke_url($c['slug']), 'priority' => '0.9', 'changefreq' => 'monthly'];
}

// 必须：正确的 XML 响应头（此前被服务器以 octet-stream 静态返回导致暴露源码）
header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noindex');
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, 'UTF-8') . '</loc>' . "\n";
    echo '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
    echo '    <changefreq>' . $u['changefreq'] . '</changefreq>' . "\n";
    echo '    <priority>' . $u['priority'] . '</priority>' . "\n";
    echo '  </url>' . "\n";
}
echo '</urlset>';
