<?php
/**
 * MEUSEGREDO.SHOP
 * Sitemap XML Dinâmico (Sitemap.xml)
 */

define('SECURE_ACCESS', true);
require_once __DIR__ . '/config.php';

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

// Imprime a tag de declaração inicial do XML
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!-- URL Inicial da Homepage -->
    <url>
        <loc><?= APP_URL ?>/</loc>
        <changefreq>always</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc><?= APP_URL ?>/recentes</loc>
        <changefreq>always</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc><?= APP_URL ?>/trending</loc>
        <changefreq>always</changefreq>
        <priority>0.8</priority>
    </url>

    <!-- URLs Dinâmicas de Segredos Ativos do Banco SQLite -->
    <?php
    if (file_exists(DATABASE_PATH)) {
        try {
            $db = new PDO("sqlite:" . DATABASE_PATH);
            $stmt = $db->query("SELECT slug, created_at FROM posts WHERE status = 1 ORDER BY created_at DESC");
            while ($post = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $lastmod = date('Y-m-d', strtotime($post['created_at']));
                ?>
                <url>
                    <loc><?= APP_URL ?>/segredo/<?= htmlspecialchars($post['slug']) ?></loc>
                    <lastmod><?= $lastmod ?></lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.7</priority>
                </url>
                <?php
            }
        } catch (Exception $e) {
            // Silencioso
        }
    }
    ?>
</urlset>
