<?php
/**
 * Hard2Global — Dynamic Sitemap XML
 * https://hard2global.com/sitemap.xml (nginx routes sitemap.xml → sitemap.php)
 */
require_once __DIR__ . '/backend/config/config.php';
require_once __DIR__ . '/backend/config/database.php';
require_once __DIR__ . '/backend/includes/functions.php';

header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>';

$base = rtrim(SITE_URL, '/');
$db   = DB::get();

// Static pages
$staticPages = [
    ['loc' => '/',              'priority' => '1.0',  'changefreq' => 'daily'],
    ['loc' => '/download',      'priority' => '0.9',  'changefreq' => 'weekly'],
    ['loc' => '/support',       'priority' => '0.7',  'changefreq' => 'weekly'],
    ['loc' => '/patch-notes',   'priority' => '0.8',  'changefreq' => 'daily'],
    ['loc' => '/register',      'priority' => '0.8',  'changefreq' => 'monthly'],
    ['loc' => '/login',         'priority' => '0.6',  'changefreq' => 'monthly'],
    ['loc' => '/terms',         'priority' => '0.3',  'changefreq' => 'yearly'],
    ['loc' => '/privacy',       'priority' => '0.3',  'changefreq' => 'yearly'],
];

// Add ranking if live mode
$siteMode = get_setting('site_mode', 'prelaunch');
if ($siteMode === 'live') {
    $staticPages[] = ['loc' => '/ranking', 'priority' => '0.8', 'changefreq' => 'hourly'];
}

// Fetch published patch notes
$notes = $db->query("SELECT slug, updated_at FROM patch_notes WHERE status='published' ORDER BY published_at DESC LIMIT 100")->fetchAll();

echo "\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";

// Static
foreach ($staticPages as $p) {
    echo "\n  <url>";
    echo "\n    <loc>{$base}{$p['loc']}</loc>";
    echo "\n    <changefreq>{$p['changefreq']}</changefreq>";
    echo "\n    <priority>{$p['priority']}</priority>";
    echo "\n  </url>";
}

// Patch notes
foreach ($notes as $n) {
    $lastmod = date('Y-m-d', strtotime($n['updated_at']));
    echo "\n  <url>";
    echo "\n    <loc>{$base}/patch-notes/" . e($n['slug']) . "</loc>";
    echo "\n    <lastmod>{$lastmod}</lastmod>";
    echo "\n    <changefreq>monthly</changefreq>";
    echo "\n    <priority>0.6</priority>";
    echo "\n  </url>";
}

echo "\n</urlset>";
