<?php
// Define o cabeçalho como XML
header("Content-Type: application/xml; charset=utf-8");

echo '<?xml version="1.0" encoding="UTF-8"?>';

// Inclui a conexão com o banco de dados (ajuste o caminho se necessário)
require_once __DIR__ . '/blog/conn_prestadorcerto_db.php'; 
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    
    <!-- Página Inicial -->
    <url>
        <loc>https://prestadorcerto.com.br/</loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- Página Principal do Blog -->
    <url>
        <loc>https://prestadorcerto.com.br/blog</loc>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>

    <!-- Categorias Fixas -->
    <url>
        <loc>https://prestadorcerto.com.br/blog/eletricista</loc>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>https://prestadorcerto.com.br/blog/pintor</loc>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>

    <!-- Artigos Dinâmicos com INNER JOIN -->
    <?php
    try {
        // Faz o JOIN entre posts e categorias para pegar o slug de ambos
        $sql = "SELECT c.slug AS categoria, p.slug AS slug, p.criado_em 
                FROM artigos p 
                INNER JOIN categorias c ON p.categoria_id = c.id";
        
        $stmt = $pdo->query($sql);
        while ($post = $stmt->fetch(PDO::FETCH_ASSOC)):
    ?>
        <url>
            <loc>https://prestadorcerto.com.br/blog/<?php echo htmlspecialchars($post['slug_categoria']); ?>/<?php echo htmlspecialchars($post['slug']); ?></loc>
            <lastmod><?php echo date('Y-m-d', strtotime($post['criado_em'])); ?></lastmod>
            <changefreq>monthly</changefreq>
            <priority>0.7</priority>
        </url>
    <?php 
        endwhile;
    } catch (Throwable $e) {
        // Se houver algum erro, mostra no código-fonte em formato de comentário para facilitar o ajuste
        echo "<!-- ERRO SQL: " . $e->getMessage() . " -->";
    }
    ?>

</urlset>