
<?php
header('Content-Type: application/xml; charset=UTF-8');

$site_url = 'https://thepalaceonwheelss.org';
$blogs_file = __DIR__ . '/data/blogs.json';

$urls = [
    [
        'loc' => $site_url . '/',
        'priority' => '1.0'
    ],
    [
        'loc' => $site_url . '/blogs.php',
        'priority' => '0.8'
    ]
];

if (file_exists($blogs_file)) {
    $blogs = json_decode(file_get_contents($blogs_file), true);

    if (is_array($blogs)) {
        foreach ($blogs as $blog) {
            if (($blog['published'] ?? true) !== true) {
                continue;
            }

            if (empty($blog['slug'])) {
                continue;
            }

            $slug = trim((string) $blog['slug']);

            if ($slug === '' || strpos($slug, '/') !== false) {
                continue;
            }

            $lastmod = date('Y-m-d');

            if (!empty($blog['date'])) {
                $timestamp = strtotime($blog['date']);
                if ($timestamp !== false) {
                    $lastmod = date('Y-m-d', $timestamp);
                }
            }

            $urls[] = [
                'loc' => $site_url . '/blog.php?slug=' . rawurlencode($slug),
                'lastmod' => $lastmod,
                'priority' => '0.7'
            ];
        }
    }
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

foreach ($urls as $url) {
    echo "  <url>\n";
    echo '    <loc>' . htmlspecialchars($url['loc'], ENT_XML1, 'UTF-8') . "</loc>\n";
    echo '    <lastmod>' . $url['lastmod'] . "</lastmod>\n";
    echo '    <priority>' . $url['priority'] . "</priority>\n";
    echo "  </url>\n";
}

echo "</urlset>";
