<?php
/**
 * /xschools/sitemap.php — XML sitemap for the bookstore (audit §5).
 *
 * DEPLOYMENT NOTE: Google expects the sitemap at the domain root,
 * e.g. https://xschools.in/sitemap.xml. Either copy this file there or
 * add a rewrite: RewriteRule ^sitemap\.xml$ /xschools/sitemap.php [L]
 */
declare(strict_types=1);

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

$urls = [
    [
        'loc'        => 'https://xschools.in/xschools/bookstore/',
        'changefreq' => 'weekly',
        'priority'   => '1.0',
    ],
];

try {
    require_once __DIR__ . '/config/db.php';
    $pdo  = get_db();
    $stmt = $pdo->query(
        'SELECT id, title, published_at FROM prerana_books
         WHERE published = 1 ORDER BY sort_order ASC, published_at DESC'
    );
    foreach ($stmt->fetchAll() as $b) {
        // Books currently open in JavaScript modals; when individual public
        // book pages exist (audit §6), list them here instead of the shelf.
        $urls[] = [
            'loc'        => 'https://xschools.in/xschools/bookstore/#book-' . (int)$b['id'],
            'changefreq' => 'monthly',
            'priority'   => '0.8',
        ];
    }
} catch (Exception $e) {
    // Serve the static URLs even if the DB is unreachable
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($urls as $u): ?>
  <url>
    <loc><?php echo htmlspecialchars($u['loc'], ENT_XML1); ?></loc>
    <changefreq><?php echo $u['changefreq']; ?></changefreq>
    <priority><?php echo $u['priority']; ?></priority>
  </url>
<?php endforeach; ?>
</urlset>
