<?php
/**
 * CRON JOB — can run standalone or is auto-called at the end of fetch_rss.php.
 * Regenerates:
 *   sitemap-news.xml   (all news articles)
 *   sitemap-games.xml  (all games)
 *   sitemap-index.xml  (points to the two above + static pages)
 * Also pings Google/Bing so Search Console picks up changes faster.
 */
if (!function_exists('db')) {
    require_once __DIR__ . '/../includes/functions.php';
}

function xml_escape($s) {
    return htmlspecialchars($s, ENT_QUOTES | ENT_XML1, 'UTF-8');
}

$root = dirname(__DIR__);

// ---------- sitemap-news.xml ----------
$newsRows = db()->query("SELECT slug, published_at FROM news ORDER BY published_at DESC")->fetchAll(PDO::FETCH_ASSOC);
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($newsRows as $r) {
    $loc = SITE_URL . '/news-detail.php?slug=' . urlencode($r['slug']);
    $lastmod = date('c', strtotime($r['published_at']));
    $xml .= "  <url>\n    <loc>" . xml_escape($loc) . "</loc>\n    <lastmod>$lastmod</lastmod>\n    <changefreq>daily</changefreq>\n    <priority>0.8</priority>\n  </url>\n";
}
$xml .= '</urlset>';
file_put_contents($root . '/sitemap-news.xml', $xml);

// ---------- sitemap-games.xml ----------
$gameRows = db()->query("SELECT slug, created_at FROM games ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
$xml2 = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml2 .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($gameRows as $r) {
    $loc = SITE_URL . '/game-detail.php?slug=' . urlencode($r['slug']);
    $lastmod = date('c', strtotime($r['created_at'] ?: 'now'));
    $xml2 .= "  <url>\n    <loc>" . xml_escape($loc) . "</loc>\n    <lastmod>$lastmod</lastmod>\n    <changefreq>weekly</changefreq>\n    <priority>0.7</priority>\n  </url>\n";
}
$xml2 .= '</urlset>';
file_put_contents($root . '/sitemap-games.xml', $xml2);

// ---------- sitemap-index.xml ----------
$now = date('c');
$xml3 = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml3 .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
$xml3 .= "  <sitemap><loc>" . xml_escape(SITE_URL . '/sitemap-static.xml') . "</loc><lastmod>$now</lastmod></sitemap>\n";
$xml3 .= "  <sitemap><loc>" . xml_escape(SITE_URL . '/sitemap-news.xml') . "</loc><lastmod>$now</lastmod></sitemap>\n";
$xml3 .= "  <sitemap><loc>" . xml_escape(SITE_URL . '/sitemap-games.xml') . "</loc><lastmod>$now</lastmod></sitemap>\n";
$xml3 .= '</sitemapindex>';
file_put_contents($root . '/sitemap-index.xml', $xml3);

// ---------- sitemap-static.xml (home, listing pages) ----------
$staticUrls = ['/index.php', '/news.php', '/games.php'];
$xml4 = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml4 .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($staticUrls as $u) {
    $xml4 .= "  <url>\n    <loc>" . xml_escape(SITE_URL . $u) . "</loc>\n    <lastmod>$now</lastmod>\n    <changefreq>hourly</changefreq>\n    <priority>1.0</priority>\n  </url>\n";
}
$xml4 .= '</urlset>';
file_put_contents($root . '/sitemap-static.xml', $xml4);

meta_set('last_sitemap_build', $now);

// ---------- Ping search engines ----------
$pingTargets = [
    'https://www.google.com/ping?sitemap=' . urlencode(SITE_URL . '/sitemap-index.xml'),
    'https://www.bing.com/ping?sitemap=' . urlencode(SITE_URL . '/sitemap-index.xml'),
];
foreach ($pingTargets as $ping) {
    if (function_exists('curl_init')) {
        $ch = curl_init($ping);
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 8]);
        @curl_exec($ch);
        curl_close($ch);
    } else {
        @file_get_contents($ping, false, stream_context_create(['http' => ['timeout' => 8]]));
    }
}

echo "Sitemaps regenerated: " . count($newsRows) . " news URLs, " . count($gameRows) . " game URLs.\n";
