<?php
// KOTACAKE - Auto-generated XML Sitemap
// Dynamically generates sitemap from blogs and pages tables
require_once 'config.php';

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

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

// Static pages
$static_pages = [
    '' => '1.0',
    'music.php' => '0.9',
    'gallery.php' => '0.8',
    'blog.php' => '0.9',
    'about.php' => '0.7',
    'contact.php' => '0.6',
    'privacy-policy.php' => '0.5',
    'terms.php' => '0.5',
    'disclaimer.php' => '0.5',
];

foreach ($static_pages as $file => $priority) {
    echo '<url>' . "\n";
    echo '<loc>' . SITE_URL . $file . '</loc>' . "\n";
    echo '<changefreq>monthly</changefreq>' . "\n";
    echo '<priority>' . $priority . '</priority>' . "\n";
    echo '</url>' . "\n";
}

// Blog posts
$blog_q = mysqli_query($conn, "SELECT slug, created_at FROM blogs WHERE status = 'published' ORDER BY created_at DESC");
while ($post = mysqli_fetch_assoc($blog_q)) {
    echo '<url>' . "\n";
    echo '<loc>' . SITE_URL . 'blog-detail.php?slug=' . urlencode($post['slug']) . '</loc>' . "\n";
    echo '<lastmod>' . date('Y-m-d', strtotime($post['created_at'])) . '</lastmod>' . "\n";
    echo '<changefreq>monthly</changefreq>' . "\n";
    echo '<priority>0.7</priority>' . "\n";
    echo '</url>' . "\n";
}

// CMS pages
$pages_q = mysqli_query($conn, "SELECT slug FROM pages WHERE status = 'active'");
while ($row = mysqli_fetch_assoc($pages_q)) {
    $page_file = '';
    switch ($row['slug']) {
        case 'privacy-policy': $page_file = 'privacy-policy.php'; break;
        case 'terms': $page_file = 'terms.php'; break;
        case 'disclaimer': $page_file = 'disclaimer.php'; break;
        default: $page_file = $row['slug'] . '.php';
    }
    echo '<url>' . "\n";
    echo '<loc>' . SITE_URL . $page_file . '</loc>' . "\n";
    echo '<changefreq>yearly</changefreq>' . "\n";
    echo '<priority>0.5</priority>' . "\n";
    echo '</url>' . "\n";
}

echo '</urlset>' . "\n";
?>
