<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/seo.php';

header('Content-Type: application/xml; charset=UTF-8');
header('X-Robots-Tag: noindex');

$base = SITE_URL;
$hoy  = date('Y-m-d');

$urls = [
    ['loc'=>$base.'/',             'lastmod'=>$hoy, 'changefreq'=>'weekly',  'priority'=>'1.0'],
    ['loc'=>$base.'/catalogo.php', 'lastmod'=>$hoy, 'changefreq'=>'weekly',  'priority'=>'0.9'],
];

$productos = [];
$cats      = [];

try {
    $cats = db()->query("SELECT id, nombre FROM categorias WHERE activa=1 ORDER BY orden ASC")->fetchAll();
    foreach ($cats as $c) {
        $urls[] = [
            'loc'        => $base.'/catalogo.php?categoria='.$c['id'],
            'lastmod'    => $hoy,
            'changefreq' => 'weekly',
            'priority'   => '0.85',
            'title'      => htmlspecialchars($c['nombre']),
        ];
    }
    $productos = db()->query(
        "SELECT id, nombre, imagen_principal, categoria_id, created_at
         FROM productos WHERE activo=1 ORDER BY destacado DESC, id ASC"
    )->fetchAll();
    foreach ($productos as $p) {
        $urls[] = [
            'loc'        => $base.'/catalogo.php?categoria='.$p['categoria_id'].'#prod-'.$p['id'],
            'lastmod'    => $hoy,
            'changefreq' => 'monthly',
            'priority'   => '0.75',
            'image'      => !empty($p['imagen_principal']) ? $base.'/'.$p['imagen_principal'] : null,
            'image_title'=> htmlspecialchars($p['nombre']),
        ];
    }
} catch (Exception $e) {}

// Anclas estáticas de index
foreach (['#categorias','#nosotros','#contacto'] as $anchor) {
    $urls[] = ['loc'=>$base.'/'.$anchor, 'lastmod'=>$hoy, 'changefreq'=>'monthly', 'priority'=>'0.5'];
}

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

foreach ($urls as $u) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($u['loc']) . "</loc>\n";
    echo "    <lastmod>{$u['lastmod']}</lastmod>\n";
    echo "    <changefreq>{$u['changefreq']}</changefreq>\n";
    echo "    <priority>{$u['priority']}</priority>\n";
    if (!empty($u['image'])) {
        echo "    <image:image>\n";
        echo "      <image:loc>" . htmlspecialchars($u['image']) . "</image:loc>\n";
        if (!empty($u['image_title'])) {
            echo "      <image:title>" . $u['image_title'] . "</image:title>\n";
            echo "      <image:caption>INTEREXPORT — " . $u['image_title'] . "</image:caption>\n";
        }
        echo "    </image:image>\n";
    }
    echo "  </url>\n";
}
echo '</urlset>';
