<?php
require_once __DIR__ . '/../waitlist/includes/bootstrap.php';

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

$baseUrl = 'https://www.logifera.com';
$pages = [
    ['/', 'weekly', '1.0'],
    ['/about', 'monthly', '0.7'],
    ['/science', 'monthly', '0.8'],
    ['/screener/dyslexia/home', 'monthly', '0.9'],
    ['/screener/dyscalculia/home', 'monthly', '0.9'],
    ['/community/home', 'weekly', '0.8'],
    ['/help', 'monthly', '0.6'],
    ['/resources/faq', 'monthly', '0.6']
];

function sitemapEscape(string $value): string {
    return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

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

foreach ($pages as [$path, $frequency, $priority]) {
    echo "  <url>\n";
    echo '    <loc>' . sitemapEscape($baseUrl . $path) . "</loc>\n";
    echo '    <changefreq>' . $frequency . "</changefreq>\n";
    echo '    <priority>' . $priority . "</priority>\n";
    echo "  </url>\n";
}

try {
    $communityDb = getDBConnection('community');
    if ($communityDb) {
        $articles = $communityDb->query("SELECT slug, published_at FROM blog_posts WHERE status = 'published' ORDER BY published_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($articles as $article) {
            echo "  <url>\n";
            echo '    <loc>' . sitemapEscape($baseUrl . '/community/article?slug=' . rawurlencode($article['slug'])) . "</loc>\n";
            echo '    <lastmod>' . date('Y-m-d', strtotime($article['published_at'])) . "</lastmod>\n";
            echo "    <changefreq>monthly</changefreq>\n";
            echo "    <priority>0.7</priority>\n";
            echo "  </url>\n";
        }
    }
} catch (Throwable $e) {
    error_log('Sitemap community query failed: ' . $e->getMessage());
}

echo "</urlset>\n";