<?php
header("Content-Type: application/xml; charset=utf-8");
require_once 'db.php';

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$base_url = $protocol . "://" . $_SERVER['HTTP_HOST'];

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!-- Ana Sayfa -->
    <url>
        <loc><?= $base_url ?>/index.php</loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <?php 
    // Tüm Kategorileri Çek
    try {
        $categories = $db->query("SELECT * FROM categories")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($categories as $cat) {
            // Kategori URL yapın varsa burayı açabilirsin
            // echo '<url><loc>' . $base_url . '/index.php?cat=' . $cat['id'] . '</loc><changefreq>weekly</changefreq><priority>0.7</priority></url>';
        }
    } catch (Exception $e) {
        // Hata sessiz geçilir
    }

    // Tüm Blog Yazılarını Çek (Slug Yapısına Uygun)
    try {
        $posts = $db->query("SELECT id, slug, created_at FROM posts ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($posts as $post) {
            // Projende detay sayfaları slug ile çalışıyorsa:
            $post_url = $base_url . "/detail.php?slug=" . $post['slug'];
            
            $lastmod = !empty($post['created_at']) ? date('c', strtotime($post['created_at'])) : date('c');
            ?>
            <url>
                <loc><?= htmlspecialchars($post_url, ENT_QUOTES, 'UTF-8') ?></loc>
                <lastmod><?= $lastmod ?></lastmod>
                <changefreq>weekly</changefreq>
                <priority>0.8</priority>
            </url>
            <?php
        }
    } catch (Exception $e) {
        // Hata sessiz geçilir
    }
    ?>
</urlset>