<?php
/**
 * Dynamic Sitemap Generator
 * Ihyaul Islam Charity Organization
 */
require_once __DIR__ . '/config/app.php';

header('Content-Type: application/xml; charset=utf-8');

$pages = [
    ['loc' => BASE_URL, 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => BASE_URL . 'about.php', 'priority' => '0.9', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'team.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'impact.php', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => BASE_URL . 'programs.php', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['loc' => BASE_URL . 'donate.php', 'priority' => '1.0', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'volunteer.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'partner.php', 'priority' => '0.6', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'news.php', 'priority' => '0.8', 'changefreq' => 'daily'],
    ['loc' => BASE_URL . 'gallery.php', 'priority' => '0.6', 'changefreq' => 'weekly'],
    ['loc' => BASE_URL . 'publications.php', 'priority' => '0.5', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'financials.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'policies.php', 'priority' => '0.6', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'impact-dashboard.php', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => BASE_URL . 'contact.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'faq.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'privacy-policy.php', 'priority' => '0.3', 'changefreq' => 'yearly'],
    ['loc' => BASE_URL . 'terms-of-service.php', 'priority' => '0.3', 'changefreq' => 'yearly'],
];

// Add dynamic programs
try {
    $pdo = getConnection();
    $programs = $pdo->query("SELECT slug, updated_at FROM programs WHERE status='active'")->fetchAll();
    foreach ($programs as $p) {
        $pages[] = ['loc' => BASE_URL . 'program.php?slug=' . $p['slug'], 'priority' => '0.8', 'changefreq' => 'weekly'];
    }
    
    $posts = $pdo->query("SELECT slug, published_at FROM blog_posts WHERE status='published'")->fetchAll();
    foreach ($posts as $post) {
        $pages[] = ['loc' => BASE_URL . 'news-detail.php?slug=' . $post['slug'], 'priority' => '0.7', 'changefreq' => 'monthly'];
    }
} catch (Exception $e) {
    // Ignore DB errors
}

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($pages as $p): ?>
    <url>
        <loc><?= escape($p['loc']) ?></loc>
        <priority><?= $p['priority'] ?></priority>
        <changefreq><?= $p['changefreq'] ?></changefreq>
    </url>
<?php endforeach; ?>
</urlset>
