<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml"
        xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">

<?php
// Dynamic sitemap generation
require_once 'config.php';

try {
    $pdo = getDbConnection();
    $base_url = 'https://localhost:8000';
    
    // Homepage
    echo "<url>\n";
    echo "  <loc>{$base_url}/</loc>\n";
    echo "  <lastmod>" . date('c') . "</lastmod>\n";
    echo "  <changefreq>daily</changefreq>\n";
    echo "  <priority>1.0</priority>\n";
    echo "</url>\n";
    
    // Blog posts
    $stmt = $pdo->prepare("
        SELECT slug, published_at, updated_at 
        FROM blog_posts 
        WHERE status = 'published' 
        ORDER BY published_at DESC
    ");
    $stmt->execute();
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($posts as $post) {
        $lastmod = $post['updated_at'] ?: $post['published_at'];
        echo "<url>\n";
        echo "  <loc>{$base_url}/post.php?slug=" . urlencode($post['slug']) . "</loc>\n";
        echo "  <lastmod>" . date('c', strtotime($lastmod)) . "</lastmod>\n";
        echo "  <changefreq>weekly</changefreq>\n";
        echo "  <priority>0.8</priority>\n";
        echo "</url>\n";
    }
    
    // Categories
    $stmt = $pdo->prepare("
        SELECT slug, updated_at 
        FROM blog_categories 
        WHERE status = 'active'
    ");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($categories as $category) {
        echo "<url>\n";
        echo "  <loc>{$base_url}/?category=" . urlencode($category['slug']) . "</loc>\n";
        echo "  <lastmod>" . date('c', strtotime($category['updated_at'])) . "</lastmod>\n";
        echo "  <changefreq>weekly</changefreq>\n";
        echo "  <priority>0.6</priority>\n";
        echo "</url>\n";
    }
    
    // Search page
    echo "<url>\n";
    echo "  <loc>{$base_url}/search.php</loc>\n";
    echo "  <lastmod>" . date('c') . "</lastmod>\n";
    echo "  <changefreq>monthly</changefreq>\n";
    echo "  <priority>0.5</priority>\n";
    echo "</url>\n";
    
} catch (Exception $e) {
    error_log("Sitemap generation error: " . $e->getMessage());
}
?>

</urlset>
