<?php
/**
 * Dynamic Blog Sitemap Generator
 *
 * Generates sitemap for all published blog posts
 */

// Autoloader
spl_autoload_register(function ($class) {
    $class = str_replace('App\\', '', $class);
    $class = str_replace('\\', '/', $class);
    $file = __DIR__ . '/../app/' . $class . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

require_once __DIR__ . '/../app/Core/env_loader.php';
loadEnv(__DIR__ . '/../.env');

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

$db = \App\Core\Database::getInstance();
$baseUrl = 'https://accessibilityscanner.top';

// Get all published blog posts
$posts = $db->fetchAll("
    SELECT slug, updated_at, created_at
    FROM blog_posts
    WHERE is_published = 1
    ORDER BY created_at DESC
");

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($posts as $post):
    $lastmod = $post['updated_at'] ?? $post['created_at'];
    $lastmodFormatted = date('Y-m-d', strtotime($lastmod));
?>
    <url>
        <loc><?= $baseUrl ?>/blog/<?= htmlspecialchars($post['slug']) ?></loc>
        <lastmod><?= $lastmodFormatted ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
    </url>
<?php endforeach; ?>
</urlset>
