<?php
// ===================================
// ARCHIVO: catalog.php
// Catálogo principal con vista diferenciada
// ===================================

$page_title = "Catálogo";
$page_description = "Catálogo de calzado mayorista con acceso a fábricas";
$breadcrumbs = [
    ['label' => 'Catálogo']
];
$additional_css = ['assets/css/catalog.css'];

require_once 'config/session.php';
debugSession('Catalog');

require_once 'config/database.php';
require_once 'includes/functions.php';

// Verificar token "recordarme" si no está logueado
if (!isLoggedIn()) {
    checkRememberToken();
}

// Determinar tipo de vista
$is_public_view = !isLoggedIn() || !isApproved();
$show_prices = isLoggedIn() && isApproved();
$user_info = isLoggedIn() ? getUserInfo($_SESSION['user_id']) : null;

// Parámetros de filtrado y búsqueda
$search = sanitizeInput($_GET['search'] ?? '', 'string');
$gender = $_GET['gender'] ?? '';
$season = $_GET['season'] ?? '';
$formality = $_GET['formality'] ?? '';
$factory_id = (int)($_GET['factory'] ?? 0);
$min_price = (float)($_GET['min_price'] ?? 0);
$max_price = (float)($_GET['max_price'] ?? 0);
$task_type = $_GET['task_type'] ?? '';
$sort_by = $_GET['sort'] ?? 'newest';
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 12;
$offset = ($page - 1) * $per_page;

// Construir consulta con filtros
$where_conditions = ["p.is_active = TRUE"];
$params = [];

if ($search) {
    $where_conditions[] = "(p.name LIKE ? OR p.sku LIKE ? OR f.name LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term]);
}

if ($gender && in_array($gender, ['hombre', 'mujer', 'unisex', 'niño', 'niña'])) {
    $where_conditions[] = "p.gender = ?";
    $params[] = $gender;
}

if ($season && in_array($season, ['verano', 'invierno', 'entretiempo', 'todo_año'])) {
    $where_conditions[] = "p.season = ?";
    $params[] = $season;
}

if ($formality && in_array($formality, ['formal', 'casual', 'deportivo', 'trabajo'])) {
    $where_conditions[] = "p.formality = ?";
    $params[] = $formality;
}

if ($factory_id > 0) {
    $where_conditions[] = "p.factory_id = ?";
    $params[] = $factory_id;
}

if ($show_prices && $min_price > 0) {
    $where_conditions[] = "p.wholesale_price >= ?";
    $params[] = $min_price;
}

if ($show_prices && $max_price > 0) {
    $where_conditions[] = "p.wholesale_price <= ?";
    $params[] = $max_price;
}

if ($task_type && in_array($task_type, ['full', 'half'])) {
    $where_conditions[] = "p.task_type = ?";
    $params[] = $task_type;
}

// Orden
$order_by = "p.created_at DESC";
switch ($sort_by) {
    case 'price_asc':
        $order_by = $show_prices ? "p.wholesale_price ASC" : "p.created_at DESC";
        break;
    case 'price_desc':
        $order_by = $show_prices ? "p.wholesale_price DESC" : "p.created_at DESC";
        break;
    case 'name':
        $order_by = "p.name ASC";
        break;
    case 'newest':
    default:
        $order_by = "p.created_at DESC";
        break;
}

$where_clause = implode(' AND ', $where_conditions);

try {
    // Contar total de productos
    $count_sql = "
        SELECT COUNT(*) as total
        FROM products p
        LEFT JOIN factories f ON p.factory_id = f.id
        WHERE $where_clause
    ";
    $stmt = $pdo->prepare($count_sql);
    $stmt->execute($params);
    $total_products = $stmt->fetch()['total'];
    $total_pages = ceil($total_products / $per_page);

    // Obtener productos con paginación
    $sql = "
        SELECT 
            p.*,
            f.name as factory_name,
            f.specialties as factory_specialties,
            (SELECT pi.image_url FROM product_images pi 
             WHERE pi.product_id = p.id AND pi.image_type = 'main' 
             LIMIT 1) as main_image,
            (SELECT COUNT(*) FROM product_colors pc 
             WHERE pc.product_id = p.id) as color_count,
            (SELECT GROUP_CONCAT(pc.color_name SEPARATOR ', ') 
             FROM product_colors pc 
             WHERE pc.product_id = p.id 
             LIMIT 3) as available_colors
        FROM products p
        LEFT JOIN factories f ON p.factory_id = f.id
        WHERE $where_clause
        ORDER BY $order_by
        LIMIT $per_page OFFSET $offset
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Obtener fábricas para filtro
    $factories_stmt = $pdo->query("
        SELECT id, name, COUNT(p.id) as product_count
        FROM factories f
        LEFT JOIN products p ON f.id = p.factory_id AND p.is_active = TRUE
        WHERE f.is_active = TRUE
        GROUP BY f.id, f.name
        HAVING product_count > 0
        ORDER BY f.name
    ");
    $factories = $factories_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Obtener rangos de precios si es usuario aprobado
    $price_range = null;
    if ($show_prices) {
        $price_stmt = $pdo->query("
            SELECT MIN(wholesale_price) as min_price, MAX(wholesale_price) as max_price
            FROM products 
            WHERE is_active = TRUE
        ");
        $price_range = $price_stmt->fetch(PDO::FETCH_ASSOC);
    }

} catch (PDOException $e) {
    error_log("Catalog error: " . $e->getMessage());
    $products = [];
    $factories = [];
    $total_products = 0;
    $total_pages = 0;
}

// Función para generar URL con filtros
function buildFilterUrl($new_params = []) {
    $current_params = $_GET;
    $merged_params = array_merge($current_params, $new_params);
    
    // Remover parámetros vacíos
    $merged_params = array_filter($merged_params, function($value) {
        return $value !== '' && $value !== null;
    });
    
    return 'catalog.php' . (!empty($merged_params) ? '?' . http_build_query($merged_params) : '');
}

require_once 'includes/header.php';
?>

<main class="catalog-main">
    <!-- Banner de estado para usuarios -->
    <?php if ($is_public_view): ?>
        <div class="access-banner">
            <div class="container">
                <?php if (!isLoggedIn()): ?>
                    <div class="banner-content">
                        <h2>👁️ Vista Pública - Precios solo para mayoristas</h2>
                        <p>Regístrese para acceder a precios mayoristas y funciones exclusivas</p>
                        <div class="banner-actions">
                            <a href="register.php" class="btn btn-primary">Registrarse</a>
                            <a href="login.php" class="btn btn-secondary">Ya tengo cuenta</a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="banner-content pending">
                        <h2>⏳ Cuenta pendiente de aprobación</h2>
                        <p>Para ver precios mayoristas, su cuenta debe ser aprobada por nuestro equipo</p>
                        <a href="pending-approval.php" class="btn btn-primary">Ver estado</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

    <div class="container">
        <div class="catalog-header">
            <h1><?php echo $is_public_view ? '👁️ Catálogo Público' : '🛍️ Catálogo Mayorista'; ?></h1>
            <p>
                <?php echo $total_products; ?> producto(s) disponible(s)
                <?php if ($show_prices): ?>
                    - <strong>Precios mayoristas</strong>
                <?php endif; ?>
            </p>
        </div>

        <div class="catalog-layout">
            <!-- Sidebar de filtros -->
            <aside class="filters-sidebar">
                <div class="filters-header">
                    <h3>🔍 Filtros</h3>
                    <?php if (array_filter($_GET)): ?>
                        <a href="catalog.php" class="clear-filters">Limpiar filtros</a>
                    <?php endif; ?>
                </div>

                <form method="GET" action="catalog.php" class="filters-form">
                    <!-- Búsqueda -->
                    <div class="filter-group">
                        <label for="search">Buscar</label>
                        <input type="text" id="search" name="search" 
                               value="<?php echo htmlspecialchars($search); ?>"
                               placeholder="Nombre, SKU, fábrica...">
                    </div>

                    <!-- Género -->
                    <div class="filter-group">
                        <label>Género</label>
                        <div class="filter-options">
                            <label class="filter-option">
                                <input type="radio" name="gender" value="" <?php echo $gender === '' ? 'checked' : ''; ?>>
                                <span>Todos</span>
                            </label>
                            <label class="filter-option">
                                <input type="radio" name="gender" value="hombre" <?php echo $gender === 'hombre' ? 'checked' : ''; ?>>
                                <span>Hombre</span>
                            </label>
                            <label class="filter-option">
                                <input type="radio" name="gender" value="mujer" <?php echo $gender === 'mujer' ? 'checked' : ''; ?>>
                                <span>Mujer</span>
                            </label>
                            <label class="filter-option">
                                <input type="radio" name="gender" value="unisex" <?php echo $gender === 'unisex' ? 'checked' : ''; ?>>
                                <span>Unisex</span>
                            </label>
                            <label class="filter-option">
                                <input type="radio" name="gender" value="niño" <?php echo $gender === 'niño' ? 'checked' : ''; ?>>
                                <span>Niño</span>
                            </label>
                            <label class="filter-option">
                                <input type="radio" name="gender" value="niña" <?php echo $gender === 'niña' ? 'checked' : ''; ?>>
                                <span>Niña</span>
                            </label>
                        </div>
                    </div>

                    <!-- Temporada -->
                    <div class="filter-group">
                        <label>Temporada</label>
                        <select name="season">
                            <option value="">Todas</option>
                            <option value="verano" <?php echo $season === 'verano' ? 'selected' : ''; ?>>Verano</option>
                            <option value="invierno" <?php echo $season === 'invierno' ? 'selected' : ''; ?>>Invierno</option>
                            <option value="entretiempo" <?php echo $season === 'entretiempo' ? 'selected' : ''; ?>>Entretiempo</option>
                            <option value="todo_año" <?php echo $season === 'todo_año' ? 'selected' : ''; ?>>Todo el año</option>
                        </select>
                    </div>

                    <!-- Formalidad -->
                    <div class="filter-group">
                        <label>Estilo</label>
                        <select name="formality">
                            <option value="">Todos</option>
                            <option value="formal" <?php echo $formality === 'formal' ? 'selected' : ''; ?>>Formal</option>
                            <option value="casual" <?php echo $formality === 'casual' ? 'selected' : ''; ?>>Casual</option>
                            <option value="deportivo" <?php echo $formality === 'deportivo' ? 'selected' : ''; ?>>Deportivo</option>
                            <option value="trabajo" <?php echo $formality === 'trabajo' ? 'selected' : ''; ?>>Trabajo</option>
                        </select>
                    </div>

                    <!-- Fábrica -->
                    <?php if (!empty($factories)): ?>
                    <div class="filter-group">
                        <label>Fábrica</label>
                        <select name="factory">
                            <option value="">Todas las fábricas</option>
                            <?php foreach ($factories as $factory): ?>
                                <option value="<?php echo $factory['id']; ?>" 
                                        <?php echo $factory_id === (int)$factory['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($factory['name']); ?> 
                                    (<?php echo $factory['product_count']; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>

                    <!-- Tipo de tarea -->
                    <div class="filter-group">
                        <label>Tipo de tarea</label>
                        <select name="task_type">
                            <option value="">Todas</option>
                            <option value="full" <?php echo $task_type === 'full' ? 'selected' : ''; ?>>Completa (12 pares)</option>
                            <option value="half" <?php echo $task_type === 'half' ? 'selected' : ''; ?>>Media (6 pares)</option>
                        </select>
                    </div>

                    <!-- Rango de precios (solo para usuarios aprobados) -->
                    <?php if ($show_prices && $price_range): ?>
                    <div class="filter-group">
                        <label>Precio mayorista</label>
                        <div class="price-inputs">
                            <input type="number" name="min_price" 
                                   value="<?php echo $min_price > 0 ? $min_price : ''; ?>"
                                   placeholder="Mín: $<?php echo number_format($price_range['min_price'], 0, ',', '.'); ?>"
                                   min="0" step="1000">
                            <input type="number" name="max_price" 
                                   value="<?php echo $max_price > 0 ? $max_price : ''; ?>"
                                   placeholder="Máx: $<?php echo number_format($price_range['max_price'], 0, ',', '.'); ?>"
                                   min="0" step="1000">
                        </div>
                    </div>
                    <?php endif; ?>

                    <button type="submit" class="btn btn-primary filter-submit">
                        Aplicar filtros
                    </button>
                </form>
            </aside>

            <!-- Contenido principal -->
            <div class="catalog-content">
                <!-- Barra de herramientas -->
                <div class="toolbar">
                    <div class="toolbar-left">
                        <span class="results-count">
                            <?php echo $total_products; ?> producto(s)
                            <?php if ($page > 1): ?>
                                - Página <?php echo $page; ?> de <?php echo $total_pages; ?>
                            <?php endif; ?>
                        </span>
                    </div>
                    
                    <div class="toolbar-right">
                        <label for="sort">Ordenar por:</label>
                        <select name="sort" id="sort" onchange="updateSort(this.value)">
                            <option value="newest" <?php echo $sort_by === 'newest' ? 'selected' : ''; ?>>Más recientes</option>
                            <option value="name" <?php echo $sort_by === 'name' ? 'selected' : ''; ?>>Nombre A-Z</option>
                            <?php if ($show_prices): ?>
                                <option value="price_asc" <?php echo $sort_by === 'price_asc' ? 'selected' : ''; ?>>Precio menor</option>
                                <option value="price_desc" <?php echo $sort_by === 'price_desc' ? 'selected' : ''; ?>>Precio mayor</option>
                            <?php endif; ?>
                        </select>
                    </div>
                </div>

                <!-- Grid de productos -->
                <?php if (empty($products)): ?>
                    <div class="no-products">
                        <div class="no-products-icon">🔍</div>
                        <h3>No se encontraron productos</h3>
                        <p>Intente ajustar los filtros o realizar una búsqueda diferente</p>
                        <a href="catalog.php" class="btn btn-secondary">Ver todos los productos</a>
                    </div>
                <?php else: ?>
                    <div class="products-grid">
                        <?php foreach ($products as $product): ?>
                            <div class="product-card" data-product-id="<?php echo $product['id']; ?>">
                                <div class="product-image">
                                    <?php if ($product['main_image']): ?>
                                        <img src="<?php echo htmlspecialchars($product['main_image']); ?>" 
                                             alt="<?php echo htmlspecialchars($product['name']); ?>"
                                             loading="lazy">
                                    <?php else: ?>
                                        <div class="no-image">
                                            <span>📷</span>
                                            <p>Sin imagen</p>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <!-- Badges -->
                                    <div class="product-badges">
                                        <span class="badge badge-<?php echo $product['gender']; ?>">
                                            <?php echo ucfirst($product['gender']); ?>
                                        </span>
                                        <?php if ($product['task_type'] === 'half'): ?>
                                            <span class="badge badge-half">Media tarea</span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Colores disponibles -->
                                    <?php if ($product['color_count'] > 1): ?>
                                        <div class="color-indicator">
                                            +<?php echo $product['color_count']; ?> colores
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="product-info">
                                    <h3 class="product-name">
                                        <?php echo htmlspecialchars($product['name']); ?>
                                    </h3>
                                    
                                    <p class="product-sku">
                                        SKU: <?php echo htmlspecialchars($product['sku']); ?>
                                    </p>
                                    
                                    <p class="product-factory">
                                        🏭 <?php echo htmlspecialchars($product['factory_name']); ?>
                                    </p>
                                    
                                    <div class="product-details">
                                        <span class="detail-item">
                                            <?php echo ucfirst($product['season']); ?>
                                        </span>
                                        <span class="detail-item">
                                            <?php echo ucfirst($product['formality']); ?>
                                        </span>
                                        <span class="detail-item">
                                            <?php echo $product['task_type'] === 'full' ? '12 pares' : '6 pares'; ?>
                                        </span>
                                    </div>
                                    
                                    <?php if ($product['available_colors']): ?>
                                        <p class="product-colors">
                                            Colores: <?php echo htmlspecialchars($product['available_colors']); ?>
                                        </p>
                                    <?php endif; ?>
                                    
                                    <div class="product-pricing">
                                        <?php if ($show_prices): ?>
                                            <div class="price-wholesale">
                                                <strong><?php echo formatPrice($product['wholesale_price']); ?></strong>
                                                <span>Precio mayorista</span>
                                            </div>
                                            <?php if ($product['suggested_retail_price']): ?>
                                                <div class="price-suggested">
                                                    Sugerido: <?php echo formatPrice($product['suggested_retail_price']); ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <div class="price-hidden">
                                                <span class="price-placeholder">$$</span>
                                                <span>Precio para mayoristas</span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="product-actions">
                                        <button class="btn btn-primary product-details-btn" 
                                                onclick="viewProduct(<?php echo $product['id']; ?>)">
                                            Ver detalles
                                        </button>
                                        
                                        <?php if ($show_prices): ?>
                                            <button class="btn btn-secondary add-to-cart-btn" 
                                                    onclick="addToCart(<?php echo $product['id']; ?>)">
                                                + Carrito
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Paginación -->
                    <?php if ($total_pages > 1): ?>
                        <div class="pagination">
                            <?php if ($page > 1): ?>
                                <a href="<?php echo buildFilterUrl(['page' => $page - 1]); ?>" class="page-btn prev">
                                    ← Anterior
                                </a>
                            <?php endif; ?>
                            
                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            if ($start_page > 1): ?>
                                <a href="<?php echo buildFilterUrl(['page' => 1]); ?>" class="page-btn">1</a>
                                <?php if ($start_page > 2): ?>
                                    <span class="page-ellipsis">...</span>
                                <?php endif; ?>
                            <?php endif;
                            
                            for ($i = $start_page; $i <= $end_page; $i++): ?>
                                <a href="<?php echo buildFilterUrl(['page' => $i]); ?>" 
                                   class="page-btn <?php echo $i === $page ? 'active' : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                            <?php endfor;
                            
                            if ($end_page < $total_pages): ?>
                                <?php if ($end_page < $total_pages - 1): ?>
                                    <span class="page-ellipsis">...</span>
                                <?php endif; ?>
                                <a href="<?php echo buildFilterUrl(['page' => $total_pages]); ?>" class="page-btn"><?php echo $total_pages; ?></a>
                            <?php endif; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <a href="<?php echo buildFilterUrl(['page' => $page + 1]); ?>" class="page-btn next">
                                    Siguiente →
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<!-- Modal de detalles del producto -->
<div id="productModal" class="modal" style="display: none;">
    <div class="modal-overlay" onclick="closeProductModal()"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalProductName">Cargando...</h2>
            <button class="modal-close" onclick="closeProductModal()">×</button>
        </div>
        <div class="modal-body" id="modalProductContent">
            <div class="loading">Cargando detalles del producto...</div>
        </div>
    </div>
</div>

<script>
// Pasar información de PHP a JavaScript
window.userIsApproved = <?php echo $show_prices ? 'true' : 'false'; ?>;

// Función para cambiar orden
function updateSort(sortValue) {
    const url = new URL(window.location);
    url.searchParams.set('sort', sortValue);
    url.searchParams.delete('page'); // Reset a página 1
    window.location = url.toString();
}

// Funciones para interacción con productos
function viewProduct(productId) {
    openProductModal(productId);
}

function addToCart(productId) {
    if (!window.userIsApproved) {
        alert('Debe ser un usuario aprobado para agregar productos al carrito');
        return;
    }
    
    // Implementar lógica de carrito
    console.log('Agregar producto al carrito:', productId);
    showToast('Producto agregado al carrito', 'success');
}

// Auto-submit de filtros con debounce
let filterTimeout;
document.getElementById('search').addEventListener('input', function() {
    clearTimeout(filterTimeout);
    filterTimeout = setTimeout(() => {
        this.form.submit();
    }, 500);
});

// Funciones auxiliares
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: ${type === 'success' ? '#27ae60' : '#3498db'};
        color: white;
        padding: 1rem;
        border-radius: 6px;
        z-index: 10000;
        opacity: 0;
        transition: opacity 0.3s ease;
    `;
    
    document.body.appendChild(toast);
    setTimeout(() => toast.style.opacity = '1', 100);
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Función para modal de productos (placeholder)
function openProductModal(productId) {
    const modal = document.getElementById('productModal');
    modal.style.display = 'flex';
    
    // Aquí iría la lógica para cargar datos del producto via AJAX
    console.log('Abrir modal para producto:', productId);
}

function closeProductModal() {
    document.getElementById('productModal').style.display = 'none';
}
</script>

<style>
/* Estilos específicos del catálogo */
.access-banner {
    background: linear-gradient(135deg, #f39c12, #e67e22);
    color: white;
    padding: 1.5rem 0;
    margin-bottom: 2rem;
}

.banner-content {
    text-align: center;
}

.banner-content.pending {
    background: linear-gradient(135deg, #f39c12, #d35400);
}

.banner-actions {
    margin-top: 1rem;
    display: flex;
    gap: 1rem;
    justify-content: center;
    flex-wrap: wrap;
}

.catalog-header {
    text-align: center;
    margin-bottom: 2rem;
}

.catalog-layout {
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 2rem;
}

.filters-sidebar {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    padding: 1.5rem;
    height: fit-content;
    position: sticky;
    top: 2rem;
}

.filters-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #ecf0f1;
}

.clear-filters {
    color: #e74c3c;
    text-decoration: none;
    font-size: 0.9rem;
}

.filter-group {
    margin-bottom: 1.5rem;
}

.filter-group label {
    display: block;
    font-weight: 600;
    margin-bottom: 0.5rem;
    color: #2c3e50;
}

.filter-group input,
.filter-group select {
    width: 100%;
    padding: 0.5rem;
    border: 2px solid #ecf0f1;
    border-radius: 6px;
    font-size: 0.9rem;
}

.filter-options {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.filter-option {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

.filter-option input[type="radio"] {
    width: auto;
}

.price-inputs {
    display: flex;
    gap: 0.5rem;
}

.price-inputs input {
    flex: 1;
}

.filter-submit {
    width: 100%;
    margin-top: 1rem;
}

.catalog-content {
    min-height: 500px;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
    padding: 1rem;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 2rem;
    margin-bottom: 3rem;
}

.product-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.product-image {
    position: relative;
    height: 220px;
    overflow: hidden;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.no-image {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: #f1f3f4;
    color: #95a5a6;
}

.no-image span {
    font-size: 3rem;
    margin-bottom: 0.5rem;
}

.product-badges {
    position: absolute;
    top: 0.5rem;
    left: 0.5rem;
    display: flex;
    gap: 0.25rem;
}

.badge {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.75rem;
    font-weight: 600;
    color: white;
}

.badge-hombre { background: #3498db; }
.badge-mujer { background: #e91e63; }
.badge-unisex { background: #9c27b0; }
.badge-niño { background: #4caf50; }
.badge-niña { background: #ff5722; }
.badge-half { background: #f39c12; }

.color-indicator {
    position: absolute;
    bottom: 0.5rem;
    right: 0.5rem;
    background: rgba(0,0,0,0.7);
    color: white;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.75rem;
}

.product-info {
    padding: 1.5rem;
}

.product-name {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    color: #2c3e50;
}

.product-sku,
.product-factory {
    color: #7f8c8d;
    font-size: 0.9rem;
    margin-bottom: 0.5rem;
}

.product-details {
    display: flex;
    gap: 0.5rem;
    margin: 1rem 0;
    flex-wrap: wrap;
}

.detail-item {
    background: #ecf0f1;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    color: #2c3e50;
}

.product-colors {
    font-size: 0.9rem;
    color: #7f8c8d;
    margin-bottom: 1rem;
}

.product-pricing {
    margin: 1rem 0;
}

.price-wholesale {
    display: flex;
    flex-direction: column;
}

.price-wholesale strong {
    font-size: 1.3rem;
    color: #27ae60;
}

.price-wholesale span {
    font-size: 0.8rem;
    color: #7f8c8d;
}

.price-suggested {
    font-size: 0.9rem;
    color: #95a5a6;
    margin-top: 0.25rem;
}

.price-hidden {
    text-align: center;
    padding: 1rem 0;
}

.price-placeholder {
    font-size: 1.5rem;
    color: #bdc3c7;
    font-weight: 600;
    display: block;
}

.product-actions {
    display: flex;
    gap: 0.5rem;
}

.product-actions .btn {
    flex: 1;
    padding: 0.75rem;
    font-size: 0.9rem;
}

.no-products {
    text-align: center;
    padding: 4rem 2rem;
    color: #7f8c8d;
}

.no-products-icon {
    font-size: 4rem;
    margin-bottom: 1rem;
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 0.5rem;
    margin-top: 2rem;
}

.page-btn {
    padding: 0.5rem 1rem;
    border: 2px solid #ecf0f1;
    border-radius: 6px;
    text-decoration: none;
    color: #2c3e50;
    transition: all 0.3s ease;
}

.page-btn:hover,
.page-btn.active {
    background: #3498db;
    color: white;
    border-color: #3498db;
}

.page-ellipsis {
    color: #95a5a6;
    padding: 0.5rem;
}

/* Modal */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.modal-content {
    background: white;
    border-radius: 12px;
    max-width: 800px;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
    z-index: 1;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.5rem;
    border-bottom: 1px solid #ecf0f1;
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: #95a5a6;
}

.modal-body {
    padding: 1.5rem;
}

.loading {
    text-align: center;
    padding: 2rem;
    color: #7f8c8d;
}

/* Responsive */
@media (max-width: 768px) {
    .catalog-layout {
        grid-template-columns: 1fr;
    }
    
    .filters-sidebar {
        position: static;
        margin-bottom: 2rem;
    }
    
    .toolbar {
        flex-direction: column;
        gap: 1rem;
        align-items: stretch;
    }
    
    .products-grid {
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 1rem;
    }
    
    .hero-actions {
        flex-direction: column;
    }
    
    .banner-actions {
        flex-direction: column;
    }
    
    .process-steps {
        flex-direction: column;
    }
}
</style>

<?php require_once 'includes/footer.php'; ?>