<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/functions.php';

header('Content-Type: application/xml; charset=UTF-8');

$baseUrl = 'https://singhhabitat.com';

function xmlEscape(string $value): string
{
    return htmlspecialchars(
        $value,
        ENT_XML1 | ENT_QUOTES,
        'UTF-8'
    );
}

$pages = [
    ['url' => '/', 'changefreq' => 'weekly', 'priority' => '1.0'],
    ['url' => '/gst-calculator.html', 'changefreq' => 'monthly', 'priority' => '0.8'],
    ['url' => '/age-calculator.html', 'changefreq' => 'monthly', 'priority' => '0.8'],
    ['url' => '/bmi-calculator.html', 'changefreq' => 'monthly', 'priority' => '0.8'],
    ['url' => '/percentage-calculator.html', 'changefreq' => 'monthly', 'priority' => '0.8'],
    ['url' => '/about.html', 'changefreq' => 'yearly', 'priority' => '0.4'],
    ['url' => '/contact.html', 'changefreq' => 'yearly', 'priority' => '0.4'],
    ['url' => '/privacy-policy.html', 'changefreq' => 'yearly', 'priority' => '0.3'],
    ['url' => '/terms.html', 'changefreq' => 'yearly', 'priority' => '0.3'],
    ['url' => '/disclaimer.html', 'changefreq' => 'yearly', 'priority' => '0.3'],
];

$articles = [];

try {
    $stmt = $pdo->query(
        "SELECT slug, updated_at
         FROM articles
         WHERE status = 'published'
         ORDER BY published_at DESC, id DESC"
    );

    $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log('Sitemap article query failed: ' . $e->getMessage());
    http_response_code(500);
    exit('Sitemap temporarily unavailable.');
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($pages as $page): ?>
    <url>
        <loc><?= xmlEscape($baseUrl . $page['url']) ?></loc>
        <changefreq><?= xmlEscape($page['changefreq']) ?></changefreq>
        <priority><?= xmlEscape($page['priority']) ?></priority>
    </url>
<?php endforeach; ?>

<?php foreach ($articles as $article): ?>
    <url>
        <loc><?= xmlEscape(
            $baseUrl . '/article.php?slug=' . rawurlencode((string) $article['slug'])
        ) ?></loc>
        <?php if (!empty($article['updated_at'])): ?>
        <lastmod><?= date('Y-m-d', strtotime((string) $article['updated_at'])) ?></lastmod>
        <?php endif; ?>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
    </url>
<?php endforeach; ?>
</urlset>