<?php $__env->startSection('title', 'Productos | Veltrix v2'); ?>
<?php $__env->startSection('page_title', 'Productos'); ?>
<?php $__env->startSection('page_subtitle', 'Gestion operativa en tiempo real'); ?>
<?php $__env->startSection('page_icon', 'bx bxs-box'); ?>

<?php $__env->startSection('content'); ?>
    <?php
        $variantCounts = is_array($productVariantCounts ?? null) ? $productVariantCounts : [];
        $suppliers = $proveedores instanceof \Illuminate\Support\Collection ? $proveedores : collect($proveedores ?? []);
        $units = $unidades instanceof \Illuminate\Support\Collection ? $unidades : collect($unidades ?? []);
        $taxes = $impuestos instanceof \Illuminate\Support\Collection ? $impuestos : collect($impuestos ?? []);
        $taxesById = $taxes->keyBy('id');
        $defaultProductImageUrl = product_image_url('');
        $defaultCreateTaxId = (int) ($taxes->first()->id ?? 0);
        $createTaxId = (int) old('impuesto_id', (string) $defaultCreateTaxId);
        $createTaxRate = (float) old('impuesto_porcentaje', (string) ((float) ($taxesById->get($createTaxId)?->porcentaje ?? 0)));
        $createHasCustomTax = $createTaxId <= 0 && $createTaxRate > 0;
        $createCustomTaxLabel = 'Manual ('.number_format($createTaxRate, 2).'%)';
        $createVariantsEnabled = (string) old('variantes_habilitadas', '0') === '1';
        $createVariantsMode = strtolower((string) old('variantes_modo', 'same'));
        if (! in_array($createVariantsMode, ['same', 'individual'], true)) {
            $createVariantsMode = 'same';
        }
        $createVariantNames = (array) old('variante_nombre', []);
        $createVariantPrices = (array) old('variante_precio', []);
        $createVariantQuantities = (array) old('variante_cantidad', []);
        $createVariantMinStocks = (array) old('variante_stock_minimo', []);
        $createAttributeNames = (array) old('atributo_nombre', ['Talla', 'Color']);
        $createAttributeValues = (array) old('atributo_valores', ['', '']);
        $selectedSucursalId = (int) old('sucursal_id', (int) ($tenantSucursalId ?? 0));

        $shouldOpenCreateModal = has_permission('productos.crear')
            && $errors->any()
            && (
                old('_product_form') === 'create'
                || old('nombre') !== null
                || old('sku') !== null
                || old('precio_venta') !== null
            );
        $shouldOpenImportModal = (bool) session('open_import_modal')
            || ($errors->any() && old('_product_form') === 'import');
    ?>

    <div class="container-fluid px-4 py-4">
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($errors->any()): ?>
            <div class="alert alert-danger mb-3">
                <?php echo e($errors->first()); ?>

            </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                    <h1 class="h4 mb-0">Productos</h1>
                    <div class="d-flex gap-2 flex-wrap">
                        <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="modal" data-bs-target="#importProductsModal">
                            <i class="bx bx-upload me-1"></i> Importar CSV
                        </button>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(has_permission('productos.crear')): ?>
                            <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#createProductModal">
                                <i class="bx bx-plus me-1"></i> Nuevo producto
                            </button>
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Foto</th>
                                <th>Nombre</th>
                                <th>Proveedor</th>
                                <th>SKU</th>
                                <th>Unidad</th>
                                <th>Precio</th>
                                <th>Stock</th>
                                <th>Minimo</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $productos; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $producto): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                <?php
                                    $variantCount = (int) ($variantCounts[$producto->id] ?? 0);
                                    $isVariable = $variantCount > 0;
                                    $supplierName = trim((string) ($producto->proveedor?->nombre ?? ''));
                                    if ($supplierName === '') {
                                        $supplierName = 'Sin proveedor';
                                    }
                                    $unitLabel = trim((string) ($producto->unidadMedida?->abreviatura ?? ''));
                                    if ($unitLabel === '') {
                                        $unitLabel = trim((string) ($producto->unidadMedida?->nombre ?? ''));
                                    }
                                    if ($unitLabel === '') {
                                        $unitLabel = '-';
                                    }
                                    $skuValue = trim((string) ($producto->sku ?? ''));
                                    if ($skuValue === '') {
                                        $skuValue = '-';
                                    }
                                ?>
                                <tr>
                                    <td><?php echo e($producto->id); ?></td>
                                    <td>
                                        <img
                                            src="<?php echo e(product_image_url((string) ($producto->imagen ?? ''))); ?>"
                                            alt="<?php echo e((string) ($producto->nombre ?? 'Producto')); ?>"
                                            class="rounded border"
                                            style="width: 44px; height: 44px; object-fit: cover;"
                                        >
                                    </td>
                                    <td>
                                        <div class="d-flex flex-column gap-1">
                                            <span><?php echo e($producto->nombre); ?></span>
                                            <span class="vx-product-type-chip <?php echo e($isVariable ? 'is-variable' : 'is-simple'); ?>">
                                                <span class="vx-product-type-icon" aria-hidden="true">
                                                    <i class="bx <?php echo e($isVariable ? 'bx-slider-alt' : 'bx-box'); ?>"></i>
                                                </span>
                                                <span class="vx-product-type-label"><?php echo e($isVariable ? 'Variable' : 'Simple'); ?></span>
                                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($isVariable): ?>
                                                    <span class="vx-product-type-meta"><?php echo e($variantCount); ?> vars</span>
                                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td><?php echo e($supplierName); ?></td>
                                    <td><span class="badge text-bg-light border"><?php echo e($skuValue); ?></span></td>
                                    <td><span class="badge text-bg-light border"><?php echo e($unitLabel); ?></span></td>
                                    <td><?php echo e(money((float) ($producto->precio_venta ?? 0))); ?></td>
                                    <td><?php echo e(number_format((float) ($producto->stock_actual ?? 0), 2)); ?></td>
                                    <td><?php echo e(number_format((float) ($producto->stock_minimo ?? 0), 2)); ?></td>
                                    <td>
                                        <a href="<?php echo e(route('productos.edit', $producto)); ?>" class="btn btn-sm btn-outline-primary">Editar</a>
                                    </td>
                                </tr>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted py-3">No hay productos registrados.</td>
                                </tr>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($productos->hasPages()): ?>
            <div class="mt-3">
                <?php echo e($productos->links()); ?>

            </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
    </div>

    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(has_permission('productos.crear')): ?>
        <div class="modal fade" id="createProductModal" tabindex="-1" aria-labelledby="createProductModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content border-0 shadow">
                    <div class="modal-header">
                        <h2 class="h6 mb-0" id="createProductModalLabel">Nuevo producto</h2>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                    </div>
                    <form action="<?php echo e(route('productos.store')); ?>" method="post" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="_product_form" value="create">
                        <input type="hidden" name="activo" value="1">
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($selectedSucursalId > 0): ?>
                            <input type="hidden" name="sucursal_id" value="<?php echo e($selectedSucursalId); ?>">
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                        <div class="modal-body">
                            <div class="row g-2">
                                <div class="col-12">
                                    <label class="form-label">Nombre</label>
                                    <input class="form-control" name="nombre" value="<?php echo e((string) old('nombre', '')); ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Categoría</label>
                                    <select class="form-select" name="categoria_id" required>
                                        <option value="">Seleccione...</option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $categorias; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $categoria): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                            <option value="<?php echo e($categoria->id); ?>" <?php if((int) old('categoria_id', 0) === (int) $categoria->id): echo 'selected'; endif; ?>>
                                                <?php echo e($categoria->nombre); ?>

                                            </option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Proveedor</label>
                                    <select class="form-select" name="proveedor_id" required>
                                        <option value="">Seleccione...</option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                            <option value="<?php echo e($supplier->id); ?>" <?php if((int) old('proveedor_id', 0) === (int) $supplier->id): echo 'selected'; endif; ?>>
                                                <?php echo e((string) ($supplier->nombre ?? '')); ?>

                                            </option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Unidad de medida</label>
                                    <select class="form-select" name="unidad_medida_id" required>
                                        <option value="">Seleccione...</option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $units; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $unit): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                            <option value="<?php echo e($unit->id); ?>" <?php if((int) old('unidad_medida_id', 0) === (int) $unit->id): echo 'selected'; endif; ?>>
                                                <?php echo e((string) ($unit->nombre ?? '')); ?><?php echo e(!empty($unit->abreviatura) ? ' ('.$unit->abreviatura.')' : ''); ?>

                                            </option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Impuesto</label>
                                    <select class="form-select product-tax-select" name="impuesto_id" data-tax-hidden="#createProductTaxRate">
                                        <option value="0" data-rate="<?php echo e($createHasCustomTax ? (string) $createTaxRate : '0'); ?>" <?php if($createTaxId <= 0): echo 'selected'; endif; ?>>
                                            <?php echo e($createHasCustomTax ? $createCustomTaxLabel : 'Sin impuesto'); ?>

                                        </option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $taxes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tax): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                            <?php
                                                $taxId = (int) ($tax->id ?? 0);
                                                $taxRate = (float) ($tax->porcentaje ?? 0);
                                                $taxName = trim((string) ($tax->nombre ?? 'Impuesto'));
                                                $taxOptionLabel = $taxName.' ('.number_format($taxRate, 2).'%)';
                                            ?>
                                            <option value="<?php echo e($taxId); ?>" data-rate="<?php echo e($taxRate); ?>" <?php if($createTaxId === $taxId): echo 'selected'; endif; ?>>
                                                <?php echo e($taxOptionLabel); ?>

                                            </option>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                    </select>
                                    <input type="hidden" name="impuesto_porcentaje" id="createProductTaxRate" value="<?php echo e((string) $createTaxRate); ?>">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">SKU / Código interno</label>
                                    <input class="form-control" name="sku" value="<?php echo e((string) old('sku', '')); ?>" maxlength="80" placeholder="Ej: SKU-001">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Precio compra</label>
                                    <input type="number" step="0.01" class="form-control" name="precio_compra" value="<?php echo e((string) old('precio_compra', '0')); ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Precio venta</label>
                                    <input type="number" step="0.01" class="form-control" name="precio_venta" value="<?php echo e((string) old('precio_venta', '0')); ?>" required>
                                </div>
                                <div class="col-md-6 product-global-stock-field <?php echo e($createVariantsEnabled ? 'd-none' : ''); ?>">
                                    <label class="form-label">Stock inicial</label>
                                    <input type="number" step="0.01" class="form-control" name="stock_actual" value="<?php echo e((string) old('stock_actual', '0')); ?>" <?php echo e($createVariantsEnabled ? 'disabled' : ''); ?>>
                                </div>
                                <div class="col-md-6 product-global-stock-field <?php echo e($createVariantsEnabled ? 'd-none' : ''); ?>">
                                    <label class="form-label">Stock mínimo</label>
                                    <input type="number" step="0.01" class="form-control" name="stock_minimo" value="<?php echo e((string) old('stock_minimo', '0')); ?>" <?php echo e($createVariantsEnabled ? 'disabled' : ''); ?>>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Código de barras</label>
                                    <input class="form-control" name="codigo_barras" value="<?php echo e((string) old('codigo_barras', '')); ?>">
                                </div>

                                <div class="col-12">
                                    <div class="border rounded-3 p-3 bg-light-subtle">
                                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
                                            <label class="form-label mb-0 fw-semibold">Variantes del producto</label>
                                            <div class="form-check form-switch m-0">
                                                <input type="hidden" name="variantes_habilitadas" value="0">
                                                <input
                                                    class="form-check-input product-variants-toggle"
                                                    type="checkbox"
                                                    id="createVariantsToggle"
                                                    name="variantes_habilitadas"
                                                    value="1"
                                                    data-target="#createVariantsBox"
                                                    <?php echo e($createVariantsEnabled ? 'checked' : ''); ?>

                                                >
                                                <label class="form-check-label" for="createVariantsToggle">Activar</label>
                                            </div>
                                        </div>
                                        <div id="createVariantsBox" class="product-variants-box <?php echo e($createVariantsEnabled ? '' : 'd-none'); ?>">
                                            <ul class="nav nav-tabs product-variant-tabs mb-2" role="tablist">
                                                <li class="nav-item" role="presentation">
                                                    <button
                                                        class="nav-link active"
                                                        type="button"
                                                        data-bs-toggle="tab"
                                                        data-bs-target="#createProductAttributesTab"
                                                        role="tab"
                                                        aria-selected="true"
                                                    >
                                                        Atributos
                                                    </button>
                                                </li>
                                                <li class="nav-item" role="presentation">
                                                    <button
                                                        class="nav-link product-variants-tab-button"
                                                        type="button"
                                                        data-bs-toggle="tab"
                                                        data-bs-target="#createProductVariationsTab"
                                                        role="tab"
                                                        aria-selected="false"
                                                    >
                                                        Variaciones
                                                    </button>
                                                </li>
                                            </ul>
                                            <div class="tab-content">
                                                <div class="tab-pane fade show active product-variant-pane" id="createProductAttributesTab" role="tabpanel">
                                                    <div class="border rounded-3 p-2 mb-2 bg-white product-variant-builder">
                                                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
                                                            <label class="form-label mb-0 fw-semibold">Define primero tus atributos</label>
                                                            <button class="btn btn-sm btn-outline-secondary product-attribute-add-row" type="button">
                                                                <i class="bx bx-plus me-1"></i>Agregar atributo
                                                            </button>
                                                        </div>
                                                        <div class="product-variant-attributes">
                                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $createAttributeNames; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attributeIndex => $attributeName): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                                                <?php $attributeValues = (string) ($createAttributeValues[$attributeIndex] ?? ''); ?>
                                                                <div class="row g-2 mb-2 product-attribute-row">
                                                                    <div class="col-md-4">
                                                                        <input
                                                                            class="form-control form-control-sm product-attribute-name"
                                                                            name="atributo_nombre[]"
                                                                            value="<?php echo e((string) $attributeName); ?>"
                                                                            placeholder="Ej: Talla"
                                                                        >
                                                                    </div>
                                                                    <div class="col-md-7">
                                                                        <input
                                                                            class="form-control form-control-sm product-attribute-values"
                                                                            name="atributo_valores[]"
                                                                            value="<?php echo e($attributeValues); ?>"
                                                                            placeholder="Ej: S, M, L"
                                                                        >
                                                                    </div>
                                                                    <div class="col-md-1 d-grid">
                                                                        <button class="btn btn-sm btn-outline-danger product-attribute-remove-row" type="button">
                                                                            <i class="bx bx-x"></i>
                                                                        </button>
                                                                    </div>
                                                                </div>
                                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                                        </div>
                                                        <small class="text-muted d-block mt-2">
                                                            Primero crea atributos y valores. Luego, en la pestaña Variaciones, los mezclas con selects.
                                                        </small>
                                                    </div>
                                                </div>
                                                <div class="tab-pane fade product-variant-pane" id="createProductVariationsTab" role="tabpanel">
                                                    <div class="product-variant-toolbar mb-2">
                                                        <div class="product-variant-toolbar-item product-variant-toolbar-mode">
                                                            <label class="form-label">Precio de variaciones</label>
                                                            <select class="form-select product-variants-mode" name="variantes_modo">
                                                                <option value="same" <?php echo e($createVariantsMode === 'same' ? 'selected' : ''); ?>>Mismo precio para todas</option>
                                                                <option value="individual" <?php echo e($createVariantsMode === 'individual' ? 'selected' : ''); ?>>Precio individual por variación</option>
                                                            </select>
                                                        </div>
                                                        <div class="product-variant-toolbar-item product-variant-toolbar-action">
                                                            <button class="btn btn-outline-primary product-variant-action-btn product-variant-generate-combos" type="button">
                                                                <i class="bx bx-grid-alt me-1"></i>Generar variaciones
                                                            </button>
                                                        </div>
                                                        <div class="product-variant-toolbar-item product-variant-toolbar-action">
                                                            <button class="btn btn-outline-primary product-variant-action-btn product-variant-add-row" type="button">
                                                                <i class="bx bx-plus me-1"></i>Añadir manualmente
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="product-variant-toolbar-meta mb-2">
                                                        <span class="badge text-bg-light border product-variant-combos-count">0 variaciones</span>
                                                    </div>
                                                    <div class="product-variant-columns-header mb-2">
                                                        <div class="row g-2 align-items-end">
                                                            <div class="col-md-5">
                                                                <div class="row g-2 product-variant-attributes-header">
                                                                    <div class="col-12">
                                                                        <span class="product-variant-col-title">Atributos</span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-2 product-variant-header-price-col">
                                                                <span class="product-variant-col-title">Precio</span>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <span class="product-variant-col-title">Stock actual</span>
                                                            </div>
                                                            <div class="col-md-2">
                                                                <span class="product-variant-col-title">Stock mínimo</span>
                                                            </div>
                                                            <div class="col-md-1">
                                                                <span class="product-variant-col-title text-center d-block">Acción</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="product-variant-rows">
                                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $createVariantNames; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $variantIndex => $variantName): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                                            <?php
                                                                $variantPrice = (string) ($createVariantPrices[$variantIndex] ?? '');
                                                                $variantQuantity = (string) ($createVariantQuantities[$variantIndex] ?? '0');
                                                                $variantMinStock = (string) ($createVariantMinStocks[$variantIndex] ?? '0');
                                                            ?>
                                                            <div class="row g-2 mb-2 product-variant-row" data-variant-name="<?php echo e((string) $variantName); ?>">
                                                                <div class="col-md-5">
                                                                    <div class="row g-2 product-variation-attribute-selects"></div>
                                                                    <input type="hidden" class="product-variant-name-input" name="variante_nombre[]" value="<?php echo e((string) $variantName); ?>">
                                                                    <small class="text-muted d-block mt-1 product-variant-name-preview"></small>
                                                                </div>
                                                                <div class="col-md-2 product-variant-price-col <?php echo e($createVariantsMode === 'individual' ? '' : 'd-none'); ?>">
                                                                    <input type="number" step="0.01" min="0" class="form-control" name="variante_precio[]" value="<?php echo e($variantPrice); ?>" placeholder="Precio">
                                                                </div>
                                                                <div class="col-md-2">
                                                                    <input type="number" step="1" min="0" class="form-control" name="variante_cantidad[]" value="<?php echo e($variantQuantity); ?>" placeholder="Stock actual">
                                                                </div>
                                                                <div class="col-md-2">
                                                                    <input type="number" step="1" min="0" class="form-control" name="variante_stock_minimo[]" value="<?php echo e($variantMinStock); ?>" placeholder="Stock mínimo">
                                                                </div>
                                                                <div class="col-md-1 d-grid">
                                                                    <button class="btn btn-outline-danger product-variant-remove-row" type="button">
                                                                        <i class="bx bx-x"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12">
                                    <label class="form-label">Vista previa</label>
                                    <div class="d-flex align-items-center gap-3 mb-2">
                                        <img
                                            id="createProductPreview"
                                            src="<?php echo e($defaultProductImageUrl); ?>"
                                            data-fallback-src="<?php echo e($defaultProductImageUrl); ?>"
                                            alt="Vista previa del producto"
                                            class="rounded border"
                                            style="width: 64px; height: 64px; object-fit: cover;"
                                        >
                                        <small class="text-muted">Si no cargas foto, se usará la imagen por defecto.</small>
                                    </div>
                                    <label class="form-label">Foto del producto</label>
                                    <input
                                        type="file"
                                        class="form-control"
                                        name="imagen"
                                        accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
                                        data-preview-target="createProductPreview"
                                    >
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button>
                            <button class="btn btn-primary" type="submit">Guardar producto</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

    <div class="modal fade" id="importProductsModal" tabindex="-1" aria-labelledby="importProductsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h2 class="h6 mb-0" id="importProductsModalLabel">
                        <i class="bx bx-upload me-1"></i> Importar productos masivamente
                    </h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <form method="POST" action="<?php echo e(route('productos.import')); ?>" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="_product_form" value="import">
                    <div class="modal-body">
                        <div class="alert alert-info py-2 mb-3">
                            <strong>Instrucciones:</strong>
                            <ol class="mb-0 ps-3 mt-1">
                                <li>Descarga la plantilla CSV.</li>
                                <li>Los campos <strong>nombre, sku, precio_venta, categoria_nombre, proveedor_nombre y unidad_nombre</strong> son obligatorios.</li>
                                <li>El <strong>SKU es unico</strong> por empresa y se usa para detectar productos ya registrados.</li>
                                <li>Los nombres de categoria, proveedor y unidad deben coincidir exactamente con los del sistema.</li>
                                <li>Sube el archivo y elige que hacer si ya existe un producto con el mismo SKU.</li>
                            </ol>
                        </div>
                        <div class="mb-3">
                            <a href="<?php echo e(route('productos.template')); ?>" class="btn btn-outline-secondary btn-sm w-100">
                                <i class="bx bx-download me-1"></i> Descargar plantilla CSV
                            </a>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Si el SKU ya existe en el sistema</label>
                            <div class="d-flex flex-wrap gap-3">
                                <div class="form-check">
                                    <input
                                        class="form-check-input"
                                        type="radio"
                                        name="accion_duplicado"
                                        id="importDupOmitir"
                                        value="omitir"
                                        <?php echo e(old('accion_duplicado', 'omitir') !== 'actualizar' ? 'checked' : ''); ?>

                                    >
                                    <label class="form-check-label" for="importDupOmitir">
                                        Omitir (no modificar el producto existente)
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input
                                        class="form-check-input"
                                        type="radio"
                                        name="accion_duplicado"
                                        id="importDupActualizar"
                                        value="actualizar"
                                        <?php echo e(old('accion_duplicado') === 'actualizar' ? 'checked' : ''); ?>

                                    >
                                    <label class="form-check-label" for="importDupActualizar">
                                        Actualizar el producto existente
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="importCsvFile" class="form-label fw-semibold">Archivo CSV <span class="text-danger">*</span></label>
                            <input type="file" class="form-control" id="importCsvFile" name="archivo_csv" accept=".csv" required>
                            <div class="form-text">Solo archivos .csv. Maximo 5 MB.</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bx bx-upload me-1"></i> Importar productos
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const modalElement = document.getElementById('createProductModal');
            const importModalElement = document.getElementById('importProductsModal');
            const shouldOpenImportModal = <?php echo json_encode($shouldOpenImportModal, 15, 512) ?>;
            if (shouldOpenImportModal && importModalElement && typeof bootstrap !== 'undefined') {
                const importModal = new bootstrap.Modal(importModalElement);
                importModal.show();
            }

            if (!modalElement) {
                return;
            }

            const form = modalElement.querySelector('form');
            if (!form) {
                return;
            }

            const taxSelect = form.querySelector('.product-tax-select');
            const taxHiddenSelector = taxSelect ? taxSelect.dataset.taxHidden : '';
            const taxHiddenInput = taxHiddenSelector ? form.querySelector(taxHiddenSelector) : null;
            const variantsToggle = form.querySelector('.product-variants-toggle');
            const variantsBox = variantsToggle ? form.querySelector(variantsToggle.dataset.target) : null;
            const globalStockFields = Array.from(form.querySelectorAll('.product-global-stock-field'));
            const attributesContainer = form.querySelector('.product-variant-attributes');
            const addAttributeButton = form.querySelector('.product-attribute-add-row');
            const variationRowsContainer = form.querySelector('.product-variant-rows');
            const addVariationButton = form.querySelector('.product-variant-add-row');
            const generateCombosButton = form.querySelector('.product-variant-generate-combos');
            const variationModeSelect = form.querySelector('.product-variants-mode');
            const combosCount = form.querySelector('.product-variant-combos-count');
            const variationAttributesHeader = form.querySelector('.product-variant-attributes-header');
            const variationPriceHeader = form.querySelector('.product-variant-header-price-col');
            const fileInput = form.querySelector('input[type="file"][data-preview-target]');

            const shouldOpenModal = <?php echo json_encode($shouldOpenCreateModal, 15, 512) ?>;
            if (shouldOpenModal && typeof bootstrap !== 'undefined') {
                const modal = new bootstrap.Modal(modalElement);
                modal.show();
            }

            const parseAttributeValues = (value) => {
                const unique = new Set();
                return String(value || '')
                    .split(/[,;\n]+/)
                    .map((item) => item.trim())
                    .filter((item) => item !== '')
                    .filter((item) => {
                        const key = item.toLowerCase();
                        if (unique.has(key)) {
                            return false;
                        }
                        unique.add(key);
                        return true;
                    });
            };

            const getAttributes = () => {
                if (!attributesContainer) {
                    return [];
                }

                const rows = Array.from(attributesContainer.querySelectorAll('.product-attribute-row'));
                return rows
                    .map((row, index) => {
                        const rawName = String(row.querySelector('.product-attribute-name')?.value || '').trim();
                        const values = parseAttributeValues(row.querySelector('.product-attribute-values')?.value || '');
                        if (values.length === 0) {
                            return null;
                        }

                        return {
                            name: rawName !== '' ? rawName : `Atributo ${index + 1}`,
                            values,
                        };
                    })
                    .filter((item) => item !== null);
            };

            const parseVariantNameSelections = (name) => {
                const byLabel = {};
                const byIndex = [];
                const parts = String(name || '')
                    .split(/\s*\/\s*/)
                    .map((part) => part.trim())
                    .filter((part) => part !== '');

                parts.forEach((part) => {
                    if (part.includes(':')) {
                        const split = part.split(':');
                        const label = String(split.shift() || '').trim();
                        const value = String(split.join(':') || '').trim();
                        if (label !== '' && value !== '') {
                            byLabel[label.toLowerCase()] = value;
                            byIndex.push(value);
                        }
                        return;
                    }

                    byIndex.push(part);
                });

                return {byLabel, byIndex};
            };

            const buildVariationName = (attributes, values) => {
                return values.map((value, index) => `${attributes[index].name}: ${value}`).join(' / ');
            };

            const cartesianProduct = (valueGroups) => {
                return valueGroups.reduce((acc, group) => {
                    const next = [];
                    acc.forEach((prefix) => {
                        group.forEach((value) => {
                            next.push(prefix.concat([value]));
                        });
                    });
                    return next;
                }, [[]]);
            };

            const updateTaxRate = () => {
                if (!taxSelect || !taxHiddenInput) {
                    return;
                }
                const option = taxSelect.selectedOptions[0];
                if (!option) {
                    return;
                }
                taxHiddenInput.value = String(option.dataset.rate || '0');
            };

            const syncGlobalStockFields = () => {
                if (!variantsToggle || !variantsBox) {
                    return;
                }

                const enabled = variantsToggle.checked;
                variantsBox.classList.toggle('d-none', !enabled);

                globalStockFields.forEach((field) => {
                    field.classList.toggle('d-none', enabled);
                    field.querySelectorAll('input').forEach((input) => {
                        input.disabled = enabled;
                    });
                });
            };

            const syncVariationPriceMode = () => {
                if (!variationModeSelect || !variationRowsContainer || !variationPriceHeader) {
                    return;
                }

                const individual = variationModeSelect.value === 'individual';
                variationPriceHeader.classList.toggle('d-none', !individual);

                variationRowsContainer.querySelectorAll('.product-variant-price-col').forEach((column) => {
                    column.classList.toggle('d-none', !individual);
                });
            };

            const updateVariationCount = () => {
                if (!variationRowsContainer || !combosCount) {
                    return;
                }
                combosCount.textContent = `${variationRowsContainer.querySelectorAll('.product-variant-row').length} variaciones`;
            };

            const updateVariationHeaderLabels = (attributes) => {
                if (!variationAttributesHeader) {
                    return;
                }

                variationAttributesHeader.innerHTML = '';
                if (attributes.length === 0) {
                    const col = document.createElement('div');
                    col.className = 'col-12';
                    col.innerHTML = '<span class="product-variant-col-title">Atributos</span>';
                    variationAttributesHeader.appendChild(col);
                    return;
                }

                attributes.forEach((attribute) => {
                    const col = document.createElement('div');
                    col.className = `col-${Math.max(3, Math.floor(12 / attributes.length))}`;
                    col.innerHTML = `<span class="product-variant-col-title">${attribute.name}</span>`;
                    variationAttributesHeader.appendChild(col);
                });
            };

            const renderSelectorsForRow = (row, attributes) => {
                const selectsWrapper = row.querySelector('.product-variation-attribute-selects');
                const hiddenNameInput = row.querySelector('.product-variant-name-input');
                const preview = row.querySelector('.product-variant-name-preview');
                if (!selectsWrapper || !hiddenNameInput) {
                    return;
                }

                const previous = parseVariantNameSelections(hiddenNameInput.value || row.dataset.variantName || '');
                selectsWrapper.innerHTML = '';

                attributes.forEach((attribute, attributeIndex) => {
                    const col = document.createElement('div');
                    col.className = `col-${Math.max(3, Math.floor(12 / attributes.length))}`;

                    const select = document.createElement('select');
                    select.className = 'form-select form-select-sm';
                    select.dataset.attributeLabel = attribute.name;

                    const placeholder = document.createElement('option');
                    placeholder.value = '';
                    placeholder.textContent = attribute.name;
                    select.appendChild(placeholder);

                    attribute.values.forEach((value) => {
                        const option = document.createElement('option');
                        option.value = value;
                        option.textContent = value;
                        select.appendChild(option);
                    });

                    const byLabel = previous.byLabel[attribute.name.toLowerCase()] || '';
                    const byIndex = previous.byIndex[attributeIndex] || '';
                    const selected = byLabel !== '' ? byLabel : byIndex;
                    if (selected !== '') {
                        const matchingOption = Array.from(select.options).find((opt) => opt.value.toLowerCase() === selected.toLowerCase());
                        if (matchingOption) {
                            select.value = matchingOption.value;
                        }
                    }

                    col.appendChild(select);
                    selectsWrapper.appendChild(col);
                });

                const syncName = () => {
                    const selects = Array.from(selectsWrapper.querySelectorAll('select'));
                    const selectedValues = selects.map((select) => String(select.value || '').trim());
                    if (selectedValues.some((value) => value === '')) {
                        hiddenNameInput.value = '';
                        if (preview) {
                            preview.textContent = 'Selecciona todos los atributos para formar la variación.';
                        }
                        return;
                    }

                    const variationName = buildVariationName(attributes, selectedValues);
                    hiddenNameInput.value = variationName;
                    if (preview) {
                        preview.textContent = variationName;
                    }
                };

                selectsWrapper.querySelectorAll('select').forEach((select) => {
                    select.addEventListener('change', syncName);
                });

                syncName();
            };

            const createVariationRow = (defaults = {}) => {
                if (!variationRowsContainer) {
                    return null;
                }

                const row = document.createElement('div');
                row.className = 'row g-2 mb-2 product-variant-row';
                row.dataset.variantName = String(defaults.name || '');
                const showIndividualPrice = variationModeSelect && variationModeSelect.value === 'individual';

                row.innerHTML = `
                    <div class="col-md-5">
                        <div class="row g-2 product-variation-attribute-selects"></div>
                        <input type="hidden" class="product-variant-name-input" name="variante_nombre[]" value="${String(defaults.name || '')}">
                        <small class="text-muted d-block mt-1 product-variant-name-preview"></small>
                    </div>
                    <div class="col-md-2 product-variant-price-col ${showIndividualPrice ? '' : 'd-none'}">
                        <input type="number" step="0.01" min="0" class="form-control" name="variante_precio[]" value="${String(defaults.price || '')}" placeholder="Precio">
                    </div>
                    <div class="col-md-2">
                        <input type="number" step="1" min="0" class="form-control" name="variante_cantidad[]" value="${String(defaults.quantity || '0')}" placeholder="Stock actual">
                    </div>
                    <div class="col-md-2">
                        <input type="number" step="1" min="0" class="form-control" name="variante_stock_minimo[]" value="${String(defaults.minStock || '0')}" placeholder="Stock mínimo">
                    </div>
                    <div class="col-md-1 d-grid">
                        <button class="btn btn-outline-danger product-variant-remove-row" type="button">
                            <i class="bx bx-x"></i>
                        </button>
                    </div>
                `;

                variationRowsContainer.appendChild(row);
                return row;
            };

            const syncAllVariationRows = () => {
                if (!variationRowsContainer) {
                    return;
                }

                const attributes = getAttributes();
                updateVariationHeaderLabels(attributes);

                Array.from(variationRowsContainer.querySelectorAll('.product-variant-row')).forEach((row) => {
                    renderSelectorsForRow(row, attributes);
                });

                updateVariationCount();
            };

            if (taxSelect) {
                taxSelect.addEventListener('change', updateTaxRate);
                updateTaxRate();
            }

            if (fileInput) {
                fileInput.addEventListener('change', () => {
                    const targetId = fileInput.dataset.previewTarget;
                    const target = targetId ? document.getElementById(targetId) : null;
                    if (!target) {
                        return;
                    }

                    const file = fileInput.files && fileInput.files[0] ? fileInput.files[0] : null;
                    const fallback = target.dataset.fallbackSrc || target.src;
                    if (!file) {
                        target.src = fallback;
                        return;
                    }
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        target.src = String(event.target?.result || fallback);
                    };
                    reader.readAsDataURL(file);
                });
            }

            if (variantsToggle) {
                variantsToggle.addEventListener('change', syncGlobalStockFields);
                syncGlobalStockFields();
            }

            if (variationModeSelect) {
                variationModeSelect.addEventListener('change', syncVariationPriceMode);
                syncVariationPriceMode();
            }

            if (addAttributeButton && attributesContainer) {
                addAttributeButton.addEventListener('click', () => {
                    const row = document.createElement('div');
                    row.className = 'row g-2 mb-2 product-attribute-row';
                    row.innerHTML = `
                        <div class="col-md-4">
                            <input class="form-control form-control-sm product-attribute-name" name="atributo_nombre[]" placeholder="Ej: Talla">
                        </div>
                        <div class="col-md-7">
                            <input class="form-control form-control-sm product-attribute-values" name="atributo_valores[]" placeholder="Ej: S, M, L">
                        </div>
                        <div class="col-md-1 d-grid">
                            <button class="btn btn-sm btn-outline-danger product-attribute-remove-row" type="button">
                                <i class="bx bx-x"></i>
                            </button>
                        </div>
                    `;
                    attributesContainer.appendChild(row);
                    syncAllVariationRows();
                });

                attributesContainer.addEventListener('click', (event) => {
                    const button = event.target instanceof Element ? event.target.closest('.product-attribute-remove-row') : null;
                    if (!button) {
                        return;
                    }
                    const row = button.closest('.product-attribute-row');
                    if (row) {
                        row.remove();
                        syncAllVariationRows();
                    }
                });

                attributesContainer.addEventListener('input', () => {
                    syncAllVariationRows();
                });
            }

            if (variationRowsContainer) {
                variationRowsContainer.addEventListener('click', (event) => {
                    const button = event.target instanceof Element ? event.target.closest('.product-variant-remove-row') : null;
                    if (!button) {
                        return;
                    }

                    const row = button.closest('.product-variant-row');
                    if (row) {
                        row.remove();
                    }
                    updateVariationCount();
                });
            }

            if (addVariationButton) {
                addVariationButton.addEventListener('click', () => {
                    const row = createVariationRow();
                    if (!row) {
                        return;
                    }
                    syncAllVariationRows();
                });
            }

            if (generateCombosButton) {
                generateCombosButton.addEventListener('click', () => {
                    const attributes = getAttributes();
                    if (attributes.length === 0) {
                        if (window.sileo && typeof window.sileo.warning === 'function') {
                            window.sileo.warning({
                                title: 'Atributos incompletos',
                                description: 'Define atributos con valores antes de generar variaciones.',
                                position: 'top-center',
                            });
                        } else {
                            window.alert('Define atributos con valores antes de generar variaciones.');
                        }
                        return;
                    }

                    const combinations = cartesianProduct(attributes.map((attribute) => attribute.values));
                    if (!variationRowsContainer) {
                        return;
                    }

                    variationRowsContainer.innerHTML = '';
                    combinations.forEach((combination) => {
                        const variationName = buildVariationName(attributes, combination);
                        const row = createVariationRow({
                            name: variationName,
                            price: '',
                            quantity: '0',
                            minStock: '0',
                        });
                        if (row) {
                            renderSelectorsForRow(row, attributes);
                        }
                    });

                    updateVariationCount();
                    syncVariationPriceMode();
                });
            }

            syncAllVariationRows();
            updateVariationCount();
            syncVariationPriceMode();
        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/veltrix-v2/resources/views/modules/productos/index.blade.php ENDPATH**/ ?>