<?php
// This file generates a sitemap dynamically
// Save as sitemap.php but when accessed, output as XML

header('Content-Type: application/xml; charset=utf-8');

require_once 'config.php';

$base_url = SITE_URL;
$urls = array();

// Add main pages
$urls[] = array(
    'loc' => $base_url . '/',
    'lastmod' => date('Y-m-d'),
    'changefreq' => 'weekly',
    'priority' => 1.0
);

$urls[] = array(
    'loc' => $base_url . '/blog/',
    'lastmod' => date('Y-m-d'),
    'changefreq' => 'daily',
    'priority' => 0.8
);

// Add blog posts
$posts = $conn->query("SELECT id, created_at, updated_at FROM blog_posts WHERE status = 'published'");
while ($post = $posts->fetch_assoc()) {
    $urls[] = array(
        'loc' => $base_url . '/blog/post.php?id=' . $post['id'],
        'lastmod' => $post['updated_at'] ?? $post['created_at'],
        'changefreq' => 'monthly',
        'priority' => 0.7
    );
}

// Generate XML
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

foreach ($urls as $url) {
    echo '  <url>' . "\n";
    echo '    <loc>' . htmlspecialchars($url['loc']) . '</loc>' . "\n";
    echo '    <lastmod>' . htmlspecialchars($url['lastmod']) . '</lastmod>' . "\n";
    echo '    <changefreq>' . htmlspecialchars($url['changefreq']) . '</changefreq>' . "\n";
    echo '    <priority>' . htmlspecialchars($url['priority']) . '</priority>' . "\n";
    echo '  </url>' . "\n";
}

echo '</urlset>';
?>