<?php
/**
 * Sadi Armatür - Dinamik Sitemap.xml
 * Otomatik ürün ve kategori entegrasyonu
 */
header('Content-Type: application/xml; charset=utf-8');

include_once 'db.php';

// Site bilgileri
$base_url = 'https://sadi.com.tr';
$today = date('Y-m-d');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
    
    <!-- Ana Sayfa -->
    <url>
        <loc><?= $base_url ?>/</loc>
        <lastmod><?= $today ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    
    <!-- İletişim -->
    <url>
        <loc><?= $base_url ?>/iletisim</loc>
        <lastmod><?= $today ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.8</priority>
    </url>
    
    <!-- Ürün Kategorileri -->
    <?php
    try {
        $gruplar = $db->query("SELECT GrupID, GrupAdi FROM urun_gruplari ORDER BY sira ASC")->fetchAll();
        
        foreach ($gruplar as $grup) {
            $grup_url = $base_url . '/kategori/' . sef_link($grup['GrupAdi']) . '-' . $grup['GrupID'];
            echo "
    <url>
        <loc>" . htmlspecialchars($grup_url) . "</loc>
        <lastmod>{$today}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.9</priority>
    </url>";
        }
    } catch (Exception $e) {
        error_log("Sitemap kategori hatası: " . $e->getMessage());
    }
    ?>
    
    <!-- Ürünler -->
    <?php
    try {
        $urunler = $db->query("
            SELECT UrunID, UrunKodu, UrunAdi, Resim1 
            FROM urunler 
            WHERE Durum = 'aktif' 
            ORDER BY UrunID DESC 
            LIMIT 1000
        ")->fetchAll();
        
        foreach ($urunler as $urun) {
            $urun_url = $base_url . '/urun/' . sef_link($urun['UrunKodu']) . '-' . $urun['UrunID'];
            
            echo "
    <url>
        <loc>" . htmlspecialchars($urun_url) . "</loc>
        <lastmod>{$today}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>";
            
            // Ürün görseli varsa ekle
            if (!empty($urun['Resim1'])) {
                $image_url = $base_url . '/images/urunler/' . basename($urun['Resim1']);
                echo "
        <image:image>
            <image:loc>" . htmlspecialchars($image_url) . "</image:loc>
            <image:title>" . htmlspecialchars($urun['UrunAdi']) . "</image:title>
        </image:image>";
            }
            
            echo "
    </url>";
        }
    } catch (Exception $e) {
        error_log("Sitemap ürün hatası: " . $e->getMessage());
    }
    ?>
    
</urlset>