<?php
// Veritabanı bağlantı bilgileri
$host = 'localhost'; 
$dbname = 'oguzhans_fluetone';
$username = 'oguzhans_fluetone';
$password = 'nedirBuSifre0634+*';

// Content-Type başlığını XML olarak ayarla
header('Content-Type: application/xml; charset=utf-8');

try {
    // PDO bağlantısı oluştur
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Site URL'ini site_settings tablosundan al
    $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = 'site_url'");
    $stmt->execute();
    $site_url = $stmt->fetchColumn();
    
    // Eğer site_url boşsa, varsayılan bir değer kullan
    if (empty($site_url)) {
        $host = $_SERVER['HTTP_HOST'] ?? 'old.fluetone.com';
        $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') == 443);
        $site_url = ($is_https ? 'https' : 'http') . '://' . $host;
    }
    
    // Site URL'inin sonundaki / karakterini kaldır
    $site_url = rtrim($site_url, '/');
    
    // XML sitemap başlangıcı
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    
    // Ana sayfa
    echo '  <url>' . "\n";
    echo '    <loc>' . htmlspecialchars($site_url . '/') . '</loc>' . "\n";
    echo '    <lastmod>' . date('c') . '</lastmod>' . "\n";
    echo '    <changefreq>daily</changefreq>' . "\n";
    echo '    <priority>1.0</priority>' . "\n";
    echo '  </url>' . "\n";
    
    // Statik sayfalar
    $static_pages = [
        'blog' => ['changefreq' => 'daily', 'priority' => '0.8']
    ];
    
    foreach ($static_pages as $page => $settings) {
        echo '  <url>' . "\n";
        echo '    <loc>' . htmlspecialchars($site_url . '/' . $page) . '</loc>' . "\n";
        echo '    <lastmod>' . date('c') . '</lastmod>' . "\n";
        echo '    <changefreq>' . $settings['changefreq'] . '</changefreq>' . "\n";
        echo '    <priority>' . $settings['priority'] . '</priority>' . "\n";
        echo '  </url>' . "\n";
    }
    
    // Blog kategorileri
    $stmt = $pdo->prepare("
        SELECT slug, updated_at 
        FROM blog_categories 
        WHERE is_active = 1 
        ORDER BY sort_order ASC, name ASC
    ");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($categories as $category) {
        echo '  <url>' . "\n";
        echo '    <loc>' . htmlspecialchars($site_url . '/blog/kategori/' . $category['slug']) . '</loc>' . "\n";
        echo '    <lastmod>' . date('c', strtotime($category['updated_at'])) . '</lastmod>' . "\n";
        echo '    <changefreq>weekly</changefreq>' . "\n";
        echo '    <priority>0.7</priority>' . "\n";
        echo '  </url>' . "\n";
    }
    
    // Blog yazıları
    $stmt = $pdo->prepare("
        SELECT bp.slug, bp.updated_at, bp.published_at
        FROM blog_posts bp 
        WHERE bp.is_published = 1 
        AND bp.published_at IS NOT NULL 
        AND bp.published_at <= NOW()
        ORDER BY bp.published_at DESC
    ");
    $stmt->execute();
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($posts as $post) {
        echo '  <url>' . "\n";
        echo '    <loc>' . htmlspecialchars($site_url . '/blog/' . $post['slug']) . '</loc>' . "\n";
        echo '    <lastmod>' . date('c', strtotime($post['updated_at'])) . '</lastmod>' . "\n";
        echo '    <changefreq>monthly</changefreq>' . "\n";
        echo '    <priority>0.8</priority>' . "\n";
        echo '  </url>' . "\n";
    }
    
    // XML sitemap sonu
    echo '</urlset>';
    
} catch(PDOException $e) {
    // Hata durumunda basit bir sitemap döndür
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    echo '  <url>' . "\n";
    $fallback_host = $_SERVER['HTTP_HOST'] ?? 'old.fluetone.com';
    $fallback_is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') == 443);
    $fallback_url = ($fallback_is_https ? 'https' : 'http') . '://' . $fallback_host . '/';
    echo '    <loc>' . htmlspecialchars($fallback_url, ENT_XML1, 'UTF-8') . '</loc>' . "\n";
    echo '    <lastmod>' . date('c') . '</lastmod>' . "\n";
    echo '    <changefreq>daily</changefreq>' . "\n";
    echo '    <priority>1.0</priority>' . "\n";
    echo '  </url>' . "\n";
    echo '</urlset>';
    
    // Hata logla (opsiyonel)
    error_log("Sitemap Error: " . $e->getMessage());
}

/**
 * Türkçe metin için URL dostu slug oluşturur
 * @param string $text
 * @return string
 */
function create_slug($text) {
    // Türkçe karakterleri değiştir
    $turkish = ['ç', 'ğ', 'ı', 'ö', 'ş', 'ü', 'Ç', 'Ğ', 'I', 'İ', 'Ö', 'Ş', 'Ü'];
    $english = ['c', 'g', 'i', 'o', 's', 'u', 'c', 'g', 'i', 'i', 'o', 's', 'u'];
    $text = str_replace($turkish, $english, $text);
    
    // Küçük harfe çevir
    $text = strtolower($text);
    
    // Alfanumerik olmayan karakterleri tire ile değiştir
    $text = preg_replace('/[^a-z0-9]/', '-', $text);
    
    // Birden fazla tireyi tek tireye çevir
    $text = preg_replace('/-+/', '-', $text);
    
    // Başındaki ve sonundaki tireleri kaldır
    $text = trim($text, '-');
    
    return $text;
}
?>