<?php
// pages/stock_calculado.php - Versión actualizada con mejoras solicitadas

session_start();
require_once '/home/crusardi/config_crusardi/database.php';

// Configurar charset UTF-8
if ($pdo) {
    $pdo->exec("SET NAMES 'utf8mb4'");
    $pdo->exec("SET CHARACTER SET utf8mb4");
    $pdo->exec("SET COLLATION_CONNECTION = 'utf8mb4_unicode_ci'");
}

date_default_timezone_set('America/Bogota');

// --- FUNCIÓN DE CONSOLIDACIÓN ---
function consolidar_stock($pdo) {
    try {
        $stmt = $pdo->prepare("CALL consolidar_stock_crusardi()");
        $stmt->execute();
        
        // Obtener resultados si los hay
        $resultados = [];
        do {
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if ($rows) {
                $resultados = array_merge($resultados, $rows);
            }
        } while ($stmt->nextRowset());
        
        $stmt->closeCursor();
        
        // Obtener estadísticas actualizadas
        $stats = $pdo->query("
            SELECT 
                COUNT(DISTINCT codigo) as total_productos,
                SUM(stock_total) as total_unidades,
                MAX(ultima_actualizacion) as ultima_actualizacion
            FROM stock_calculado_cache 
            WHERE stock_total > 0
        ")->fetch(PDO::FETCH_ASSOC);
        
        return [
            'success' => true,
            'message' => 'Stock consolidado exitosamente',
            'stats' => $stats,
            'resultados' => $resultados
        ];
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Error al consolidar: ' . $e->getMessage()
        ];
    }
}

// --- PROCESAR ACCIÓN DE CONSOLIDACIÓN ---
if (isset($_POST['action']) && $_POST['action'] === 'consolidar') {
    $resultado = consolidar_stock($pdo);
    if ($resultado['success']) {
        $_SESSION['upload_success'] = $resultado['message'] . ' - ' . 
            number_format($resultado['stats']['total_productos']) . ' productos procesados';
    } else {
        $_SESSION['upload_error'] = $resultado['message'];
    }
    header('Location: index.php?page=stock_calculado');
    exit;
}

// --- INICIALIZACIÓN DE VARIABLES ---
$db_error = null;
$paginated_items = [];
$total_items = 0;
$total_pages = 1;
$current_page_num = 1;
$stats = [];

$upload_success_message = $_SESSION['upload_success'] ?? null;
unset($_SESSION['upload_success']);
$upload_error_message = $_SESSION['upload_error'] ?? null;
unset($_SESSION['upload_error']);

// --- RECUPERAR VALORES DE FILTROS ---
$search_get = $_GET['search'] ?? '';
$tipo_get = $_GET['tipo'] ?? '';
$bodega_get = $_GET['bodega'] ?? '';
$categoria1_get = $_GET['categoria1'] ?? '';
$categoria2_get = $_GET['categoria2'] ?? '';
$estado_get = $_GET['estado'] ?? '';
$orden_get = $_GET['orden'] ?? 'nombre_asc';
$page_num = isset($_GET['page_num']) ? max(1, intval($_GET['page_num'])) : 1;

try {
    // --- OBTENER ESTADÍSTICAS GENERALES ---
    $stats_query = "
        SELECT 
            SUM(stock_total) as total_unidades,
            SUM(CASE WHEN tipo = 'kit' THEN 1 ELSE 0 END) as total_kits,
            SUM(CASE WHEN tipo = 'articulo' THEN 1 ELSE 0 END) as total_articulos,
            SUM(CASE WHEN tipo = 'imperfecto' THEN 1 ELSE 0 END) as total_imperfectos,
            SUM(CASE WHEN tipo = 'parte' THEN 1 ELSE 0 END) as total_partes,
            MAX(ultima_actualizacion) as ultima_actualizacion
        FROM stock_calculado_cache 
        WHERE stock_total > 0
    ";
    $stats = $pdo->query($stats_query)->fetch(PDO::FETCH_ASSOC);
    
    // --- CONSTRUIR CONSULTA CON FILTROS ---
    $where_conditions = ["stock_total > 0"];
    $params = [];
    
    // Búsqueda
    if (!empty($search_get)) {
        $where_conditions[] = "(codigo LIKE :search OR nombre LIKE :search2 OR codigo_unico LIKE :search3)";
        $params[':search'] = "%$search_get%";
        $params[':search2'] = "%$search_get%";
        $params[':search3'] = "%$search_get%";
    }
    
    // Tipo de producto
    if (!empty($tipo_get)) {
        $where_conditions[] = "tipo = :tipo";
        $params[':tipo'] = $tipo_get;
    }
    
    // Bodega
    if (!empty($bodega_get)) {
        $where_conditions[] = "bodega = :bodega";
        $params[':bodega'] = $bodega_get;
    }
    
    // Categoría 1
    if (!empty($categoria1_get)) {
        $where_conditions[] = "categoria1_id = :categoria1";
        $params[':categoria1'] = $categoria1_get;
    }
    
    // Categoría 2
    if (!empty($categoria2_get)) {
        $where_conditions[] = "categoria2_id = :categoria2";
        $params[':categoria2'] = $categoria2_get;
    }
    
    // Estado
    if (!empty($estado_get)) {
        // Verificar si la columna estado existe
        $check_estado = $pdo->query("SHOW COLUMNS FROM stock_calculado_cache LIKE 'estado'")->fetch();
        if ($check_estado) {
            $where_conditions[] = "estado = :estado";
            $params[':estado'] = $estado_get;
        }
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    // --- CONTAR TOTAL DE RESULTADOS ---
    $count_sql = "SELECT COUNT(*) FROM stock_calculado_cache WHERE $where_clause";
    $count_stmt = $pdo->prepare($count_sql);
    $count_stmt->execute($params);
    $total_items = $count_stmt->fetchColumn();
    
    // --- PAGINACIÓN ---
    $items_per_page = 50;
    $current_page_num = $page_num;
    $total_pages = max(1, ceil($total_items / $items_per_page));
    
    if ($current_page_num > $total_pages) {
        $current_page_num = $total_pages;
    }
    
    $offset = ($current_page_num - 1) * $items_per_page;
    
    // --- VERIFICAR SI EXISTE LA COLUMNA ESTADO ---
    $has_estado_column = $pdo->query("SHOW COLUMNS FROM stock_calculado_cache LIKE 'estado'")->fetch() ? true : false;
    
    // --- DEFINIR ORDENAMIENTO MEJORADO ---
    $order_clause = "ORDER BY ";
    switch ($orden_get) {
        case 'precio_asc':
            $order_clause .= "precio ASC, nombre ASC";
            break;
        case 'precio_desc':
            $order_clause .= "precio DESC, nombre ASC";
            break;
        case 'precio_final_asc':
            $order_clause .= "precio_final ASC, nombre ASC";
            break;
        case 'precio_final_desc':
            $order_clause .= "precio_final DESC, nombre ASC";
            break;
        case 'descuento_asc':
            $order_clause .= "descuento ASC, nombre ASC";
            break;
        case 'descuento_desc':
            $order_clause .= "descuento DESC, nombre ASC";
            break;
        case 'stock_asc':
            $order_clause .= "stock_total ASC, nombre ASC";
            break;
        case 'stock_desc':
            $order_clause .= "stock_total DESC, nombre ASC";
            break;
        case 'nombre_desc':
            $order_clause .= "nombre DESC";
            break;
        case 'nombre_asc':
        default:
            $order_clause .= "nombre ASC";
            break;
    }
    
    // --- OBTENER DATOS PAGINADOS ---
    $estado_select = $has_estado_column ? ", estado" : ", NULL as estado";
    
    $data_sql = "
        SELECT 
            id,
            codigo,
            codigo_unico,
            nombre,
            tipo,
            bodega,
            tienda,
            ubicacion,
            almacen,
            stock_total,
            stock_sat,
            stock_outlet,
            stock_showroom,
            stock_own,
            precio,
            descuento,
            precio_final,
            origen_descuento,
            categoria1,
            categoria2,
            categoria1_id,
            categoria2_id,
            es_kit,
            es_imperfecto,
            es_excepcion,
            ultima_actualizacion
            $estado_select
        FROM stock_calculado_cache 
        WHERE $where_clause
        $order_clause
        LIMIT :limit OFFSET :offset
    ";
    
    $data_stmt = $pdo->prepare($data_sql);
    foreach ($params as $key => $value) {
        $data_stmt->bindValue($key, $value);
    }
    $data_stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
    $data_stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $data_stmt->execute();
    
    $paginated_items = $data_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // --- OBTENER LISTAS PARA FILTROS ---
    // Categorías nivel 1
    $categorias1 = $pdo->query("
        SELECT DISTINCT c1.id, c1.nombre 
        FROM stock_calculado_cache scc
        INNER JOIN categorias_nivel1 c1 ON scc.categoria1_id = c1.id
        WHERE scc.stock_total > 0
        ORDER BY c1.nombre
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Categorías nivel 2 (filtradas por categoría 1 si está seleccionada)
    if (!empty($categoria1_get)) {
        $stmt_cat2 = $pdo->prepare("
            SELECT DISTINCT c2.id, c2.nombre 
            FROM stock_calculado_cache scc
            INNER JOIN categorias_nivel2 c2 ON scc.categoria2_id = c2.id
            WHERE scc.stock_total > 0 AND scc.categoria1_id = :cat1
            ORDER BY c2.nombre
        ");
        $stmt_cat2->execute([':cat1' => $categoria1_get]);
        $categorias2 = $stmt_cat2->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $categorias2 = $pdo->query("
            SELECT DISTINCT c2.id, c2.nombre 
            FROM stock_calculado_cache scc
            INNER JOIN categorias_nivel2 c2 ON scc.categoria2_id = c2.id
            WHERE scc.stock_total > 0
            ORDER BY c2.nombre
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Estados únicos
    $estados = [];
    if ($has_estado_column) {
        $estados = $pdo->query("
            SELECT DISTINCT estado 
            FROM stock_calculado_cache 
            WHERE estado IS NOT NULL AND stock_total > 0
            ORDER BY estado
        ")->fetchAll(PDO::FETCH_COLUMN);
    }
    
} catch (Exception $e) {
    $db_error = $e->getMessage();
}

// Función para formatear fecha
function formatDate($dateString) {
    if (empty($dateString)) return 'No disponible';
    return date('d/m/Y H:i', strtotime($dateString));
}

// Función para obtener URL de imagen
function getImageUrl($codigo, $codigo_unico = null) {
    // IMPORTANTE: Siempre usar el código (referencia) para la imagen
    // El código contiene la referencia correcta para buscar la foto
    $codigo_imagen = $codigo;
    return "https://imagenes.crusardi.net/boconcept/STOCKCOMERCIAL/{$codigo_imagen}.jpg";
}

// Función para obtener badge de estado
function getEstadoBadge($estado) {
    if (empty($estado)) return '<span class="text-gray-400">-</span>';
    
    $badges = [
        'activo' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Activo</span>',
        'inactivo' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">Inactivo</span>',
        'descontinuado' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">Descontinuado</span>',
        'agotado' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-orange-100 text-orange-800">Agotado</span>',
        'disponible' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">Disponible</span>',
    ];
    
    $estado_lower = strtolower($estado);
    return $badges[$estado_lower] ?? '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">' . htmlspecialchars($estado) . '</span>';
}

// Función para obtener información adicional de productos imperfectos
function getImperfectoInfo($codigo_unico, $pdo) {
    if (empty($codigo_unico)) return null;
    
    try {
        $stmt = $pdo->prepare("
            SELECT notas, imagen_detalle_1, imagen_detalle_2, imagen_detalle_3, 
                   imagen_detalle_4, imagen_detalle_5
            FROM productos_imperfectos 
            WHERE codigo_unico = :codigo_unico
            LIMIT 1
        ");
        $stmt->execute([':codigo_unico' => $codigo_unico]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return null;
    }
}
?>

<div class="space-y-6">
    <!-- Header con botón de consolidación -->
    <header class="bg-white p-4 rounded-lg shadow-md">
        <div class="flex justify-between items-center mb-4">
            <div>
                <h1 class="text-2xl font-bold text-gray-800">Calculadora de STOCK</h1>
                <p class="text-gray-600">Transformamos espacios en pers💛nas felices</p>
            </div>
            <div class="flex items-center gap-4">
                <form method="POST" action="index.php?page=stock_calculado" class="inline">
                    <input type="hidden" name="action" value="consolidar">
                    <button type="submit" 
                            onclick="return confirm('¿Ejecutar consolidación de stock? Esto puede tomar unos segundos.')"
                            class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors flex items-center gap-2">
                        <i class="fas fa-sync-alt"></i>
                        Consolidar Stock
                    </button>
                </form>
                <?php if (!empty($stats['ultima_actualizacion'])): ?>
                <div class="text-sm text-gray-600">
                    <i class="fas fa-clock mr-1"></i>
                    Última actualización: <?php echo formatDate($stats['ultima_actualizacion']); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- KPIs sin el contador de productos -->
        <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
            <div class="bg-gray-50 p-3 rounded-lg flex items-center gap-3">
                <div class="bg-yellow-100 text-yellow-600 p-3 rounded-full">
                    <i class="fas fa-box-open"></i>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Unidades</p>
                    <p class="text-xl font-bold text-gray-800"><?php echo number_format($stats['total_unidades'] ?? 0); ?></p>
                </div>
            </div>
            
            <div class="bg-gray-50 p-3 rounded-lg flex items-center gap-3">
                <div class="bg-purple-100 text-purple-600 p-3 rounded-full">
                    <i class="fas fa-cubes"></i>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Kits</p>
                    <p class="text-xl font-bold text-gray-800"><?php echo number_format($stats['total_kits'] ?? 0); ?></p>
                </div>
            </div>
            
            <div class="bg-gray-50 p-3 rounded-lg flex items-center gap-3">
                <div class="bg-teal-100 text-teal-600 p-3 rounded-full">
                    <i class="fas fa-tag"></i>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Artículos</p>
                    <p class="text-xl font-bold text-gray-800"><?php echo number_format($stats['total_articulos'] ?? 0); ?></p>
                </div>
            </div>
            
            <div class="bg-gray-50 p-3 rounded-lg flex items-center gap-3">
                <div class="bg-red-100 text-red-600 p-3 rounded-full">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Imperfectos</p>
                    <p class="text-xl font-bold text-gray-800"><?php echo number_format($stats['total_imperfectos'] ?? 0); ?></p>
                </div>
            </div>
            
            <div class="bg-gray-50 p-3 rounded-lg flex items-center gap-3">
                <div class="bg-orange-100 text-orange-600 p-3 rounded-full">
                    <i class="fas fa-puzzle-piece"></i>
                </div>
                <div>
                    <p class="text-xs text-gray-500">Partes</p>
                    <p class="text-xl font-bold text-gray-800"><?php echo number_format($stats['total_partes'] ?? 0); ?></p>
                </div>
            </div>
        </div>
    </header>

    <!-- Mensajes -->
    <?php if ($upload_success_message): ?>
    <div id="alert-success" class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative alert-message">
        <span class="block sm:inline"><?php echo htmlspecialchars($upload_success_message); ?></span>
    </div>
    <?php endif; ?>

    <?php if ($upload_error_message): ?>
    <div id="alert-error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative alert-message">
        <span class="block sm:inline"><?php echo htmlspecialchars($upload_error_message); ?></span>
    </div>
    <?php endif; ?>

    <?php if ($db_error): ?>
    <div id="alert-db-error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative alert-message">
        <strong class="font-bold">Error:</strong>
        <span class="block sm:inline"><?php echo htmlspecialchars($db_error); ?></span>
    </div>
    <?php endif; ?>

    <!-- Filtros con ordenamiento mejorado -->
    <div class="bg-white p-6 rounded-lg shadow-md">
        <form method="GET" action="index.php">
            <input type="hidden" name="page" value="stock_calculado">
            
            <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                <!-- Búsqueda -->
                <div class="xl:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Buscar</label>
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search_get); ?>"
                           placeholder="Código, nombre..."
                           class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <!-- Tipo -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                    <select name="tipo" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        <option value="">Todos</option>
                        <option value="kit" <?php echo $tipo_get === 'kit' ? 'selected' : ''; ?>>Kits</option>
                        <option value="articulo" <?php echo $tipo_get === 'articulo' ? 'selected' : ''; ?>>Artículos</option>
                        <option value="imperfecto" <?php echo $tipo_get === 'imperfecto' ? 'selected' : ''; ?>>Imperfectos</option>
                        <option value="parte" <?php echo $tipo_get === 'parte' ? 'selected' : ''; ?>>Partes</option>
                    </select>
                </div>
                
                <!-- Bodega -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Bodega</label>
                    <select name="bodega" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        <option value="">Todas</option>
                        <?php
                        $bodegas = $pdo->query("SELECT DISTINCT bodega FROM stock_calculado_cache WHERE bodega IS NOT NULL ORDER BY bodega")->fetchAll(PDO::FETCH_COLUMN);
                        foreach ($bodegas as $bodega):
                        ?>
                        <option value="<?php echo htmlspecialchars($bodega); ?>" <?php echo $bodega_get === $bodega ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($bodega); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Categoría 1 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Categoría 1</label>
                    <select name="categoria1" id="categoria1" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        <option value="">Todas</option>
                        <?php foreach ($categorias1 as $cat1): ?>
                        <option value="<?php echo $cat1['id']; ?>" <?php echo $categoria1_get == $cat1['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat1['nombre']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Categoría 2 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Categoría 2</label>
                    <select name="categoria2" id="categoria2" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        <option value="">Todas</option>
                        <?php foreach ($categorias2 as $cat2): ?>
                        <option value="<?php echo $cat2['id']; ?>" <?php echo $categoria2_get == $cat2['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat2['nombre']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Estado -->
                <?php if (!empty($estados)): ?>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Estado de axapta</label>
                    <select name="estado" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        <option value="">Todos</option>
                        <?php foreach ($estados as $estado): ?>
                        <option value="<?php echo htmlspecialchars($estado); ?>" <?php echo $estado_get === $estado ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($estado); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                
                <!-- Ordenamiento mejorado -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Ordenar por</label>
                    <select name="orden" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        <option value="nombre_asc" <?php echo $orden_get === 'nombre_asc' ? 'selected' : ''; ?>>Nombre (A-Z)</option>
                        <option value="nombre_desc" <?php echo $orden_get === 'nombre_desc' ? 'selected' : ''; ?>>Nombre (Z-A)</option>
                        <option value="precio_desc" <?php echo $orden_get === 'precio_desc' ? 'selected' : ''; ?>>Mayor precio</option>
                        <option value="precio_asc" <?php echo $orden_get === 'precio_asc' ? 'selected' : ''; ?>>Menor precio</option>
                        <option value="precio_final_desc" <?php echo $orden_get === 'precio_final_desc' ? 'selected' : ''; ?>>Mayor precio final</option>
                        <option value="precio_final_asc" <?php echo $orden_get === 'precio_final_asc' ? 'selected' : ''; ?>>Menor precio final</option>
                        <option value="descuento_desc" <?php echo $orden_get === 'descuento_desc' ? 'selected' : ''; ?>>Mayor descuento</option>
                        <option value="descuento_asc" <?php echo $orden_get === 'descuento_asc' ? 'selected' : ''; ?>>Menor descuento</option>
                        <option value="stock_desc" <?php echo $orden_get === 'stock_desc' ? 'selected' : ''; ?>>Mayor stock</option>
                        <option value="stock_asc" <?php echo $orden_get === 'stock_asc' ? 'selected' : ''; ?>>Menor stock</option>
                    </select>
                </div>
                
                <!-- Botones -->
                <div class="md:col-span-3 lg:col-span-4 xl:col-span-5">
                    <label class="block text-sm font-medium text-gray-700 mb-1">&nbsp;</label>
                    <div class="flex gap-2">
                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                            <i class="fas fa-search mr-2"></i>Buscar
                        </button>
                        <a href="?page=stock_calculado" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
                            <i class="fas fa-redo mr-2"></i>Limpiar filtros
                        </a>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Toggle Vista y Productos -->
    <?php if (!empty($paginated_items)): ?>
    
    <!-- Vista de Tabla (visible en desktop) -->
    <div id="table-view" class="bg-white rounded-lg shadow-md overflow-hidden hidden md:block">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Imagen</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Código</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nombre</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tipo</th>
                        <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Stock</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Ubicación</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase hidden md:table-cell">Cat. 1</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase hidden lg:table-cell">Cat. 2</th>
                        <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase hidden xl:table-cell">Estado</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Precio</th>
                        <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Desc.</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">P. Final</th>
                        <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Acciones</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($paginated_items as $item): ?>
                    <tr class="hover:bg-gray-50 <?php echo $item['es_imperfecto'] ? 'bg-yellow-50' : ''; ?>">
                        <td class="px-4 py-3 whitespace-nowrap">
                            <img src="<?php echo htmlspecialchars(getImageUrl($item['codigo'], $item['codigo_unico'])); ?>" 
                                 alt="<?php echo htmlspecialchars($item['codigo']); ?>"
                                 class="h-12 w-12 object-cover rounded cursor-pointer hover:scale-110 transition-transform"
                                 onerror="this.src='https://imagenes.crusardi.net/boconcept/sin_foto.png'"
                                 onclick="window.open(this.src, '_blank')">
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="font-medium text-gray-900"><?php echo htmlspecialchars($item['codigo']); ?></div>
                            <?php if ($item['codigo_unico']): ?>
                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($item['codigo_unico']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3">
                            <div class="text-sm text-gray-900">
                                <?php echo htmlspecialchars($item['nombre'] ?: 'Sin nombre'); ?>
                            </div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <?php 
                            $tipo_badges = [
                                'kit' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-purple-100 text-purple-800">Kit</span>',
                                'articulo' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">Artículo</span>',
                                'imperfecto' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">Imperfecto</span>',
                                'parte' => '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-orange-100 text-orange-800">Parte</span>'
                            ];
                            echo $tipo_badges[$item['tipo']] ?? htmlspecialchars($item['tipo']);
                            ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-center">
                            <div class="font-semibold text-gray-900"><?php echo number_format($item['stock_total']); ?></div>
                            <div class="text-xs text-gray-500">
                                <?php if ($item['stock_sat'] > 0): ?>
                                    <span class="inline-block">SAT:<?php echo $item['stock_sat']; ?></span>
                                <?php endif; ?>
                                <?php if ($item['stock_outlet'] > 0): ?>
                                    <span class="inline-block ml-1">OUT:<?php echo $item['stock_outlet']; ?></span>
                                <?php endif; ?>
                                <?php if ($item['stock_showroom'] > 0): ?>
                                    <span class="inline-block ml-1">SHOW:<?php echo $item['stock_showroom']; ?></span>
                                <?php endif; ?>
                                <?php if ($item['stock_own'] > 0): ?>
                                    <span class="inline-block ml-1">OWN:<?php echo $item['stock_own']; ?></span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm">
                            <?php if ($item['tienda']): ?>
                                <div class="font-medium"><?php echo htmlspecialchars($item['tienda']); ?></div>
                            <?php endif; ?>
                            <?php if ($item['ubicacion']): ?>
                                <div class="text-xs text-gray-500">📍 <?php echo htmlspecialchars($item['ubicacion']); ?></div>
                            <?php endif; ?>
                            <?php if ($item['bodega'] && $item['bodega'] != $item['tienda']): ?>
                                <div class="text-xs text-gray-400"> Bod: <?php echo htmlspecialchars($item['bodega']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap hidden md:table-cell">
                            <div class="text-sm text-gray-900">
                                <?php echo htmlspecialchars($item['categoria1'] ?: '-'); ?>
                            </div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap hidden lg:table-cell">
                            <div class="text-sm text-gray-900">
                                <?php echo htmlspecialchars($item['categoria2'] ?: '-'); ?>
                            </div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-center hidden xl:table-cell">
                            <?php echo getEstadoBadge($item['estado'] ?? ''); ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-right">
                            <?php if ($item['descuento'] > 0): ?>
                                <div class="line-through text-gray-400">$<?php echo number_format($item['precio'], 2); ?></div>
                            <?php else: ?>
                                <div>$<?php echo number_format($item['precio'], 2); ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-center">
                            <?php if ($item['descuento'] > 0): ?>
                                <span class="px-2 py-1 text-xs font-semibold rounded bg-green-100 text-green-800" 
                                      title="<?php echo htmlspecialchars($item['origen_descuento'] ?? 'Descuento aplicado'); ?>">
                                    <?php echo number_format($item['descuento'], 0); ?>%
                                </span>
                            <?php else: ?>
                                <span class="text-gray-400">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-right">
                            <div class="font-bold <?php echo $item['descuento'] > 0 ? 'text-green-600' : 'text-gray-900'; ?>">
                                $<?php echo number_format($item['precio_final'], 2); ?>
                            </div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-center">
                            <?php if ($item['es_imperfecto'] && $item['codigo_unico']): ?>
                                <?php 
                                $imperfecto_info = getImperfectoInfo($item['codigo_unico'], $pdo);
                                $has_notes = !empty($imperfecto_info['notas']);
                                $has_images = false;
                                for ($i = 1; $i <= 5; $i++) {
                                    if (!empty($imperfecto_info["imagen_detalle_$i"])) {
                                        $has_images = true;
                                        break;
                                    }
                                }
                                ?>
                                <div class="flex gap-1 justify-center">
                                    <?php if ($has_notes): ?>
                                    <button onclick="showNotes('<?php echo htmlspecialchars($item['codigo_unico']); ?>', <?php echo htmlspecialchars(json_encode($imperfecto_info['notas'])); ?>)"
                                            class="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 transition-colors"
                                            title="Ver notas">
                                        <i class="fas fa-sticky-note"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button onclick="showGallery('<?php echo htmlspecialchars($item['codigo_unico']); ?>')"
                                            class="px-2 py-1 bg-purple-500 text-white text-xs rounded hover:bg-purple-600 transition-colors"
                                            title="Ver galería de detalles">
                                        <i class="fas fa-images"></i>
                                    </button>
                                </div>
                            <?php else: ?>
                                <span class="text-gray-400">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Vista de Tarjetas Móvil Mejorada (solo móvil) -->
    <div id="cards-view" class="block md:hidden space-y-3">
        <?php foreach ($paginated_items as $item): ?>
        <div class="bg-white rounded-lg shadow-md <?php echo $item['es_imperfecto'] ? 'ring-2 ring-yellow-400' : ''; ?>">
            <div class="flex">
                <!-- Imagen -->
                <div class="w-24 h-24 flex-shrink-0">
                    <img src="<?php echo htmlspecialchars(getImageUrl($item['codigo'], $item['codigo_unico'])); ?>" 
                         alt="<?php echo htmlspecialchars($item['codigo']); ?>"
                         class="w-full h-full object-cover rounded-l-lg"
                         onerror="this.src='https://imagenes.crusardi.net/boconcept/sin_foto.png'"
                         onclick="window.open(this.src, '_blank')">
                </div>
                
                <!-- Información -->
                <div class="flex-1 p-3">
                    <!-- Código y tipo -->
                    <div class="flex justify-between items-start mb-1">
                        <div>
                            <div class="font-bold text-sm text-gray-900"><?php echo htmlspecialchars($item['codigo']); ?></div>
                            <?php if ($item['codigo_unico']): ?>
                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($item['codigo_unico']); ?></div>
                            <?php endif; ?>
                        </div>
                        <?php 
                        $tipo_badges_mini = [
                            'kit' => '<span class="px-1.5 py-0.5 text-xs font-semibold rounded bg-purple-100 text-purple-800">Kit</span>',
                            'articulo' => '<span class="px-1.5 py-0.5 text-xs font-semibold rounded bg-blue-100 text-blue-800">Art</span>',
                            'imperfecto' => '<span class="px-1.5 py-0.5 text-xs font-semibold rounded bg-red-100 text-red-800">Imp</span>',
                            'parte' => '<span class="px-1.5 py-0.5 text-xs font-semibold rounded bg-orange-100 text-orange-800">Parte</span>'
                        ];
                        echo $tipo_badges_mini[$item['tipo']] ?? '';
                        ?>
                    </div>
                    
                    <!-- Nombre -->
                    <div class="text-xs text-gray-700 mb-1 line-clamp-1">
                        <?php echo htmlspecialchars($item['nombre'] ?: 'Sin nombre'); ?>
                    </div>
                    
                    <!-- UBICACIÓN  para productos imperfectos -->
                    <div class="text-xs text-gray-500 mb-1">
                        <i class="fas fa-map-marker-alt text-xs mr-1"></i>
                        <?php if ($item['tienda']): ?>
                            <span class="font-semibold"><?php echo htmlspecialchars($item['tienda']); ?></span>
                        <?php else: ?>
                            <span class="font-semibold"><?php echo htmlspecialchars($item['bodega'] ?: 'Sin ubicación'); ?></span>
                        <?php endif; ?>
                        <?php if ($item['ubicacion']): ?>
                            / <?php echo htmlspecialchars($item['ubicacion']); ?>
                        <?php elseif ($item['almacen']): ?>
                            / <?php echo htmlspecialchars($item['almacen']); ?>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Stock y precio -->
                    <div class="flex justify-between items-end">
                        <div>
                            <span class="text-xs text-gray-500">Stock:</span>
                            <span class="font-bold text-sm ml-1"><?php echo number_format($item['stock_total']); ?></span>
                        </div>
                        
                        <div class="text-right">
                            <?php if ($item['descuento'] > 0): ?>
                                <span class="bg-green-500 text-white text-xs px-1 py-0.5 rounded font-bold mr-1">
                                    -<?php echo number_format($item['descuento'], 0); ?>%
                                </span>
                                <div class="text-xs line-through text-gray-400">$<?php echo number_format($item['precio'], 0); ?></div>
                                <div class="font-bold text-green-600">$<?php echo number_format($item['precio_final'], 0); ?></div>
                            <?php else: ?>
                                <div class="font-bold text-gray-900">$<?php echo number_format($item['precio'], 0); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Botones de acción para imperfectos -->
                    <?php if ($item['es_imperfecto'] && $item['codigo_unico']): ?>
                        <?php 
                        $imperfecto_info = getImperfectoInfo($item['codigo_unico'], $pdo);
                        $has_notes = !empty($imperfecto_info['notas']);
                        ?>
                        <div class="flex gap-1 mt-2 pt-2 border-t">
                            <?php if ($has_notes): ?>
                            <button onclick="showNotes('<?php echo htmlspecialchars($item['codigo_unico']); ?>', <?php echo htmlspecialchars(json_encode($imperfecto_info['notas'])); ?>)"
                                    class="flex-1 px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600">
                                <i class="fas fa-sticky-note mr-1"></i>Notas
                            </button>
                            <?php endif; ?>
                            <button onclick="showGallery('<?php echo htmlspecialchars($item['codigo_unico']); ?>')"
                                    class="flex-1 px-2 py-1 bg-purple-500 text-white text-xs rounded hover:bg-purple-600">
                                <i class="fas fa-images mr-1"></i>Detalles
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
        
        <!-- Paginación -->
        <?php if ($total_pages > 1): ?>
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200">
            <div class="flex-1 flex justify-between sm:hidden">
                <?php if ($current_page_num > 1): ?>
                <a href="?page=stock_calculado&page_num=<?php echo $current_page_num - 1; ?>&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                   class="px-4 py-2 border text-sm rounded-md">
                    Anterior
                </a>
                <?php endif; ?>
                <?php if ($current_page_num < $total_pages): ?>
                <a href="?page=stock_calculado&page_num=<?php echo $current_page_num + 1; ?>&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                   class="px-4 py-2 border text-sm rounded-md">
                    Siguiente
                </a>
                <?php endif; ?>
            </div>
            
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        Mostrando <span class="font-medium"><?php echo $offset + 1; ?></span> a 
                        <span class="font-medium"><?php echo min($offset + $items_per_page, $total_items); ?></span> de 
                        <span class="font-medium"><?php echo number_format($total_items); ?></span> resultados
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                        <?php if ($current_page_num > 1): ?>
                        <a href="?page=stock_calculado&page_num=1&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                           class="px-2 py-2 rounded-l-md border bg-white text-sm">
                            <i class="fas fa-angle-double-left"></i>
                        </a>
                        <a href="?page=stock_calculado&page_num=<?php echo $current_page_num - 1; ?>&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                           class="px-2 py-2 border bg-white text-sm">
                            <i class="fas fa-angle-left"></i>
                        </a>
                        <?php endif; ?>
                        
                        <?php
                        $start = max(1, $current_page_num - 2);
                        $end = min($total_pages, $current_page_num + 2);
                        
                        for ($i = $start; $i <= $end; $i++):
                        ?>
                        <a href="?page=stock_calculado&page_num=<?php echo $i; ?>&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                           class="px-4 py-2 border text-sm <?php echo $i === $current_page_num ? 'bg-blue-50 border-blue-500 text-blue-600 font-medium' : 'bg-white'; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>
                        
                        <?php if ($current_page_num < $total_pages): ?>
                        <a href="?page=stock_calculado&page_num=<?php echo $current_page_num + 1; ?>&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                           class="px-2 py-2 border bg-white text-sm">
                            <i class="fas fa-angle-right"></i>
                        </a>
                        <a href="?page=stock_calculado&page_num=<?php echo $total_pages; ?>&<?php echo http_build_query(array_diff_key($_GET, array_flip(['page', 'page_num']))); ?>" 
                           class="px-2 py-2 rounded-r-md border bg-white text-sm">
                            <i class="fas fa-angle-double-right"></i>
                        </a>
                        <?php endif; ?>
                    </nav>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php else: ?>
    <div class="bg-white rounded-lg shadow-md p-12 text-center">
        <i class="fas fa-box-open text-6xl text-gray-300 mb-4"></i>
        <h3 class="text-lg font-medium text-gray-900 mb-2">No se encontraron productos</h3>
        <p class="text-gray-600 mb-4">
            <?php if (!empty($search_get) || !empty($tipo_get) || !empty($bodega_get) || !empty($categoria1_get) || !empty($categoria2_get) || !empty($estado_get)): ?>
                No hay productos que coincidan con los filtros seleccionados.
            <?php else: ?>
                La tabla de stock está vacía. Ejecuta la consolidación para cargar los datos.
            <?php endif; ?>
        </p>
        <div class="flex justify-center gap-2">
            <?php if (!empty($search_get) || !empty($tipo_get) || !empty($bodega_get) || !empty($categoria1_get) || !empty($categoria2_get) || !empty($estado_get)): ?>
            <a href="?page=stock_calculado" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
                <i class="fas fa-redo mr-2"></i>Limpiar filtros
            </a>
            <?php endif; ?>
            <form method="POST" action="index.php?page=stock_calculado" class="inline">
                <input type="hidden" name="action" value="consolidar">
                <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                    <i class="fas fa-sync-alt mr-2"></i>Consolidar Stock
                </button>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Modal para Notas -->
<div id="notesModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75" onclick="closeNotesModal()"></div>
        <div class="relative w-full max-w-lg mx-auto bg-white rounded-lg shadow-xl">
            <div class="p-4 sm:p-6">
                <div class="flex justify-between items-start mb-4">
                    <h3 class="text-lg font-medium text-gray-900">Notas del Producto</h3>
                    <button onclick="closeNotesModal()" class="text-gray-400 hover:text-gray-500">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div id="notesContent" class="mt-2 text-sm text-gray-600 whitespace-pre-wrap max-h-60 sm:max-h-96 overflow-y-auto bg-gray-50 p-3 rounded"></div>
            </div>
            <div class="px-4 py-3 bg-gray-50 sm:px-6 flex flex-col sm:flex-row-reverse gap-2">
                <button type="button" onclick="closeNotesModal()" 
                        class="w-full sm:w-auto px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm hover:bg-blue-700 focus:outline-none">
                    Cerrar
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal para Galería de Imágenes -->
<div id="galleryModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen p-2 sm:p-4">
        <div class="fixed inset-0 transition-opacity bg-gray-900 bg-opacity-90" onclick="closeGalleryModal()"></div>
        <div class="relative w-full max-w-5xl mx-auto bg-white rounded-lg shadow-xl max-h-[95vh] overflow-y-auto">
            <div class="sticky top-0 z-10 bg-white border-b">
                <div class="flex justify-between items-center p-4">
                    <h3 class="text-sm sm:text-lg font-medium text-gray-900">
                        <i class="fas fa-images mr-1 sm:mr-2"></i>
                        <span class="hidden sm:inline">Galería de Detalles - </span>
                        <span id="galleryTitle"></span>
                    </h3>
                    <button onclick="closeGalleryModal()" class="text-gray-400 hover:text-gray-500 text-xl p-2">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <div class="p-4">
                <!-- Imagen principal -->
                <div class="mb-4">
                    <img id="mainGalleryImage" src="" alt="Imagen de detalle" 
                         class="w-full h-48 sm:h-64 md:h-96 lg:h-[700px] object-contain bg-gray-100 rounded-lg"
                         onerror="this.src='https://imagenes.crusardi.net/boconcept/sin_foto.png'">
                </div>
                
                <!-- Miniaturas -->
                <div class="grid grid-cols-5 gap-1 sm:gap-2" id="galleryThumbnails">
                    <!-- Se llenarán dinámicamente con JavaScript -->
                </div>
                
                <!-- Indicador de carga -->
                <div id="galleryLoading" class="text-center py-4 hidden">
                    <i class="fas fa-spinner fa-spin text-2xl text-gray-400"></i>
                    <p class="text-sm text-gray-500 mt-2">Cargando imágenes...</p>
                </div>
            </div>
            
            <div class="sticky bottom-0 px-4 py-3 bg-gray-50 border-t">
                <div class="flex flex-col sm:flex-row sm:items-center gap-2">
                    <button type="button" onclick="closeGalleryModal()" 
                            class="w-full sm:w-auto px-4 py-2 text-sm font-medium text-white bg-purple-600 border border-transparent rounded-md shadow-sm hover:bg-purple-700 focus:outline-none">
                        Cerrar
                    </button>
                    <span class="text-xs text-gray-500 text-center sm:text-left sm:ml-auto">
                        <i class="fas fa-info-circle mr-1"></i>
                        <span class="hidden sm:inline">Las imágenes se cargan desde: /SALE2019/N [código]/1-5.jpg</span>
                        <span class="sm:hidden">Fotos: SALE2019/N [código]</span>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Función para previsualizar imagen en modal
function previewImage(url) {
    window.open(url, '_blank', 'width=800,height=600');
}

// Auto-cerrar SOLO mensajes de alerta después de 5 segundos
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-message');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 5000);

// Función para mostrar notas
function showNotes(codigo, notas) {
    const modal = document.getElementById('notesModal');
    const content = document.getElementById('notesContent');
    
    content.textContent = notas || 'No hay notas disponibles para este producto.';
    modal.classList.remove('hidden');
}

// Función para cerrar modal de notas
function closeNotesModal() {
    document.getElementById('notesModal').classList.add('hidden');
}

// Función para mostrar galería con mejor manejo responsivo
function showGallery(codigoUnico) {
    const modal = document.getElementById('galleryModal');
    const mainImage = document.getElementById('mainGalleryImage');
    const thumbnails = document.getElementById('galleryThumbnails');
    const loading = document.getElementById('galleryLoading');
    const title = document.getElementById('galleryTitle');
    
    // Limpiar contenido anterior
    thumbnails.innerHTML = '';
    title.textContent = codigoUnico;
    
    // Mostrar modal y loading
    modal.classList.remove('hidden');
    loading.classList.remove('hidden');
    
    // Prevenir scroll del body cuando el modal está abierto
    document.body.style.overflow = 'hidden';
    
    // URL base para las imágenes (el espacio se codifica automáticamente como %20)
    const baseUrl = 'https://imagenes.crusardi.net/boconcept/SALE2019/N ' + codigoUnico;
    
    // Cargar las 5 imágenes posibles
    let loadedImages = 0;
    let firstValidImage = null;
    
    for (let i = 1; i <= 5; i++) {
        const imgUrl = baseUrl + '/' + i + '.jpg';
        const thumbContainer = document.createElement('div');
        thumbContainer.className = 'relative group cursor-pointer overflow-hidden rounded-lg bg-gray-100 aspect-square';
        
        const img = document.createElement('img');
        img.src = imgUrl;
        img.alt = 'Detalle ' + i;
        img.className = 'w-full h-full object-cover transition-transform group-hover:scale-110';
        img.dataset.imageNumber = i;
        
        img.onload = function() {
            loadedImages++;
            if (!firstValidImage) {
                firstValidImage = imgUrl;
                mainImage.src = imgUrl;
            }
            thumbContainer.appendChild(img);
            thumbnails.appendChild(thumbContainer);
            
            // Agregar evento click para cambiar imagen principal
            thumbContainer.onclick = function() {
                mainImage.src = imgUrl;
                // Resaltar miniatura activa
                document.querySelectorAll('#galleryThumbnails > div').forEach(div => {
                    div.classList.remove('ring-2', 'ring-purple-500');
                });
                thumbContainer.classList.add('ring-2', 'ring-purple-500');
            };
            
            // Si es la primera imagen, marcarla como activa
            if (imgUrl === firstValidImage) {
                thumbContainer.classList.add('ring-2', 'ring-purple-500');
            }
            
            if (loadedImages === 1) {
                loading.classList.add('hidden');
            }
        };
        
        img.onerror = function() {
            // Si no se encuentra la imagen, mostrar placeholder
            const placeholder = document.createElement('div');
            placeholder.className = 'w-full h-full flex items-center justify-center bg-gray-200';
            placeholder.innerHTML = '<i class="fas fa-image text-gray-400 text-lg sm:text-2xl"></i>';
            thumbContainer.appendChild(placeholder);
            thumbnails.appendChild(thumbContainer);
            
            loadedImages++;
            if (loadedImages === 5 && !firstValidImage) {
                // Si ninguna imagen cargó, mostrar mensaje
                mainImage.src = 'https://imagenes.crusardi.net/boconcept/sin_foto.png';
                loading.innerHTML = '<p class="text-sm text-gray-500">No se encontraron imágenes de detalle</p>';
            }
        };
    }
}

// Función para cerrar modal de galería
function closeGalleryModal() {
    document.getElementById('galleryModal').classList.add('hidden');
    document.getElementById('mainGalleryImage').src = '';
    document.getElementById('galleryThumbnails').innerHTML = '';
    // Restaurar scroll del body
    document.body.style.overflow = '';
}

// Cerrar modales con tecla ESC
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeNotesModal();
        closeGalleryModal();
    }
});

// Actualizar categoría 2 cuando cambia categoría 1 (si quieres implementar AJAX)
document.getElementById('categoria1')?.addEventListener('change', function() {
    // Aquí podrías implementar AJAX para actualizar dinámicamente categoria2
});
</script>