<?php
// Tüm output buffer'ları temizle
while (ob_get_level() > 0) {
    ob_end_clean();
}
ob_start();

// Config ve helper'ları yükle
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/blog-helper.php';

// Buffer'ı temizle
ob_clean();

// Header
header('Content-Type: application/xml; charset=utf-8');

// Database
$db = getDB();

// Posts
$stmt = $db->query("SELECT id, slug, title, featured_image, date, updated_at FROM blog_posts WHERE status = 'published' AND featured_image IS NOT NULL AND featured_image != '' ORDER BY date DESC");
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// XML output
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
echo "\n";

foreach ($posts as $post) {
    if (empty($post['featured_image'])) continue;
    
    $postUrl = SITE_URL . '/blog-post.php?post=' . urlencode($post['slug']);
    $imagePath = ltrim($post['featured_image'], '/');
    $imageUrl = SITE_URL . IMAGES_PATH . $imagePath;
    
    $postUrlEscaped = htmlspecialchars($postUrl, ENT_XML1 | ENT_QUOTES, 'UTF-8', false);
    $imageUrlEscaped = htmlspecialchars($imageUrl, ENT_XML1 | ENT_QUOTES, 'UTF-8', false);
    $titleEscaped = htmlspecialchars($post['title'], ENT_XML1 | ENT_QUOTES, 'UTF-8', false);
    $captionEscaped = htmlspecialchars($post['title'] . ' - Esat Can Travel', ENT_XML1 | ENT_QUOTES, 'UTF-8', false);
    $lastmod = date('Y-m-d', strtotime($post['updated_at'] ?? $post['date']));
    
    echo "  <url>\n";
    echo "    <loc>" . $postUrlEscaped . "</loc>\n";
    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
    echo "    <image:image>\n";
    echo "      <image:loc>" . $imageUrlEscaped . "</image:loc>\n";
    echo "      <image:title>" . $titleEscaped . "</image:title>\n";
    echo "      <image:caption>" . $captionEscaped . "</image:caption>\n";
    echo "    </image:image>\n";
    echo "  </url>\n";
}

echo '</urlset>';
echo "\n";
