<?xml version="1.0" encoding="UTF-8"?>
<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
header('Content-Type: application/xml; charset=utf-8');
$base = rtrim(APP_URL, '/');
$hoje = date('Y-m-d');
$pages = [
    ['/',               '1.0', 'daily',   $hoje],
    ['/blog',           '0.9', 'daily',   $hoje],
    ['/como-funciona',  '0.8', 'monthly', $hoje],
    ['/sobre',          '0.7', 'monthly', $hoje],
    ['/cadastro',       '0.9', 'weekly',  $hoje],
    ['/contato',        '0.6', 'monthly', $hoje],
    ['/termos',         '0.4', 'yearly',  $hoje],
    ['/privacidade',    '0.4', 'yearly',  $hoje],
];

// Fetch published blog posts
try {
    $blog_posts = Database::fetchAll(
        "SELECT slug, atualizado_em FROM blog_posts WHERE status='publicado' ORDER BY publicado_em DESC LIMIT 500"
    );
} catch (\Throwable $e) { $blog_posts = []; }
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($pages as [$url, $priority, $freq, $lastmod]): ?>
  <url>
    <loc><?= $base . $url ?></loc>
    <lastmod><?= $lastmod ?></lastmod>
    <changefreq><?= $freq ?></changefreq>
    <priority><?= $priority ?></priority>
  </url>
<?php endforeach; ?>
<?php foreach ($blog_posts as $bp): ?>
  <url>
    <loc><?= $base ?>/blog/<?= htmlspecialchars($bp['slug']) ?></loc>
    <lastmod><?= $bp['atualizado_em'] ? date('Y-m-d', strtotime($bp['atualizado_em'])) : $hoje ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
  </url>
<?php endforeach; ?>
</urlset>
