<?php
require_once 'includes/db.php';

header('Content-Type: application/xml');

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

// Static pages
$pages = [
    '' => 'daily',
    'about' => 'weekly',
    'franchise' => 'weekly',
    'dealership' => 'weekly',
    'distributorship' => 'weekly',
    'products' => 'weekly',
    'apply' => 'monthly',
    'blog' => 'daily',
    'contact' => 'monthly'
];

foreach ($pages as $page => $frequency) {
    $url = SITE_URL . '/' . $page;
    echo '<url>';
    echo '<loc>' . htmlspecialchars($url) . '</loc>';
    echo '<changefreq>' . $frequency . '</changefreq>';
    echo '<priority>0.8</priority>';
    echo '</url>';
}

// Dynamic blog posts
$stmt = $conn->query("SELECT slug, updated_at FROM blogs WHERE status = 'published'");
$blogs = $stmt->fetchAll();

foreach ($blogs as $blog) {
    $url = SITE_URL . '/blog/' . $blog['slug'];
    $lastmod = date('Y-m-d', strtotime($blog['updated_at']));
    echo '<url>';
    echo '<loc>' . htmlspecialchars($url) . '</loc>';
    echo '<lastmod>' . $lastmod . '</lastmod>';
    echo '<changefreq>weekly</changefreq>';
    echo '<priority>0.6</priority>';
    echo '</url>';
}

echo '</urlset>';
