<?php

declare(strict_types=1);

if (ob_get_level()) {
    ob_end_clean();
}

header('Content-Type: application/xml; charset=UTF-8');
header('Cache-Control: public, max-age=900'); 
header('X-Robots-Tag: noindex');

require_once __DIR__ . '/config/config.php';

$settings = function_exists('getAllSettings') ? getAllSettings() : [];
$siteName = $settings['site_name'] ?? 'ServerList101';
$base = rtrim(APP_URL, '/');

$news = [];

try {
    $db = db();
    $driver = strtolower((string)$db->getAttribute(PDO::ATTR_DRIVER_NAME));
    $isMysql = str_contains($driver, 'mysql');

    // 1. Published News Articles
    try {
        $stmt = $db->query("
            SELECT id, slug, title, game_slug, lang, published_at
            FROM news_articles
            WHERE status = 'published'
            ORDER BY published_at DESC
            LIMIT 100
        ");
        $artRows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        foreach ($artRows as $ar) {
            $news[] = [
                'loc' => $base . '/news/' . urlencode((string)$ar['slug']),
                'published' => date('c', strtotime((string)$ar['published_at'])),
                'title' => (string)$ar['title'],
                'keywords' => sprintf('%s guide, gaming update, %s', (string)($ar['game_slug'] ?? 'gaming'), $siteName),
                'genre' => 'Blog',
                'language' => !empty($ar['lang']) ? (string)$ar['lang'] : 'en',
            ];
        }
    } catch (Throwable $e) {}

    // 2. Freshly Added Servers (Last 48 Hours)
    try {
        $serverWhere = $isMysql ? "s.created_at >= DATE_SUB(NOW(), INTERVAL 48 HOUR)" : "s.created_at >= datetime('now', '-48 hours')";
        $stmt = $db->query("
            SELECT s.id, s.slug AS server_slug, s.name, s.created_at,
                   COALESCE(g.slug, c.slug, 'game') AS game_slug,
                   COALESCE(g.name, c.name, 'Game') AS game_name
            FROM servers s
            LEFT JOIN games g ON (s.game_id = g.id OR s.category_id = g.id)
            LEFT JOIN categories c ON (s.category_id = c.id OR s.game_id = c.id)
            WHERE s.is_active = 1
              AND s.slug IS NOT NULL AND s.slug != ''
              AND {$serverWhere}
            ORDER BY s.created_at DESC
            LIMIT 500
        ");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        foreach ($rows as $r) {
            if (empty($r['server_slug'])) continue;
            $news[] = [
                'loc' => $base . '/server/' . urlencode((string)$r['server_slug']),
                'published' => date('c', strtotime((string)$r['created_at'])),
                'title' => sprintf('New %s server: %s', (string)($r['game_name'] ?? 'Multiplayer'), (string)$r['name']),
                'keywords' => sprintf('%s server, new server, %s', (string)($r['game_slug'] ?? ''), $siteName),
                'genre' => 'Directory',
            ];
        }
    } catch (Throwable $e) {}
} catch (Throwable $e) {
    $news = [];
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
<?php foreach ($news as $n): ?>
    <url>
        <loc><?= htmlspecialchars($n['loc'], ENT_XML1, 'UTF-8') ?></loc>
        <news:news>
            <news:publication>
                <news:name><?= htmlspecialchars($siteName, ENT_XML1, 'UTF-8') ?></news:name>
                <news:language><?= htmlspecialchars($n['language'] ?? 'en', ENT_XML1, 'UTF-8') ?></news:language>
            </news:publication>
            <news:publication_date><?= $n['published'] ?></news:publication_date>
            <news:title><?= htmlspecialchars($n['title'], ENT_XML1, 'UTF-8') ?></news:title>
            <news:keywords><?= htmlspecialchars($n['keywords'], ENT_XML1, 'UTF-8') ?></news:keywords>
            <news:genres><?= htmlspecialchars($n['genre'], ENT_XML1, 'UTF-8') ?></news:genres>
        </news:news>
    </url>
<?php endforeach; ?>
</urlset>
