<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';

header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: public, max-age=3600');

$siteUrl = rtrim(config('site_url', 'https://seudominio.com.br'), '/');

$produtos   = DB::fetchAll('SELECT slug, criado_em FROM produtos WHERE ativo = 1 ORDER BY criado_em DESC');
$categorias = DB::fetchAll('SELECT slug FROM categorias WHERE ativo = 1');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// Página inicial
echo "<url><loc>{$siteUrl}/</loc><changefreq>daily</changefreq><priority>1.0</priority></url>\n";
echo "<url><loc>{$siteUrl}/busca.php</loc><changefreq>weekly</changefreq><priority>0.5</priority></url>\n";

foreach ($categorias as $c) {
    $url = $siteUrl . '/categoria/' . htmlspecialchars($c['slug'], ENT_XML1, 'UTF-8');
    echo "<url><loc>{$url}</loc><changefreq>daily</changefreq><priority>0.7</priority></url>\n";
}

foreach ($produtos as $p) {
    $url     = $siteUrl . '/produto/' . htmlspecialchars($p['slug'], ENT_XML1, 'UTF-8');
    $lastmod = substr($p['criado_em'], 0, 10);
    echo "<url><loc>{$url}</loc><lastmod>{$lastmod}</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url>\n";
}

echo '</urlset>';
