<?php
/**
 * Dynamic Sitemap Generator
 * Automatically generates sitemap from database
 * Cache: 1 hour TTL for performance
 */

// IMPORTANT: Set XML headers BEFORE any output
header('Content-Type: application/xml; charset=utf-8');

// Suppress errors from output
error_reporting(0);
ini_set('display_errors', '0');

require_once 'config.php';

// Cache configuration
$cacheFile = __DIR__ . '/cache/sitemap_cache.xml';
$cacheTime = 3600; // 1 hour

// Check if cache exists and is fresh
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
    readfile($cacheFile);
    exit;
}

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

// Get base URL from settings or config
$baseUrl = rtrim(getSetting('site_url', 'https://berogame.com'), '/');
if (empty($baseUrl) || $baseUrl === 'https://') {
    $baseUrl = 'https://berogame.com';
}

// Helper function to add URL to sitemap
function addUrl(string $loc, string $lastmod, string $changefreq, string $priority): string
{
    $url = "  <url>\n";
    $url .= "    <loc>" . htmlspecialchars($loc, ENT_XML1, 'UTF-8') . "</loc>\n";
    $url .= "    <lastmod>" . htmlspecialchars($lastmod, ENT_XML1, 'UTF-8') . "</lastmod>\n";
    $url .= "    <changefreq>" . htmlspecialchars($changefreq, ENT_XML1, 'UTF-8') . "</changefreq>\n";
    $url .= "    <priority>" . htmlspecialchars($priority, ENT_XML1, 'UTF-8') . "</priority>\n";
    $url .= "  </url>\n";
    return $url;
}

try {
    // 1. Homepage (highest priority)
    $sitemap .= addUrl(
        $baseUrl . '/',
        date('c'),
        'daily',
        '1.0'
    );

    // 2. Main pages
    $mainPages = [
        ['url' => '/urunler', 'changefreq' => 'daily', 'priority' => '0.9'],
        ['url' => '/marketplace', 'changefreq' => 'daily', 'priority' => '0.8'],
    ];

    foreach ($mainPages as $page) {
        $sitemap .= addUrl(
            $baseUrl . $page['url'],
            date('c'),
            $page['changefreq'],
            $page['priority']
        );
    }

    // 3. Active products
    $productsStmt = $pdo->query("
        SELECT slug, updated_at, created_at 
        FROM products 
        WHERE is_active = 1 
        ORDER BY created_at DESC
    ");

    while ($product = $productsStmt->fetch(PDO::FETCH_ASSOC)) {
        $lastmod = !empty($product['updated_at']) ? $product['updated_at'] : $product['created_at'];
        $sitemap .= addUrl(
            $baseUrl . '/urun/' . urlencode($product['slug']),
            date('c', strtotime($lastmod)),
            'weekly',
            '0.7'
        );
    }

    // 4. Active categories
    $categoriesStmt = $pdo->query("
        SELECT slug, updated_at, created_at 
        FROM categories 
        WHERE is_active = 1 
        ORDER BY display_order ASC, name ASC
    ");

    while ($category = $categoriesStmt->fetch(PDO::FETCH_ASSOC)) {
        $lastmod = !empty($category['updated_at']) ? $category['updated_at'] : $category['created_at'];
        $sitemap .= addUrl(
            $baseUrl . '/kategori/' . urlencode($category['slug']),
            date('c', strtotime($lastmod)),
            'weekly',
            '0.8'
        );
    }

    // 5. Static pages
    try {
        $pagesStmt = $pdo->query("
            SELECT slug, updated_at, created_at 
            FROM pages 
            WHERE is_active = 1 
            ORDER BY created_at DESC
        ");

        while ($page = $pagesStmt->fetch(PDO::FETCH_ASSOC)) {
            $lastmod = !empty($page['updated_at']) ? $page['updated_at'] : $page['created_at'];
            $sitemap .= addUrl(
                $baseUrl . '/sayfa/' . urlencode($page['slug']),
                date('c', strtotime($lastmod)),
                'monthly',
                '0.5'
            );
        }
    } catch (Exception $e) {
        // Pages table might not exist, skip silently
    }

    // 6. Blog posts (if blog table exists)
    try {
        $blogStmt = $pdo->query("
            SELECT slug, updated_at, created_at 
            FROM blog_posts 
            WHERE is_active = 1 
            ORDER BY created_at DESC
        ");

        while ($post = $blogStmt->fetch(PDO::FETCH_ASSOC)) {
            $lastmod = !empty($post['updated_at']) ? $post['updated_at'] : $post['created_at'];
            $sitemap .= addUrl(
                $baseUrl . '/blog/' . urlencode($post['slug']),
                date('c', strtotime($lastmod)),
                'monthly',
                '0.6'
            );
        }
    } catch (Exception $e) {
        // Blog table might not exist, skip silently
    }

} catch (Exception $e) {
    // If any error occurs, output a minimal sitemap with just homepage
    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    $sitemap .= addUrl($baseUrl . '/', date('c'), 'daily', '1.0');
    error_log('Sitemap generation error: ' . $e->getMessage());
}

// Close sitemap
$sitemap .= '</urlset>';

// Save to cache
$cacheDir = dirname($cacheFile);
if (!is_dir($cacheDir)) {
    mkdir($cacheDir, 0755, true);
}
file_put_contents($cacheFile, $sitemap);

// Output
echo $sitemap;
