<?php

declare(strict_types=1);

while (ob_get_level()) {
    ob_end_clean();
}

error_reporting(0);
ini_set('display_errors', '0');

if (!headers_sent()) {
    header('Content-Type: application/xml; charset=UTF-8', true);
    header('X-Content-Type-Options: nosniff');
    header('Cache-Control: public, max-age=3600');
}

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

$baseUrl = rtrim(APP_URL, '/');
$db = db();
$today = date('Y-m-d');

$siteLm = $today;
try {
    $mx = $db->query("SELECT MAX(updated_at) FROM servers WHERE is_active = 1")->fetchColumn();
    if ($mx) {
        $siteLm = date('Y-m-d', strtotime((string)$mx));
    }
} catch (Throwable $e) {}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// 1. Homepage
echo "  <url>\n";
echo "    <loc>" . htmlspecialchars($baseUrl . '/', ENT_XML1) . "</loc>\n";
echo "    <lastmod>{$siteLm}</lastmod>\n";
echo "  </url>\n";

// 2. Core Public Static Pages (strictly indexable, no redirecting or login-only pages)
$staticPages = [
    'servers'           => ['daily', '0.9'],
    'add-server'        => ['monthly', '0.8'],
    'recruitment'       => ['daily', '0.8'],
    'news'              => ['daily', '0.8'],
    'glossary'          => ['weekly', '0.8'],
    'quiz'              => ['weekly', '0.7'],
    'server-of-the-day' => ['daily', '0.7'],
    'stats'             => ['daily', '0.6'],
    'tools/ping-checker' => ['daily', '0.9'],
    'tools/discord-inspector' => ['daily', '0.9'],
    'tools/votifier-test' => ['daily', '0.9'],
    'faq'               => ['weekly', '0.7'],
    'contact'           => ['monthly', '0.5']
];
if (function_exists('isVipEnabled') && isVipEnabled()) {
    $staticPages['promote'] = ['weekly', '0.8'];
}

foreach ($staticPages as $slug => $meta) {
    $loc = $baseUrl . '/' . $slug;
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
    echo "    <lastmod>{$siteLm}</lastmod>\n";
    echo "  </url>\n";
}

// 3. Active Games & Game Modes with at least 1 active server
try {
    $games = $db->query("SELECT id, slug, name FROM games WHERE is_active = 1 ORDER BY sort_order ASC, name ASC")->fetchAll();
    $modes = $db->query("SELECT id, slug FROM game_modes WHERE is_active = 1 AND (type = 'game' OR type IS NULL OR type = '') ORDER BY display_order ASC")->fetchAll();

    // Query active server modes to find which (game_id, mode_slug) actually have servers
    $activeModePairs = [];
    
    // Check via server_modes table
    $smStmt = $db->query("
        SELECT DISTINCT COALESCE(s.game_id, s.category_id) AS gid, gm.slug AS mslug, MAX(s.updated_at) AS lastmod
        FROM servers s
        JOIN server_modes sm ON sm.server_id = s.id
        JOIN game_modes gm ON sm.mode_id = gm.id
        WHERE s.is_active = 1 AND gm.is_active = 1
        GROUP BY gid, mslug
    ");
    if ($smStmt) {
        while ($row = $smStmt->fetch(PDO::FETCH_ASSOC)) {
            if (!empty($row['gid']) && !empty($row['mslug'])) {
                $activeModePairs[(int)$row['gid']][$row['mslug']] = !empty($row['lastmod']) ? date('Y-m-d', strtotime((string)$row['lastmod'])) : $siteLm;
            }
        }
    }

    // Also check via server tags
    foreach ($modes as $m) {
        $mSlug = (string)$m['slug'];
        $tagStmt = $db->prepare("
            SELECT COALESCE(s.game_id, s.category_id) AS gid, MAX(s.updated_at) AS lastmod
            FROM servers s
            WHERE s.is_active = 1 AND s.tags LIKE ?
            GROUP BY gid
        ");
        if ($tagStmt) {
            $tagStmt->execute(['%' . $mSlug . '%']);
            while ($tRow = $tagStmt->fetch(PDO::FETCH_ASSOC)) {
                $gid = (int)$tRow['gid'];
                if (!isset($activeModePairs[$gid][$mSlug])) {
                    $activeModePairs[$gid][$mSlug] = !empty($tRow['lastmod']) ? date('Y-m-d', strtotime((string)$tRow['lastmod'])) : $siteLm;
                }
            }
        }
    }

    foreach ($games as $g) {
        $gSlug = slugify((string)$g['slug']);
        $gId = (int)$g['id'];
        $loc = $baseUrl . '/game/' . $gSlug;
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
        echo "    <lastmod>{$siteLm}</lastmod>\n";
        echo "  </url>\n";

        // ONLY output game modes if this game has active servers with that mode!
        if (!empty($activeModePairs[$gId])) {
            foreach ($activeModePairs[$gId] as $mSlug => $mLastmod) {
                $mSlug = slugify((string)$mSlug);
                $modeLoc = $baseUrl . '/game/' . $gSlug . '/' . $mSlug;
                echo "  <url>\n";
                echo "    <loc>" . htmlspecialchars($modeLoc, ENT_XML1) . "</loc>\n";
                echo "    <lastmod>{$mLastmod}</lastmod>\n";
                echo "  </url>\n";
            }
        }
    }
} catch (Throwable $e) {}

// 4. Active Servers (Strictly Slugified - No Spaces)
try {
    $servers = $db->query("
        SELECT s.id, s.name, s.slug, s.updated_at
        FROM servers s
        WHERE s.is_active = 1
        ORDER BY s.is_vip DESC, s.votes_month DESC, s.online_players DESC
        LIMIT 1000
    ")->fetchAll();

    foreach ($servers as $srv) {
        $srvLm = !empty($srv['updated_at']) ? date('Y-m-d', strtotime((string)$srv['updated_at'])) : $today;
        $rawSrvSlug = !empty($srv['slug']) ? (string)$srv['slug'] : (!empty($srv['name']) ? (string)$srv['name'] : (string)$srv['id']);
        $srvSlug = slugify($rawSrvSlug);
        $loc = $baseUrl . '/server/' . $srvSlug;
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
        echo "    <lastmod>{$srvLm}</lastmod>\n";
        echo "  </url>\n";
    }
} catch (Throwable $e) {}

// 5. Published News Articles (real published articles only)
try {
    $articles = $db->query("
        SELECT slug, lang, updated_at, published_at
        FROM news_articles
        WHERE status = 'published'
        ORDER BY published_at DESC
        LIMIT 200
    ")->fetchAll();

    foreach ($articles as $art) {
        $artLm = !empty($art['updated_at']) ? date('Y-m-d', strtotime((string)$art['updated_at'])) : (!empty($art['published_at']) ? date('Y-m-d', strtotime((string)$art['published_at'])) : $today);
        $artSlug = (string)$art['slug'];
        $langPfx = (!empty($art['lang']) && $art['lang'] !== 'en') ? ('/' . $art['lang']) : '';
        $loc = $baseUrl . $langPfx . '/news/' . $artSlug;
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
        echo "    <lastmod>{$artLm}</lastmod>\n";
        echo "  </url>\n";
    }
} catch (Throwable $e) {}

// 6. Active Recruitment Posts (real active posts only)
try {
    $recruitments = $db->query("
        SELECT id, title, slug, updated_at, created_at
        FROM recruitments
        WHERE (status = 'active' OR status = 'open')
          AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
        ORDER BY created_at DESC
        LIMIT 100
    ")->fetchAll();

    foreach ($recruitments as $rc) {
        $rcLm = !empty($rc['updated_at']) ? date('Y-m-d', strtotime((string)$rc['updated_at'])) : (!empty($rc['created_at']) ? date('Y-m-d', strtotime((string)$rc['created_at'])) : $today);
        $rawRcSlug = !empty($rc['slug']) ? (string)$rc['slug'] : (!empty($rc['title']) ? (string)$rc['title'] : (string)$rc['id']);
        $rcSlug = slugify($rawRcSlug);
        $loc = $baseUrl . '/recruitment/' . $rcSlug;
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
        echo "    <lastmod>{$rcLm}</lastmod>\n";
        echo "  </url>\n";
    }
} catch (Throwable $e) {}

// 7. Public User Profiles (only active users with public profiles)
try {
    $users = $db->query("
        SELECT id, username, slug, updated_at, created_at
        FROM users
        WHERE status = 'active'
          AND public_profile = 1
        ORDER BY created_at DESC
        LIMIT 500
    ")->fetchAll();

    foreach ($users as $u) {
        $uLm = !empty($u['updated_at']) ? date('Y-m-d', strtotime((string)$u['updated_at'])) : (!empty($u['created_at']) ? date('Y-m-d', strtotime((string)$u['created_at'])) : $today);
        $rawUserSlug = !empty($u['slug']) ? (string)$u['slug'] : (string)$u['username'];
        $uSlug = preg_replace('/[^a-zA-Z0-9_.-]/', '', $rawUserSlug);
        if ($uSlug !== '') {
            $loc = $baseUrl . '/user/' . urlencode($uSlug);
            echo "  <url>\n";
            echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
            echo "    <lastmod>{$uLm}</lastmod>\n";
            echo "  </url>\n";
        }
    }
} catch (Throwable $e) {}

echo '</urlset>' . "\n";
