<?php
/**
 * 동적 sitemap
 *
 * 이전에는 sitemap.xml 정적 파일에 6개 URL 이 lastmod 2026-08-03 으로 굳어 있었고,
 * 색인 가치가 없는 login/signup 이 들어 있었다. 대회 페이지가 늘어나는 구조라
 * 수동 관리로는 따라갈 수 없어 DB 에서 생성한다.
 *
 * nginx 에서 /sitemap.xml 을 이 파일로 rewrite 한다 (nginx-web-config.conf).
 */
require_once __DIR__ . '/inc/config.site.php';
require_once __DIR__ . '/inc/marathon.helper.php';

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

$urls = [
    ['loc' => '/',                  'changefreq' => 'weekly',  'priority' => '1.0'],
    ['loc' => '/marathon.php',      'changefreq' => 'daily',   'priority' => '0.9'],
    ['loc' => '/blog.php',          'changefreq' => 'weekly',  'priority' => '0.7'],
    ['loc' => '/terms.php',         'changefreq' => 'yearly',  'priority' => '0.3'],
    ['loc' => '/privacy.php',       'changefreq' => 'yearly',  'priority' => '0.3'],
    ['loc' => '/account-delete.php','changefreq' => 'yearly',  'priority' => '0.3'],
];
// login/signup 은 색인 가치가 없어 제외한다 (예전 sitemap.xml 에는 들어 있었다)

// 다가오는 대회 전부 — 지난 대회는 색인 가치가 떨어져 제외
try {
    $rows = $DB->rawQuery(
        "SELECT marathon_id, slug, event_date, updated_at, created_at
           FROM rw_official_marathons
          WHERE status = 'PUBLISHED' AND event_date >= CURDATE()
          ORDER BY event_date ASC
          LIMIT 5000"
    );
} catch (\Throwable $e) {
    error_log('sitemap marathon query failed: ' . $e->getMessage());
    $rows = [];
}

foreach ($rows ?: [] as $m) {
    $urls[] = [
        'loc'        => marathon_url($m),
        'lastmod'    => date('Y-m-d', strtotime($m['updated_at'] ?: $m['created_at'] ?: 'now')),
        'changefreq' => 'weekly',
        'priority'   => '0.8',
    ];
}

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(APP_DOMAIN . $u['loc'], ENT_XML1, 'UTF-8') . "</loc>\n";
    echo '    <lastmod>' . ($u['lastmod'] ?? date('Y-m-d')) . "</lastmod>\n";
    echo '    <changefreq>' . $u['changefreq'] . "</changefreq>\n";
    echo '    <priority>' . $u['priority'] . "</priority>\n";
    echo "  </url>\n";
}
echo '</urlset>' . "\n";
