<?php
// /var/www/powerlottokorea.co.kr/public_html/sitemap.php
// robots.txt에서 이 파일을 가리키도록 설정되어 있습니다.
// 뉴스가 새로 추가될 때마다 자동으로 sitemap에 반영됩니다 (수동 편집 불필요).
require_once __DIR__ . '/../config/db.php';

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

$staticUrls = [
    ['loc' => '/',                                   'changefreq' => 'daily',   'priority' => '1.0'],
    ['loc' => '/results.php?type=powerball',          'changefreq' => 'daily',   'priority' => '0.9'],
    ['loc' => '/results.php?type=megamillions',       'changefreq' => 'daily',   'priority' => '0.9'],
    ['loc' => '/guide.php',                           'changefreq' => 'monthly', 'priority' => '0.9'],
    ['loc' => '/how-to-buy-powerball.php',            'changefreq' => 'monthly', 'priority' => '0.9'],
    ['loc' => '/how-to-buy-megamillions.php',         'changefreq' => 'monthly', 'priority' => '0.9'],
    ['loc' => '/tax-calculator.php',                  'changefreq' => 'monthly', 'priority' => '0.7'],
    ['loc' => '/news.php',                            'changefreq' => 'daily',   'priority' => '0.8'],
    ['loc' => '/board.php',                           'changefreq' => 'daily',   'priority' => '0.5'],
];

$newsUrls = [];
try {
    $stmt = $pdo->query("SELECT id, slug, published_at FROM news ORDER BY published_at DESC");
    foreach ($stmt->fetchAll() as $row) {
        $loc = $row['slug']
            ? '/news-detail.php?slug=' . urlencode($row['slug'])
            : '/news-detail.php?id=' . $row['id'];
        $newsUrls[] = [
            'loc'        => $loc,
            'lastmod'    => date('Y-m-d', strtotime($row['published_at'])),
            'changefreq' => 'monthly',
            'priority'   => '0.6',
        ];
    }
} catch (\PDOException $e) {
    error_log('[sitemap 뉴스 조회 실패] ' . $e->getMessage());
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach (array_merge($staticUrls, $newsUrls) as $u): ?>
    <url>
        <loc>https://powerlottokorea.co.kr<?= htmlspecialchars($u['loc']) ?></loc>
        <?php if (!empty($u['lastmod'])): ?><lastmod><?= $u['lastmod'] ?></lastmod><?php endif; ?>
        <changefreq><?= $u['changefreq'] ?></changefreq>
        <priority><?= $u['priority'] ?></priority>
    </url>
<?php endforeach; ?>
</urlset>