<?php
/** 动态 sitemap.xml */
require __DIR__ . '/config/config.php';
require __DIR__ . '/includes/functions.php';
header('Content-Type: application/xml; charset=utf-8');

$base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
$path = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
if ($path && $path !== '\\') {
    $base .= $path;
}
$base = rtrim($base, '/');

$urls = [
    ['loc' => $base . '/', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => $base . '/about', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['loc' => $base . '/news', 'priority' => '0.9', 'changefreq' => 'daily'],
    ['loc' => $base . '/party', 'priority' => '0.85', 'changefreq' => 'daily'],
    ['loc' => $base . '/business', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['loc' => $base . '/technology', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => $base . '/contact', 'priority' => '0.8', 'changefreq' => 'monthly'],
];

$pdo = getDb();
$news = $pdo->query("SELECT id, updated_at FROM news ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
foreach ($news as $n) {
    $urls[] = [
        'loc' => $base . '/news/' . $n['id'] . '.html',
        'priority' => '0.7',
        'changefreq' => 'monthly',
        'lastmod' => date('Y-m-d', strtotime($n['updated_at'])),
    ];
}

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><loc>' . htmlspecialchars($u['loc']) . '</loc>';
    if (!empty($u['lastmod'])) echo '<lastmod>' . $u['lastmod'] . '</lastmod>';
    echo '<changefreq>' . $u['changefreq'] . '</changefreq><priority>' . $u['priority'] . '</priority></url>' . "\n";
}
echo '</urlset>';
