<?php
header("Content-Type: application/xml; charset=utf-8");
require_once __DIR__ . '/../adm/config/db.php';

$baseUrl = "https://" . $_SERVER['HTTP_HOST'];
if (strpos($_SERVER['REQUEST_URI'], '/nova/') !== false) {
    $baseUrl .= "/nova";
}

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

// Home page
echo '<url>';
echo '<loc>' . htmlspecialchars($baseUrl . '/index.php') . '</loc>';
echo '<changefreq>daily</changefreq>';
echo '<priority>1.0</priority>';
echo '</url>';

// Categories
$sql_cat = "SELECT id FROM categorias WHERE status = 'Ativo' OR status IS NULL";
$res_cat = $conn->query($sql_cat);
if ($res_cat && $res_cat->num_rows > 0) {
    while ($cat = $res_cat->fetch_assoc()) {
        echo '<url>';
        echo '<loc>' . htmlspecialchars($baseUrl . '/departamento.php?categoria_id=' . $cat['id']) . '</loc>';
        echo '<changefreq>weekly</changefreq>';
        echo '<priority>0.8</priority>';
        echo '</url>';
    }
}

// Products
$sql_prod = "SELECT nome FROM produtos WHERE status = 'Ativo'";
$res_prod = $conn->query($sql_prod);
if ($res_prod && $res_prod->num_rows > 0) {
    while ($prod = $res_prod->fetch_assoc()) {
        echo '<url>';
        echo '<loc>' . htmlspecialchars($baseUrl . '/produto.php?nome=' . urlencode($prod['nome'])) . '</loc>';
        echo '<changefreq>weekly</changefreq>';
        echo '<priority>0.9</priority>';
        echo '</url>';
    }
}

echo '</urlset>';
?>
