<?php
/**
 * Dynamic XML Sitemap Generator for Search Engines (Google, Bing, etc.)
 */
require_once __DIR__ . '/config.php';

header('Content-Type: application/xml; charset=UTF-8');
header('X-Robots-Tag: noindex'); // Do not index the sitemap file itself as a web page

$baseUrl = rtrim(SITE_URL, '/') . '/';

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

// The legal registry defines both LEGAL_EFFECTIVE_DATE and $LEGAL_DOCS, and the
// static list below uses the constant, so it has to be loaded first.
require_once __DIR__ . '/includes/legal_docs.php';

// 1. Core Landing Pages
$staticPages = [
    ['loc' => $baseUrl, 'changefreq' => 'daily', 'priority' => '1.0', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'pricing/', 'changefreq' => 'weekly', 'priority' => '0.9', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'public_blog_discover/', 'changefreq' => 'daily', 'priority' => '0.9', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'blog_discover/', 'changefreq' => 'daily', 'priority' => '0.85', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'blogs/', 'changefreq' => 'daily', 'priority' => '0.85', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'forums/', 'changefreq' => 'daily', 'priority' => '0.9', 'lastmod' => date('Y-m-d')],
    ['loc' => APPSTORE_URL, 'changefreq' => 'daily', 'priority' => '0.85', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'mc_servers/', 'changefreq' => 'daily', 'priority' => '0.8', 'lastmod' => date('Y-m-d')],
    ['loc' => $baseUrl . 'legal/', 'changefreq' => 'yearly', 'priority' => '0.4', 'lastmod' => LEGAL_EFFECTIVE_DATE],
];

// 1b. Legal documents, driven off the same registry the pages themselves use.
foreach ($LEGAL_DOCS as $legalDoc) {
    $staticPages[] = [
        'loc'        => $baseUrl . $legalDoc['slug'] . '/',
        'changefreq' => 'yearly',
        'priority'   => '0.4',
        'lastmod'    => LEGAL_EFFECTIVE_DATE,
    ];
}

foreach ($staticPages as $sp) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($sp['loc'], ENT_XML1, 'UTF-8') . "</loc>\n";
    echo "    <lastmod>" . $sp['lastmod'] . "</lastmod>\n";
    echo "    <changefreq>" . $sp['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $sp['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// 2. Published Blog Articles
$bStmt = $conn->query("SELECT blog_id, title, cover_url, updated_at, created_at FROM blogs WHERE status = 'published' ORDER BY updated_at DESC");
if ($bStmt) {
    while ($blog = $bStmt->fetch_assoc()) {
        $blogLoc = $baseUrl . 'read_blog/?id=' . (int)$blog['blog_id'];
        $lastmod = !empty($blog['updated_at']) ? date('Y-m-d', strtotime($blog['updated_at'])) : date('Y-m-d', strtotime($blog['created_at']));
        $cover = !empty($blog['cover_url']) ? getBlogCoverUrl($blog['cover_url']) : '';

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($blogLoc, ENT_XML1, 'UTF-8') . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.80</priority>\n";
        if ($cover) {
            echo "    <image:image>\n";
            echo "      <image:loc>" . htmlspecialchars($cover, ENT_XML1, 'UTF-8') . "</image:loc>\n";
            echo "      <image:title>" . htmlspecialchars($blog['title'], ENT_XML1, 'UTF-8') . "</image:title>\n";
            echo "    </image:image>\n";
        }
        echo "  </url>\n";
    }
}

// 3. Forum Categories
$fStmt = $conn->query("SELECT forum_id, forum_name, last_post_at FROM forums ORDER BY sort_order, forum_id");
if ($fStmt) {
    while ($forum = $fStmt->fetch_assoc()) {
        $forumLoc = $baseUrl . 'forums/?forum=' . (int)$forum['forum_id'];
        $lastmod = !empty($forum['last_post_at']) ? date('Y-m-d', strtotime($forum['last_post_at'])) : date('Y-m-d');

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($forumLoc, ENT_XML1, 'UTF-8') . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>daily</changefreq>\n";
        echo "    <priority>0.75</priority>\n";
        echo "  </url>\n";
    }
}

// 4. Forum Threads
$tStmt = $conn->query("SELECT thread_id, title, last_reply_at, created_at FROM forum_threads WHERE is_deleted = 0 ORDER BY last_reply_at DESC LIMIT 50000");
if ($tStmt) {
    while ($thread = $tStmt->fetch_assoc()) {
        $threadLoc = $baseUrl . 'forums/?thread=' . (int)$thread['thread_id'];
        $lastmod = !empty($thread['last_reply_at']) ? date('Y-m-d', strtotime($thread['last_reply_at'])) : date('Y-m-d', strtotime($thread['created_at']));

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($threadLoc, ENT_XML1, 'UTF-8') . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>daily</changefreq>\n";
        echo "    <priority>0.70</priority>\n";
        echo "  </url>\n";
    }
}

// 5. App Store Listings
$aStmt = $conn->query("SELECT slug, title, updated_at, created_at FROM software_apps WHERE status = 'approved' ORDER BY updated_at DESC");
if ($aStmt) {
    while ($app = $aStmt->fetch_assoc()) {
        $appLoc = APPSTORE_URL . 'app/' . rawurlencode($app['slug']) . '/';
        $lastmod = !empty($app['updated_at']) ? date('Y-m-d', strtotime($app['updated_at'])) : date('Y-m-d', strtotime($app['created_at']));

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($appLoc, ENT_XML1, 'UTF-8') . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.75</priority>\n";
        echo "  </url>\n";
    }
}

// 6. Minecraft Server Listings
$mStmt = $conn->query("SELECT slug, updated_at, created_at FROM minecraft_servers WHERE status = 'approved' ORDER BY updated_at DESC");
if ($mStmt) {
    while ($srv = $mStmt->fetch_assoc()) {
        $srvLoc = $baseUrl . 'mc/' . $srv['slug'] . '/';
        $lastmod = !empty($srv['updated_at']) ? date('Y-m-d', strtotime($srv['updated_at'])) : date('Y-m-d', strtotime($srv['created_at']));

        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($srvLoc, ENT_XML1, 'UTF-8') . "</loc>\n";
        echo "    <lastmod>" . $lastmod . "</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.7</priority>\n";
        echo "  </url>\n";
    }
}

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