<?php
require_once __DIR__ . '/includes/config.php';
header('Content-Type: application/xml; charset=utf-8');

$base = rtrim(SITE_URL, '/') . '/';

// Static pages with priorities
$staticPages = [
    ['loc' => $base,                        'priority' => '1.0', 'changefreq' => 'weekly'],
    ['loc' => $base . 'products.php',       'priority' => '0.9', 'changefreq' => 'weekly'],
    ['loc' => $base . 'franchising.php',    'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => $base . 'blog.php',           'priority' => '0.7', 'changefreq' => 'weekly'],
    ['loc' => $base . 'careers.php',        'priority' => '0.6', 'changefreq' => 'weekly'],
    ['loc' => $base . 'contact.php',        'priority' => '0.6', 'changefreq' => 'monthly'],
];

// Dynamic blog posts
$posts = $pdo->query("SELECT slug, published_at, created_at FROM blog_posts WHERE status='published' ORDER BY published_at DESC")->fetchAll();

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

foreach ($staticPages as $p) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($p['loc']) . "</loc>\n";
    echo "    <changefreq>{$p['changefreq']}</changefreq>\n";
    echo "    <priority>{$p['priority']}</priority>\n";
    echo "  </url>\n";
}

foreach ($posts as $post) {
    $date = $post['published_at'] ?: $post['created_at'];
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($base . 'blog-post.php?slug=' . urlencode($post['slug'])) . "</loc>\n";
    echo "    <lastmod>" . date('Y-m-d', strtotime($date)) . "</lastmod>\n";
    echo "    <changefreq>monthly</changefreq>\n";
    echo "    <priority>0.5</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>';
