<?php
// sitemap.xml - Dynamic XML Sitemap
header('Content-Type: application/xml; charset=utf-8');

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

$db = Database::getInstance();
$baseUrl = rtrim(baseUrl(), '/');

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

// Static pages
$staticPages = ['', 'about', 'contact', 'umrah-packages', 'hajj-packages', 'visit-visa', 'student-visa', 'work-permit', 'immigration', 'hajj-pre-registration', 'blog', 'saudi-investment-license'];
foreach ($staticPages as $page) {
    $loc = $baseUrl . '/' . $page;
    $changefreq = $page === '' ? 'daily' : 'weekly';
    $priority = $page === '' ? '1.0' : '0.8';
    echo "<url><loc>{$loc}</loc><changefreq>{$changefreq}</changefreq><priority>{$priority}</priority></url>";
}

// Umrah Packages
try {
    $packages = $db->fetchAll("SELECT slug, updated_at FROM umrah_packages WHERE status = 'active'");
    foreach ($packages as $p) {
        echo "<url><loc>{$baseUrl}/umrah-packages/{$p['slug']}</loc><changefreq>weekly</changefreq><priority>0.8</priority><lastmod>{$p['updated_at']}</lastmod></url>";
    }
} catch (Exception $e) {}

// Hajj Packages
try {
    $packages = $db->fetchAll("SELECT slug, updated_at FROM hajj_packages WHERE status = 'active'");
    foreach ($packages as $p) {
        echo "<url><loc>{$baseUrl}/hajj-packages/{$p['slug']}</loc><changefreq>weekly</changefreq><priority>0.8</priority><lastmod>{$p['updated_at']}</lastmod></url>";
    }
} catch (Exception $e) {}

// Countries/Visa
try {
    $countries = $db->fetchAll("SELECT slug, updated_at FROM countries WHERE status = 'active'");
    foreach ($countries as $c) {
        echo "<url><loc>{$baseUrl}/visit-visa/{$c['slug']}</loc><changefreq>monthly</changefreq><priority>0.7</priority><lastmod>{$c['updated_at']}</lastmod></url>";
    }
} catch (Exception $e) {}

// Blog Posts
try {
    $posts = $db->fetchAll("SELECT slug, updated_at FROM blog_posts WHERE status = 'published'");
    foreach ($posts as $p) {
        echo "<url><loc>{$baseUrl}/blog/{$p['slug']}</loc><changefreq>weekly</changefreq><priority>0.7</priority><lastmod>{$p['updated_at']}</lastmod></url>";
    }
} catch (Exception $e) {}

echo '</urlset>';
