<?php
// =========================================================
// OYUN ŞAHİNİ - DİNAMİK SITEMAP (BLOG ENTEGRELİ TAM)
// =========================================================

require_once __DIR__ . '/config.php';

header("Content-Type: application/xml; charset=utf-8");
header("Cache-Control: public, max-age=3600");

$baseUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : 'https://oyunsahini.com';

echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . PHP_EOL;

// ============================================================
// 1. ANA SAYFA
// ============================================================
echo "  <url>\n";
echo "    <loc>{$baseUrl}/</loc>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>1.0</priority>\n";
echo "  </url>\n";

// ============================================================
// 2. KURUMSAL SAYFALAR
// ============================================================
$pages = [
    ['url' => '/about', 'priority' => '0.6'],
    ['url' => '/contact', 'priority' => '0.5'],
    ['url' => '/privacy', 'priority' => '0.3'],
    ['url' => '/populer', 'priority' => '0.8'],
];

foreach ($pages as $page) {
    echo "  <url>\n";
    echo "    <loc>{$baseUrl}{$page['url']}</loc>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>{$page['priority']}</priority>\n";
    echo "  </url>\n";
}

// ============================================================
// 3. BLOG ANA SAYFA
// ============================================================
echo "  <url>\n";
echo "    <loc>{$baseUrl}/blog/</loc>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>0.9</priority>\n";
echo "  </url>\n";

// ============================================================
// 4. OYUN KATEGORİLERİ
// ============================================================
$categories = ['adventure', 'online', 'car', '2-player', 'war', 'mario', 'retro', 'flash', 'girl', 'io', 'sport', 'brain'];

foreach ($categories as $slug) {
    echo "  <url>\n";
    echo "    <loc>{$baseUrl}/category/{$slug}</loc>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>0.8</priority>\n";
    echo "  </url>\n";
}

// ============================================================
// 5. BLOG KATEGORİLERİ
// ============================================================
try {
    $blogCats = $pdo->query("
        SELECT slug, 
               (SELECT MAX(published_at) FROM blog_posts WHERE category_id = blog_categories.id AND is_published = 1) AS lastmod
        FROM blog_categories 
        WHERE is_active = 1
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($blogCats as $cat) {
        echo "  <url>\n";
        echo "    <loc>{$baseUrl}/blog/category/{$cat['slug']}</loc>\n";
        if (!empty($cat['lastmod'])) {
            echo "    <lastmod>" . date('Y-m-d', strtotime($cat['lastmod'])) . "</lastmod>\n";
        }
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.7</priority>\n";
        echo "  </url>\n";
    }
} catch (Exception $e) {
    // Sessiz kal
}

// ============================================================
// 6. BLOG ETİKETLERİ
// ============================================================
try {
    $blogTags = $pdo->query("
        SELECT t.slug,
               (SELECT MAX(p.published_at) FROM blog_posts p 
                JOIN blog_post_tags pt ON p.id = pt.post_id 
                WHERE pt.tag_id = t.id AND p.is_published = 1) AS lastmod
        FROM blog_tags t
        WHERE EXISTS (SELECT 1 FROM blog_post_tags WHERE tag_id = t.id)
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($blogTags as $tag) {
        echo "  <url>\n";
        echo "    <loc>{$baseUrl}/blog/tag/{$tag['slug']}</loc>\n";
        if (!empty($tag['lastmod'])) {
            echo "    <lastmod>" . date('Y-m-d', strtotime($tag['lastmod'])) . "</lastmod>\n";
        }
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.4</priority>\n";
        echo "  </url>\n";
    }
} catch (Exception $e) {
    // Sessiz kal
}

// ============================================================
// 7. BLOG YAZILARI (Google News + Image)
// ============================================================
try {
    $blogPosts = $pdo->query("
        SELECT slug, title, published_at, updated_at, featured_image
        FROM blog_posts 
        WHERE is_published = 1 
        ORDER BY published_at DESC
        LIMIT 5000
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($blogPosts as $post) {
        $lastmod = date('Y-m-d', strtotime($post['updated_at'] ?? $post['published_at']));
        $isNews  = strtotime($post['published_at']) > strtotime('-2 days');
        
        echo "  <url>\n";
        echo "    <loc>{$baseUrl}/blog/{$post['slug']}</loc>\n";
        echo "    <lastmod>{$lastmod}</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.7</priority>\n";
        
        // Öne çıkan görsel
        if (!empty($post['featured_image'])) {
            $imgUrl = str_starts_with($post['featured_image'], 'http') 
                ? $post['featured_image'] 
                : $baseUrl . '/' . ltrim($post['featured_image'], '/');
            echo "    <image:image>\n";
            echo "      <image:loc>" . htmlspecialchars($imgUrl) . "</image:loc>\n";
            echo "      <image:title><![CDATA[" . htmlspecialchars($post['title']) . "]]></image:title>\n";
            echo "    </image:image>\n";
        }
        
        // Google News (son 2 gün)
        if ($isNews) {
            echo "    <news:news>\n";
            echo "      <news:publication>\n";
            echo "        <news:name>Oyun Şahini</news:name>\n";
            echo "        <news:language>tr</news:language>\n";
            echo "      </news:publication>\n";
            echo "      <news:publication_date>" . date('Y-m-d', strtotime($post['published_at'])) . "</news:publication_date>\n";
            echo "      <news:title><![CDATA[" . htmlspecialchars($post['title']) . "]]></news:title>\n";
            echo "    </news:news>\n";
        }
        
        echo "  </url>\n";
    }
} catch (Exception $e) {
    // Sessiz kal
}

// ============================================================
// 8. OYUNLAR (VERİTABANINDAN)
// ============================================================
try {
    $stmt = $pdo->query("
        SELECT slug, created_at 
        FROM games 
        WHERE is_active = 1 
        ORDER BY created_at DESC
        LIMIT 10000
    ");

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $date = date('Y-m-d', strtotime($row['created_at']));
        echo "  <url>\n";
        echo "    <loc>{$baseUrl}/game/{$row['slug']}</loc>\n";
        echo "    <lastmod>{$date}</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.6</priority>\n";
        echo "  </url>\n";
    }
} catch (Exception $e) {
    // Sessiz kal
}

echo '</urlset>';