<?php
/**
 * Dynamic XML sitemap for the EduTrack blog.
 * Submit to Google: https://search.google.com/search-console
 * Submit URL: https://edutrack.oricnetwork.com/blog/sitemap.php
 */

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

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

$conn  = blog_db();
$posts = $conn->query(
    'SELECT slug, updated_at, published_at FROM blog_posts
     WHERE status = "published" ORDER BY published_at DESC'
);

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

// Blog index
echo '  <url>' . "\n";
echo '    <loc>' . BLOG_BASE_URL . '/index.php</loc>' . "\n";
echo '    <changefreq>daily</changefreq>' . "\n";
echo '    <priority>0.8</priority>' . "\n";
echo '  </url>' . "\n";

if ($posts) {
    while ($row = $posts->fetch_assoc()) {
        $lastmod = $row['updated_at'] ?: $row['published_at'];
        $lastmod_iso = $lastmod ? date('Y-m-d', strtotime($lastmod)) : date('Y-m-d');
        echo '  <url>' . "\n";
        echo '    <loc>' . BLOG_BASE_URL . '/post.php?slug=' . urlencode($row['slug']) . '</loc>' . "\n";
        echo '    <lastmod>' . $lastmod_iso . '</lastmod>' . "\n";
        echo '    <changefreq>monthly</changefreq>' . "\n";
        echo '    <priority>0.7</priority>' . "\n";
        echo '  </url>' . "\n";
    }
}

echo '</urlset>';
