<?php
// Load configuration and models
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/models/Game.php';
require_once __DIR__ . '/models/Category.php';
require_once __DIR__ . '/models/Blog.php';
require_once __DIR__ . '/models/Page.php';

// Set content type to XML
header('Content-Type: application/xml; charset=utf-8');

// Get the requested sitemap
$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);

// Get base URL
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . '://' . $host;

// Determine which sitemap to generate
if ($path === '/sitemap.xml') {
    generateSitemapIndex($baseUrl);
} elseif ($path === '/sitemap-games.xml') {
    generateGamesSitemap($baseUrl);
} elseif (preg_match('/\/sitemap-games-(\d+)\.xml/', $path, $matches)) {
    generateGamesSitemap($baseUrl, intval($matches[1]));
} elseif ($path === '/sitemap-categories.xml') {
    generateCategoriesSitemap($baseUrl);
} elseif ($path === '/sitemap-blogs.xml') {
    generateBlogsSitemap($baseUrl);
} elseif (preg_match('/\/sitemap-blogs-(\d+)\.xml/', $path, $matches)) {
    generateBlogsSitemap($baseUrl, intval($matches[1]));
} elseif ($path === '/sitemap-pages.xml') {
    generatePagesSitemap($baseUrl);
} else {
    // If no valid sitemap is requested, return 404
    header("HTTP/1.0 404 Not Found");
    exit;
}

/**
 * Generate the main sitemap index
 */
function generateSitemapIndex($baseUrl) {
    // Initialize models
    $gameModel = new Game();
    $blogModel = new Blog();
    
    // Get total counts
    $totalGames = $gameModel->getTotalGames();
    $totalBlogs = $blogModel->getPostCount();
    
    // Calculate number of game sitemaps needed (5000 URLs per sitemap)
    $gamesSitemapCount = ceil($totalGames / 5000);
    $blogsSitemapCount = ceil($totalBlogs / 5000);
    
    // Start XML output
    echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
    echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    
    // Add categories sitemap (usually small enough for one file)
    echo '  <sitemap>' . PHP_EOL;
    echo '    <loc>' . $baseUrl . '/sitemap-categories.xml</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
    echo '  </sitemap>' . PHP_EOL;
    
    // Add games sitemaps
    for ($i = 0; $i < $gamesSitemapCount; $i++) {
        echo '  <sitemap>' . PHP_EOL;
        if ($i === 0) {
            echo '    <loc>' . $baseUrl . '/sitemap-games.xml</loc>' . PHP_EOL;
        } else {
            echo '    <loc>' . $baseUrl . '/sitemap-games-' . $i . '.xml</loc>' . PHP_EOL;
        }
        echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
        echo '  </sitemap>' . PHP_EOL;
    }
    
    // Add blogs sitemaps
    for ($i = 0; $i < $blogsSitemapCount; $i++) {
        echo '  <sitemap>' . PHP_EOL;
        if ($i === 0) {
            echo '    <loc>' . $baseUrl . '/sitemap-blogs.xml</loc>' . PHP_EOL;
        } else {
            echo '    <loc>' . $baseUrl . '/sitemap-blogs-' . $i . '.xml</loc>' . PHP_EOL;
        }
        echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
        echo '  </sitemap>' . PHP_EOL;
    }
    
    // Add pages sitemap (usually small enough for one file)
    echo '  <sitemap>' . PHP_EOL;
    echo '    <loc>' . $baseUrl . '/sitemap-pages.xml</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
    echo '  </sitemap>' . PHP_EOL;
    
    echo '</sitemapindex>';
}

/**
 * Generate sitemap for games
 */
function generateGamesSitemap($baseUrl, $page = 0) {
    $gameModel = new Game();
    $limit = 5000;
    $offset = $page * $limit;
    
    // Get games for this page
    $games = $gameModel->getAllGames($limit, $offset);
    
    // Start XML output
    echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    
    foreach ($games as $game) {
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . $baseUrl . '/game/' . htmlspecialchars($game['slug']) . '</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c', strtotime($game['updated_at'] ?? 'now')) . '</lastmod>' . PHP_EOL;
        echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
        echo '    <priority>0.8</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
    }
    
    echo '</urlset>';
}

/**
 * Generate sitemap for categories
 */
function generateCategoriesSitemap($baseUrl) {
    $categoryModel = new Category();
    
    // Get all categories
    $categories = $categoryModel->getAllCategories(1000, 0); // Assuming there won't be more than 1000 categories
    
    // Start XML output
    echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    
    // Add categories page
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . $baseUrl . '/categories</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
    echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
    echo '    <priority>0.8</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
    
    foreach ($categories as $category) {
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . $baseUrl . '/category/' . htmlspecialchars($category['slug']) . '</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c', strtotime($category['updated_at'] ?? 'now')) . '</lastmod>' . PHP_EOL;
        echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
        echo '    <priority>0.7</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
    }
    
    echo '</urlset>';
}

/**
 * Generate sitemap for blogs
 */
function generateBlogsSitemap($baseUrl, $page = 0) {
    $blogModel = new Blog();
    $limit = 5000;
    $offset = $page * $limit;
    
    // Get blog posts for this page
    $posts = $blogModel->getAllPosts($limit, $offset);
    
    // Start XML output
    echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    
    // Add main blog page if this is the first page
    if ($page === 0) {
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . $baseUrl . '/blog</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
        echo '    <changefreq>daily</changefreq>' . PHP_EOL;
        echo '    <priority>0.8</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
    }
    
    foreach ($posts as $post) {
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . $baseUrl . '/blog/' . htmlspecialchars($post['slug']) . '</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c', strtotime($post['updated_at'])) . '</lastmod>' . PHP_EOL;
        echo '    <changefreq>monthly</changefreq>' . PHP_EOL;
        echo '    <priority>0.6</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
        
        // Add tag pages if tags exist
        if (!empty($post['tags'])) {
            $tags = explode(',', $post['tags']);
            foreach ($tags as $tag) {
                $tag = trim($tag);
                if (!empty($tag)) {
                    echo '  <url>' . PHP_EOL;
                    echo '    <loc>' . $baseUrl . '/blog/tag/' . urlencode($tag) . '</loc>' . PHP_EOL;
                    echo '    <lastmod>' . date('c', strtotime($post['updated_at'])) . '</lastmod>' . PHP_EOL;
                    echo '    <changefreq>monthly</changefreq>' . PHP_EOL;
                    echo '    <priority>0.5</priority>' . PHP_EOL;
                    echo '  </url>' . PHP_EOL;
                }
            }
        }
    }
    
    echo '</urlset>';
}

/**
 * Generate sitemap for pages
 */
function generatePagesSitemap($baseUrl) {
    $pageModel = new Page();
    
    // Get all pages
    $pages = $pageModel->getAllPages();
    
    // Start XML output
    echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    
    // Add homepage
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . $baseUrl . '/</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
    echo '    <changefreq>daily</changefreq>' . PHP_EOL;
    echo '    <priority>1.0</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
    
    // Add search page
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . $baseUrl . '/search</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
    echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
    echo '    <priority>0.7</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
    
    foreach ($pages as $page) {
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . $baseUrl . '/page/' . htmlspecialchars($page['slug']) . '</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c', strtotime($page['updated_at'])) . '</lastmod>' . PHP_EOL;
        echo '    <changefreq>monthly</changefreq>' . PHP_EOL;
        echo '    <priority>0.6</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
    }
    
    echo '</urlset>';
} 