<?php
// public/sitemap.php - Generador de Sitemap XML
// Ejecutar: https://americanharus.com.pe/sitemap.php

header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">

    <!-- Página principal -->
    <url>
        <loc><?php echo BASE_URL; ?>/</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- Catálogo -->
    <url>
        <loc><?php echo BASE_URL; ?>/catalogo</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>

    <!-- Páginas estáticas -->
    <url>
        <loc><?php echo BASE_URL; ?>/nosotros</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>

    <url>
        <loc><?php echo BASE_URL; ?>/contacto</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>

    <?php
    // Productos desde la base de datos
    try {
        $db = new PDO('mysql:host=localhost;dbname=ldaemopi_26_amhacat_bd;charset=utf8', 'ldaemopi_us26amha_ms', '*/AmHa2026msoft');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $db->query("SELECT id, codigo_sistema, updated_at, imagen FROM productos WHERE activo = 1 ORDER BY id DESC LIMIT 1000");
        $productos = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($productos as $p) {
            $fecha = $p['updated_at'] ?? date('Y-m-d H:i:s');
            ?>
    <url>
        <loc><?php echo BASE_URL; ?>/producto/<?php echo $p['id']; ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($fecha)); ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
        <?php if (!empty($p['imagen'])): ?>
        <image:image>
            <image:loc><?php echo BASE_URL; ?>/uploads/<?php echo $p['imagen']; ?></image:loc>
            <image:title>Repuesto <?php echo htmlspecialchars($p['codigo_sistema'] ?? ''); ?></image:title>
        </image:image>
        <?php endif; ?>
    </url>
    <?php
        }
    } catch (Exception $e) {
        // Si hay error, no mostrar nada
    }
    ?>
</urlset>