<?php
$units = $units ?? [];
$unitsAll = $units_all ?? $units;
$products = $products ?? [];
$productVariantsMap = is_array($productVariantsMap ?? null) ? $productVariantsMap : [];
$suppliers = $suppliers ?? [];
$taxes = $taxes ?? [];
$defaultProductImageUrl = product_image_url('');

$oldProductForm = trim((string) old('_product_form', ''));
$editModalProductId = (int) (flash('product_edit_modal') ?? 0);
$requestOpenCreate = isset($_GET['crear']) && trim((string) $_GET['crear']) === '1';
$shouldOpenCreateProductModal = $oldProductForm === 'create' || $requestOpenCreate;
$shouldOpenEditProductModal = $oldProductForm === 'edit' && $editModalProductId > 0;

$taxesById = [];
foreach ($taxes as $tax) {
    $taxId = (int) ($tax['id'] ?? 0);
    if ($taxId > 0) {
        $taxesById[$taxId] = $tax;
    }
}

$findTaxIdByRate = static function (array $availableTaxes, float $rate): int {
    foreach ($availableTaxes as $tax) {
        $taxRate = (float) ($tax['porcentaje'] ?? 0);
        if (abs($taxRate - $rate) < 0.0001) {
            return (int) ($tax['id'] ?? 0);
        }
    }

    return 0;
};

$extractVariantAttributes = static function (array $variants): array {
    $attributeMap = [];

    foreach ($variants as $variant) {
        $variantName = trim((string) ($variant['nombre'] ?? ''));
        if ($variantName === '') {
            continue;
        }

        $parts = preg_split('/\s*\/\s*/', $variantName) ?: [];
        foreach ($parts as $partIndex => $part) {
            $piece = trim((string) $part);
            if ($piece === '') {
                continue;
            }

            if (str_contains($piece, ':')) {
                [$rawLabel, $rawValue] = array_pad(explode(':', $piece, 2), 2, '');
                $label = trim($rawLabel);
                $value = trim($rawValue);
            } else {
                $label = count($parts) > 1 ? ('Opción ' . ($partIndex + 1)) : 'Opción';
                $value = trim($piece);
            }

            if ($label === '' || $value === '') {
                continue;
            }

            $labelKey = mb_strtolower($label);
            $valueKey = mb_strtolower($value);

            if (!isset($attributeMap[$labelKey])) {
                $attributeMap[$labelKey] = [
                    'name' => $label,
                    'values' => [],
                ];
            }

            $attributeMap[$labelKey]['values'][$valueKey] = $value;
        }
    }

    $attributes = [];
    foreach ($attributeMap as $attributeData) {
        $values = array_values($attributeData['values']);
        if ($values === []) {
            continue;
        }

        $attributes[] = [
            'name' => (string) ($attributeData['name'] ?? ''),
            'values' => implode(', ', $values),
        ];
    }

    return $attributes;
};
?>

<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="h5 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>
                <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>
            </div>
        </div>
        <?php if ($suppliers === []): ?>
            <div class="alert alert-warning mb-3">
                Debes crear al menos un proveedor activo antes de registrar productos.
            </div>
        <?php endif; ?>
        <?php if ($taxes === []): ?>
            <div class="alert alert-info mb-3">
                No hay impuestos activos configurados. Puedes crearlos en Configuración para asignarlos a productos.
            </div>
        <?php endif; ?>

        <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>Mínimo</th>
                    <th>Acciones</th>
                </tr>
                </thead>
                <tbody>
                <?php if ($products === []): ?>
                    <tr>
                        <td colspan="10" class="text-center text-muted py-3">No hay productos registrados.</td>
                    </tr>
                <?php endif; ?>
                <?php foreach ($products as $item): ?>
                    <?php
                    $productId = (int) ($item['id'] ?? 0);
                    $rowVariants = is_array($productVariantsMap[$productId] ?? null) ? $productVariantsMap[$productId] : [];
                    $rowVariants = array_values(array_filter($rowVariants, static function (array $variant): bool {
                        return (int) ($variant['activo'] ?? 0) === 1;
                    }));
                    $isVariableProduct = $rowVariants !== [];
                    $variantCount = count($rowVariants);
                    $imageUrl = product_image_url((string) ($item['imagen'] ?? ''));
                    $unitLabel = trim((string) ($item['unidad_abreviatura'] ?? ''));
                    if ($unitLabel === '') {
                        $unitLabel = trim((string) ($item['unidad_nombre'] ?? ''));
                    }
                    if ($unitLabel === '') {
                        $unitLabel = '-';
                    }
                    $supplierName = trim((string) ($item['proveedor_nombre'] ?? ''));
                    if ($supplierName === '') {
                        $supplierName = 'Sin proveedor';
                    }
                    $skuValue = trim((string) ($item['sku'] ?? ''));
                    if ($skuValue === '') {
                        $skuValue = '-';
                    }
                    ?>
                    <tr>
                        <td><?= e((string) $productId) ?></td>
                        <td>
                            <img
                                src="<?= e($imageUrl) ?>"
                                alt="<?= e((string) ($item['nombre'] ?? 'Producto')) ?>"
                                class="rounded border"
                                style="width: 44px; height: 44px; object-fit: cover;"
                            >
                        </td>
                        <td>
                            <div class="d-flex flex-column gap-1">
                                <span><?= e((string) ($item['nombre'] ?? '')) ?></span>
                                <span class="vx-product-type-chip <?= $isVariableProduct ? 'is-variable' : 'is-simple' ?>">
                                    <span class="vx-product-type-icon" aria-hidden="true">
                                        <i class="bx <?= $isVariableProduct ? 'bx-slider-alt' : 'bx-box' ?>"></i>
                                    </span>
                                    <span class="vx-product-type-label">
                                        <?= $isVariableProduct ? 'Variable' : 'Simple' ?>
                                    </span>
                                    <?php if ($isVariableProduct): ?>
                                        <span class="vx-product-type-meta"><?= e((string) $variantCount) ?> vars</span>
                                    <?php endif; ?>
                                </span>
                            </div>
                        </td>
                        <td><?= e($supplierName) ?></td>
                        <td><span class="badge text-bg-light border"><?= e($skuValue) ?></span></td>
                        <td><span class="badge text-bg-light border"><?= e($unitLabel) ?></span></td>
                        <td><?= e(money((float) ($item['precio_venta'] ?? 0))) ?></td>
                        <td><?= e((string) ($item['stock_actual'] ?? 0)) ?></td>
                        <td><?= e((string) ($item['stock_minimo'] ?? 0)) ?></td>
                        <td>
                            <button
                                class="btn btn-sm btn-outline-primary"
                                type="button"
                                data-bs-toggle="modal"
                                data-bs-target="#editProductModal<?= e((string) $productId) ?>"
                            >
                                Editar
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php foreach ($products as $item): ?>
    <?php
    $productId = (int) ($item['id'] ?? 0);
    $isEditTarget = $shouldOpenEditProductModal && $editModalProductId === $productId;

    $editName = $isEditTarget ? (string) old('nombre', (string) ($item['nombre'] ?? '')) : (string) ($item['nombre'] ?? '');
    $editCategoryId = (int) ($isEditTarget ? old('categoria_id', (string) ($item['categoria_id'] ?? 0)) : (string) ($item['categoria_id'] ?? 0));
    $editSupplierId = (int) ($isEditTarget ? old('proveedor_id', (string) ($item['proveedor_id'] ?? 0)) : (string) ($item['proveedor_id'] ?? 0));
    $editUnitId = (int) ($isEditTarget ? old('unidad_medida_id', (string) ($item['unidad_medida_id'] ?? 0)) : (string) ($item['unidad_medida_id'] ?? 0));
    $editSku = (string) ($isEditTarget ? old('sku', (string) ($item['sku'] ?? '')) : (string) ($item['sku'] ?? ''));
    $editPurchasePrice = (string) ($isEditTarget ? old('precio_compra', (string) ($item['precio_compra'] ?? '0')) : (string) ($item['precio_compra'] ?? '0'));
    $editSalePrice = (string) ($isEditTarget ? old('precio_venta', (string) ($item['precio_venta'] ?? '0')) : (string) ($item['precio_venta'] ?? '0'));
    $editStock = (string) ($isEditTarget ? old('stock_actual', (string) ($item['stock_actual'] ?? '0')) : (string) ($item['stock_actual'] ?? '0'));
    $editMinStock = (string) ($isEditTarget ? old('stock_minimo', (string) ($item['stock_minimo'] ?? '0')) : (string) ($item['stock_minimo'] ?? '0'));
    $editBarcode = (string) ($isEditTarget ? old('codigo_barras', (string) ($item['codigo_barras'] ?? '')) : (string) ($item['codigo_barras'] ?? ''));
    $productTaxRate = (float) ($item['impuesto_porcentaje'] ?? 0);
    $defaultEditTaxId = $findTaxIdByRate($taxes, $productTaxRate);
    $editTaxId = (int) ($isEditTarget ? old('impuesto_id', (string) $defaultEditTaxId) : (string) $defaultEditTaxId);
    $editTaxRate = (float) ($isEditTarget ? old('impuesto_porcentaje', (string) $productTaxRate) : $productTaxRate);
    $editHasCustomTax = $editTaxId <= 0 && $editTaxRate > 0;
    $editCustomTaxLabel = 'Actual (' . number_format($editTaxRate, 2) . '%)';
    $editUseDefault = $isEditTarget && (string) old('usar_imagen_defecto', '0') === '1';
    $existingVariants = is_array($productVariantsMap[$productId] ?? null) ? $productVariantsMap[$productId] : [];
    $editVariantsEnabled = $isEditTarget
        ? (string) old('variantes_habilitadas', $existingVariants !== [] ? '1' : '0') === '1'
        : $existingVariants !== [];
    $editVariantsMode = strtolower((string) ($isEditTarget ? old('variantes_modo', 'same') : 'same'));
    if (!in_array($editVariantsMode, ['same', 'individual'], true)) {
        $editVariantsMode = 'same';
    }
    $editVariantNames = $isEditTarget ? (array) old('variante_nombre', []) : array_map(
        static fn (array $variant): string => (string) ($variant['nombre'] ?? ''),
        $existingVariants
    );
    $editVariantPrices = $isEditTarget ? (array) old('variante_precio', []) : array_map(
        static fn (array $variant): string => (string) ($variant['precio_venta'] ?? ''),
        $existingVariants
    );
    $editVariantQuantities = $isEditTarget ? (array) old('variante_cantidad', []) : array_map(
        static fn (array $variant): string => (string) ((int) ($variant['cantidad'] ?? 0)),
        $existingVariants
    );
    $editVariantMinStocks = $isEditTarget ? (array) old('variante_stock_minimo', []) : array_map(
        static fn (array $variant): string => (string) ((int) ($variant['stock_minimo'] ?? 0)),
        $existingVariants
    );

    $detectedAttributes = $extractVariantAttributes($existingVariants);
    if ($detectedAttributes === []) {
        $detectedAttributes = [
            ['name' => 'Talla', 'values' => ''],
            ['name' => 'Color', 'values' => ''],
        ];
    }

    $editAttributeNames = $isEditTarget
        ? (array) old('atributo_nombre', array_map(static fn (array $attr): string => (string) ($attr['name'] ?? ''), $detectedAttributes))
        : array_map(static fn (array $attr): string => (string) ($attr['name'] ?? ''), $detectedAttributes);
    $editAttributeValues = $isEditTarget
        ? (array) old('atributo_valores', array_map(static fn (array $attr): string => (string) ($attr['values'] ?? ''), $detectedAttributes))
        : array_map(static fn (array $attr): string => (string) ($attr['values'] ?? ''), $detectedAttributes);

    if ($editAttributeNames === []) {
        $editAttributeNames = ['Talla', 'Color'];
        $editAttributeValues = ['', ''];
    }

    if ($editVariantNames === []) {
        $editVariantNames = [''];
        $editVariantPrices = [''];
        $editVariantQuantities = ['0'];
        $editVariantMinStocks = ['0'];
    }
    ?>
    <div class="modal fade" id="editProductModal<?= e((string) $productId) ?>" tabindex="-1" aria-labelledby="editProductModalLabel<?= e((string) $productId) ?>" 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="editProductModalLabel<?= e((string) $productId) ?>">
                        Editar producto #<?= e((string) $productId) ?>
                    </h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <form action="<?= e(url('productos/' . $productId . '/actualizar')) ?>" method="post" enctype="multipart/form-data">
                    <div class="modal-body">
                        <?= csrf_field() ?>
                        <input type="hidden" name="_product_form" value="edit">
                        <input type="hidden" name="_product_id" value="<?= e((string) $productId) ?>">

                        <div class="row g-2">
                            <div class="col-12">
                                <label class="form-label">Nombre</label>
                                <input class="form-control" name="nombre" value="<?= e($editName) ?>" 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 foreach ($categories as $category): ?>
                                        <option value="<?= e((string) $category['id']) ?>" <?= $editCategoryId === (int) $category['id'] ? 'selected' : '' ?>>
                                            <?= e((string) $category['nombre']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </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 foreach ($suppliers as $supplier): ?>
                                        <option value="<?= e((string) $supplier['id']) ?>" <?= $editSupplierId === (int) $supplier['id'] ? 'selected' : '' ?>>
                                            <?= e((string) ($supplier['nombre'] ?? '')) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </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 foreach ($unitsAll as $unit): ?>
                                        <?php
                                        $unitIsActive = (int) ($unit['activo'] ?? 1) === 1;
                                        $unitSuffix = $unitIsActive ? '' : ' (Inactiva)';
                                        ?>
                                        <option value="<?= e((string) $unit['id']) ?>" <?= $editUnitId === (int) $unit['id'] ? 'selected' : '' ?>>
                                            <?= e((string) ($unit['nombre'] ?? '')) ?> (<?= e((string) ($unit['abreviatura'] ?? '')) ?>)<?= e($unitSuffix) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </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="#editProductTaxRate<?= e((string) $productId) ?>">
                                    <option value="0" data-rate="<?= e($editHasCustomTax ? (string) $editTaxRate : '0') ?>" data-type="" <?= $editTaxId <= 0 ? 'selected' : '' ?>><?= e($editHasCustomTax ? $editCustomTaxLabel : 'Sin impuesto') ?></option>
                                    <?php foreach ($taxes as $tax): ?>
                                        <?php
                                        $taxId = (int) ($tax['id'] ?? 0);
                                        $taxRate = (float) ($tax['porcentaje'] ?? 0);
                                        $taxName = trim((string) ($tax['nombre'] ?? 'Impuesto'));
                                        $taxType = trim((string) ($tax['tipo'] ?? ''));
                                        $taxOptionLabel = $taxName . ' (' . number_format($taxRate, 2) . '%';
                                        if ($taxType !== '' && strcasecmp($taxType, $taxName) !== 0) {
                                            $taxOptionLabel .= ' · ' . $taxType;
                                        }
                                        $taxOptionLabel .= ')';
                                        ?>
                                        <option value="<?= e((string) $taxId) ?>" data-rate="<?= e((string) $taxRate) ?>" data-type="<?= e($taxType) ?>" <?= $editTaxId === $taxId ? 'selected' : '' ?>>
                                            <?= e($taxOptionLabel) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <input type="hidden" name="impuesto_porcentaje" id="editProductTaxRate<?= e((string) $productId) ?>" value="<?= e((string) $editTaxRate) ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label">SKU / Código interno</label>
                                <input class="form-control" name="sku" value="<?= e($editSku) ?>" 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="<?= e($editPurchasePrice) ?>">
                            </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="<?= e($editSalePrice) ?>" required>
                            </div>
                            <div class="col-md-6 product-global-stock-field <?= $editVariantsEnabled ? 'd-none' : '' ?>">
                                <label class="form-label">Stock actual</label>
                                <input type="number" step="0.01" class="form-control" name="stock_actual" value="<?= e($editStock) ?>" <?= $editVariantsEnabled ? 'disabled' : '' ?>>
                            </div>
                            <div class="col-md-6 product-global-stock-field <?= $editVariantsEnabled ? 'd-none' : '' ?>">
                                <label class="form-label">Stock mínimo</label>
                                <input type="number" step="0.01" class="form-control" name="stock_minimo" value="<?= e($editMinStock) ?>" <?= $editVariantsEnabled ? 'disabled' : '' ?>>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Código de barras</label>
                                <input class="form-control" name="codigo_barras" value="<?= e($editBarcode) ?>">
                            </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="editVariantsToggle<?= e((string) $productId) ?>"
                                                name="variantes_habilitadas"
                                                value="1"
                                                data-target="#editVariantsBox<?= e((string) $productId) ?>"
                                                <?= $editVariantsEnabled ? 'checked' : '' ?>
                                            >
                                            <label class="form-check-label" for="editVariantsToggle<?= e((string) $productId) ?>">Activar</label>
                                        </div>
                                    </div>
                                    <div
                                        id="editVariantsBox<?= e((string) $productId) ?>"
                                        class="product-variants-box <?= $editVariantsEnabled ? '' : '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="#editProductAttributesTab<?= e((string) $productId) ?>"
                                                    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="#editProductVariationsTab<?= e((string) $productId) ?>"
                                                    role="tab"
                                                    aria-selected="false"
                                                >
                                                    Variaciones
                                                </button>
                                            </li>
                                        </ul>
                                        <div class="tab-content">
                                            <div
                                                class="tab-pane fade show active product-variant-pane"
                                                id="editProductAttributesTab<?= e((string) $productId) ?>"
                                                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 foreach ($editAttributeNames as $attributeIndex => $attributeName): ?>
                                                            <?php $attributeValues = (string) ($editAttributeValues[$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="<?= 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="<?= 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 endforeach; ?>
                                                    </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="editProductVariationsTab<?= e((string) $productId) ?>"
                                                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" <?= $editVariantsMode === 'same' ? 'selected' : '' ?>>Mismo precio para todas</option>
                                                            <option value="individual" <?= $editVariantsMode === '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 foreach ($editVariantNames as $variantIndex => $variantName): ?>
                                                        <?php $variantPrice = (string) ($editVariantPrices[$variantIndex] ?? ''); ?>
                                                        <?php $variantQuantity = (string) ($editVariantQuantities[$variantIndex] ?? '0'); ?>
                                                        <?php $variantMinStock = (string) ($editVariantMinStocks[$variantIndex] ?? '0'); ?>
                                                        <div class="row g-2 mb-2 product-variant-row" data-variant-name="<?= 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="<?= 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 <?= $editVariantsMode === 'individual' ? '' : 'd-none' ?>">
                                                                <input
                                                                    type="number"
                                                                    step="0.01"
                                                                    min="0"
                                                                    class="form-control"
                                                                    name="variante_precio[]"
                                                                    value="<?= e($variantPrice) ?>"
                                                                    placeholder="Precio"
                                                                >
                                                            </div>
                                                            <div class="col-md-2">
                                                                <input
                                                                    type="number"
                                                                    step="1"
                                                                    min="0"
                                                                    class="form-control"
                                                                    name="variante_cantidad[]"
                                                                    value="<?= 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="<?= 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 endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <?php $currentImageUrl = product_image_url((string) ($item['imagen'] ?? '')); ?>
                                <label class="form-label">Foto actual</label>
                                <div class="d-flex align-items-center gap-3 mb-2">
                                    <img
                                        id="editProductPreview<?= e((string) $productId) ?>"
                                        src="<?= e($currentImageUrl) ?>"
                                        data-fallback-src="<?= e($currentImageUrl) ?>"
                                        alt="Foto del producto"
                                        class="rounded border"
                                        style="width: 64px; height: 64px; object-fit: cover;"
                                    >
                                    <small class="text-muted">Selecciona una nueva imagen para reemplazarla.</small>
                                </div>
                                <label class="form-label">Cambiar foto (opcional)</label>
                                <input
                                    type="file"
                                    class="form-control"
                                    name="imagen"
                                    accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
                                    data-preview-target="editProductPreview<?= e((string) $productId) ?>"
                                >
                                <div class="form-check mt-2">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        id="useDefaultImage<?= e((string) $productId) ?>"
                                        name="usar_imagen_defecto"
                                        value="1"
                                        data-preview-target="editProductPreview<?= e((string) $productId) ?>"
                                        data-preview-default="<?= e($defaultProductImageUrl) ?>"
                                        <?= $editUseDefault ? 'checked' : '' ?>
                                    >
                                    <label class="form-check-label" for="useDefaultImage<?= e((string) $productId) ?>">
                                        Usar imagen por defecto
                                    </label>
                                </div>
                            </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 cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endforeach; ?>

<?php
$defaultCreateTaxId = 0;
if ($taxes !== []) {
    $defaultCreateTaxId = (int) ($taxes[0]['id'] ?? 0);
}
$createTaxId = (int) old('impuesto_id', (string) $defaultCreateTaxId);
$createTaxRate = (float) old('impuesto_porcentaje', (string) ((float) ($taxesById[$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', ['0']);
$createVariantMinStocks = (array) old('variante_stock_minimo', ['0']);
$createAttributeNames = (array) old('atributo_nombre', ['Talla', 'Color']);
$createAttributeValues = (array) old('atributo_valores', ['', '']);
if ($createVariantNames === []) {
    $createVariantNames = [''];
    $createVariantPrices = [''];
    $createVariantQuantities = ['0'];
    $createVariantMinStocks = ['0'];
}
if ($createAttributeNames === []) {
    $createAttributeNames = ['Talla', 'Color'];
    $createAttributeValues = ['', ''];
}
?>

<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="<?= e(url('productos')) ?>" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <?= csrf_field() ?>
                    <input type="hidden" name="_product_form" value="create">
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label">Nombre</label>
                            <input class="form-control" name="nombre" value="<?= e(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 foreach ($categories as $category): ?>
                                    <option value="<?= e((string) $category['id']) ?>" <?= (int) old('categoria_id', 0) === (int) $category['id'] ? 'selected' : '' ?>>
                                        <?= e((string) $category['nombre']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </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 foreach ($suppliers as $supplier): ?>
                                    <option value="<?= e((string) $supplier['id']) ?>" <?= (int) old('proveedor_id', 0) === (int) $supplier['id'] ? 'selected' : '' ?>>
                                        <?= e((string) ($supplier['nombre'] ?? '')) ?>
                                    </option>
                                <?php endforeach; ?>
                            </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 foreach ($units as $unit): ?>
                                    <option value="<?= e((string) $unit['id']) ?>" <?= (int) old('unidad_medida_id', 0) === (int) $unit['id'] ? 'selected' : '' ?>>
                                        <?= e((string) ($unit['nombre'] ?? '')) ?> (<?= e((string) ($unit['abreviatura'] ?? '')) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </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="<?= e($createHasCustomTax ? (string) $createTaxRate : '0') ?>" data-type="" <?= $createTaxId <= 0 ? 'selected' : '' ?>><?= e($createHasCustomTax ? $createCustomTaxLabel : 'Sin impuesto') ?></option>
                                <?php foreach ($taxes as $tax): ?>
                                    <?php
                                    $taxId = (int) ($tax['id'] ?? 0);
                                    $taxRate = (float) ($tax['porcentaje'] ?? 0);
                                    $taxName = trim((string) ($tax['nombre'] ?? 'Impuesto'));
                                    $taxType = trim((string) ($tax['tipo'] ?? ''));
                                    $taxOptionLabel = $taxName . ' (' . number_format($taxRate, 2) . '%';
                                    if ($taxType !== '' && strcasecmp($taxType, $taxName) !== 0) {
                                        $taxOptionLabel .= ' · ' . $taxType;
                                    }
                                    $taxOptionLabel .= ')';
                                    ?>
                                    <option value="<?= e((string) $taxId) ?>" data-rate="<?= e((string) $taxRate) ?>" data-type="<?= e($taxType) ?>" <?= $createTaxId === $taxId ? 'selected' : '' ?>>
                                        <?= e($taxOptionLabel) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden" name="impuesto_porcentaje" id="createProductTaxRate" value="<?= e((string) $createTaxRate) ?>">
                        </div>
                        <div class="col-12">
                            <label class="form-label">SKU / Código interno</label>
                            <input class="form-control" name="sku" value="<?= e(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="<?= e(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="<?= e(old('precio_venta', '0')) ?>" required>
                        </div>
                        <div class="col-md-6 product-global-stock-field <?= $createVariantsEnabled ? 'd-none' : '' ?>">
                            <label class="form-label">Stock inicial</label>
                            <input type="number" step="0.01" class="form-control" name="stock_actual" value="<?= e(old('stock_actual', '0')) ?>" <?= $createVariantsEnabled ? 'disabled' : '' ?>>
                        </div>
                        <div class="col-md-6 product-global-stock-field <?= $createVariantsEnabled ? 'd-none' : '' ?>">
                            <label class="form-label">Stock mínimo</label>
                            <input type="number" step="0.01" class="form-control" name="stock_minimo" value="<?= e(old('stock_minimo', '0')) ?>" <?= $createVariantsEnabled ? 'disabled' : '' ?>>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Código de barras</label>
                            <input class="form-control" name="codigo_barras" value="<?= e(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"
                                            <?= $createVariantsEnabled ? 'checked' : '' ?>
                                        >
                                        <label class="form-check-label" for="createVariantsToggle">Activar</label>
                                    </div>
                                </div>
                                <div id="createVariantsBox" class="product-variants-box <?= $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 foreach ($createAttributeNames as $attributeIndex => $attributeName): ?>
                                                        <?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="<?= 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="<?= 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 endforeach; ?>
                                                </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" <?= $createVariantsMode === 'same' ? 'selected' : '' ?>>Mismo precio para todas</option>
                                                        <option value="individual" <?= $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 foreach ($createVariantNames as $variantIndex => $variantName): ?>
                                                    <?php $variantPrice = (string) ($createVariantPrices[$variantIndex] ?? ''); ?>
                                                    <?php $variantQuantity = (string) ($createVariantQuantities[$variantIndex] ?? '0'); ?>
                                                    <?php $variantMinStock = (string) ($createVariantMinStocks[$variantIndex] ?? '0'); ?>
                                                    <div class="row g-2 mb-2 product-variant-row" data-variant-name="<?= 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="<?= 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 <?= $createVariantsMode === 'individual' ? '' : 'd-none' ?>">
                                                            <input
                                                                type="number"
                                                                step="0.01"
                                                                min="0"
                                                                class="form-control"
                                                                name="variante_precio[]"
                                                                value="<?= e($variantPrice) ?>"
                                                                placeholder="Precio"
                                                            >
                                                        </div>
                                                        <div class="col-md-2">
                                                            <input
                                                                type="number"
                                                                step="1"
                                                                min="0"
                                                                class="form-control"
                                                                name="variante_cantidad[]"
                                                                value="<?= 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="<?= 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 endforeach; ?>
                                            </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="<?= e($defaultProductImageUrl) ?>"
                                    data-fallback-src="<?= 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>

<!-- Modal: Importar productos CSV -->
<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">
            <div class="modal-header">
                <h5 class="modal-title" id="importProductsModalLabel">
                    <i class="bx bx-upload me-1"></i> Importar productos masivamente
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <form method="POST" action="<?= url('productos/importar') ?>" enctype="multipart/form-data">
                <?= csrf_field() ?>
                <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 único</strong> por empresa y se usa para detectar productos ya registrados.</li>
                            <li>Los nombres de categoría, proveedor y unidad deben coincidir exactamente con los del sistema.</li>
                            <li>Sube el archivo y elige qué hacer si ya existe un producto con el mismo SKU.</li>
                        </ol>
                    </div>
                    <div class="mb-3">
                        <a href="<?= url('productos/plantilla') ?>" 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 gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="accion_duplicado" id="importDupOmitir" value="omitir" 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">
                                <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. Máximo 5 MB.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-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 if ($shouldOpenCreateProductModal || $shouldOpenEditProductModal): ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
    if (typeof bootstrap === 'undefined') {
        return;
    }

    <?php if ($shouldOpenEditProductModal): ?>
    const editModalElement = document.getElementById('editProductModal<?= e((string) $editModalProductId) ?>');
    if (editModalElement) {
        const editModal = new bootstrap.Modal(editModalElement);
        editModal.show();
        return;
    }
    <?php endif; ?>

    <?php if ($shouldOpenCreateProductModal): ?>
    const createModalElement = document.getElementById('createProductModal');
    if (!createModalElement) {
        return;
    }

    const createProductModal = new bootstrap.Modal(createModalElement);
    createProductModal.show();
    <?php endif; ?>
});
</script>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            '\'': '&#39;',
        };
        return map[char] || char;
    });

    const normalizeKey = (value) => String(value || '').trim().toLowerCase();

    const notifyWarning = (title, text) => {
        if (typeof window.Swal !== 'undefined') {
            window.Swal.fire({
                icon: 'warning',
                title,
                text,
                confirmButtonText: 'Entendido',
            });
            return;
        }
        window.alert(text);
    };

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

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

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

        return {byLabel, byIndex};
    };

    const findMatchingValue = (options, candidate) => {
        const target = normalizeKey(candidate);
        if (target === '') {
            return '';
        }

        for (const option of options) {
            if (normalizeKey(option) === target) {
                return option;
            }
        }

        return '';
    };

    const createAttributeRow = (defaults = {}) => {
        const defaultName = escapeHtml(defaults.name || '');
        const defaultValues = escapeHtml(defaults.values || '');

        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[]" value="${defaultName}" placeholder="Ej: Talla">
            </div>
            <div class="col-md-7">
                <input class="form-control form-control-sm product-attribute-values" name="atributo_valores[]" value="${defaultValues}" 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>
        `;

        return row;
    };

    const collectAttributes = (scope) => {
        const attributesContainer = scope.querySelector('.product-variant-attributes');
        if (!attributesContainer) {
            return [];
        }

        const rows = Array.from(attributesContainer.querySelectorAll('.product-attribute-row'));
        const attributes = [];

        rows.forEach((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;
            }

            const fallbackName = `Atributo ${index + 1}`;
            attributes.push({
                name: rawName !== '' ? rawName : fallbackName,
                values,
            });
        });

        return attributes;
    };

    const buildVariationName = (attributes, values) => {
        const pieces = [];
        values.forEach((value, index) => {
            const label = String(attributes[index]?.name || '').trim();
            pieces.push(label !== '' ? `${label}: ${value}` : value);
        });
        return pieces.join(' / ');
    };

    const buildVariationNameFromSelects = (selects) => {
        const pieces = [];
        selects.forEach((select, index) => {
            const value = String(select.value || '').trim();
            const label = String(select.dataset.attributeLabel || `Atributo ${index + 1}`).trim();
            if (value === '') {
                return;
            }
            pieces.push(label !== '' ? `${label}: ${value}` : value);
        });
        return pieces.join(' / ');
    };

    const createVariantRow = (mode, defaults = {}) => {
        const defaultName = escapeHtml(defaults.name || '');
        const defaultPrice = defaults.price !== undefined && defaults.price !== null ? String(defaults.price) : '';
        const defaultQuantityRaw = defaults.quantity !== undefined && defaults.quantity !== null ? Number(defaults.quantity) : 0;
        const defaultQuantity = Number.isFinite(defaultQuantityRaw) ? Math.max(0, Math.floor(defaultQuantityRaw)) : 0;
        const defaultMinStockRaw = defaults.minStock !== undefined && defaults.minStock !== null ? Number(defaults.minStock) : 0;
        const defaultMinStock = Number.isFinite(defaultMinStockRaw) ? Math.max(0, Math.floor(defaultMinStockRaw)) : 0;

        const row = document.createElement('div');
        row.className = 'row g-2 mb-2 product-variant-row';
        row.setAttribute('data-variant-name', defaults.name ? String(defaults.name) : '');
        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="${defaultName}">
                <small class="text-muted d-block mt-1 product-variant-name-preview"></small>
            </div>
            <div class="col-md-2 product-variant-price-col ${mode === 'individual' ? '' : 'd-none'}">
                <input type="number" step="0.01" min="0" class="form-control" name="variante_precio[]" value="${escapeHtml(defaultPrice)}" placeholder="Precio">
            </div>
            <div class="col-md-2">
                <input type="number" step="1" min="0" class="form-control" name="variante_cantidad[]" value="${defaultQuantity}" placeholder="Stock actual">
            </div>
            <div class="col-md-2">
                <input type="number" step="1" min="0" class="form-control" name="variante_stock_minimo[]" value="${defaultMinStock}" 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>
        `;

        return row;
    };

    const syncVariantPriceColumns = (scope) => {
        const modeSelect = scope.querySelector('.product-variants-mode');
        const mode = modeSelect ? String(modeSelect.value || 'same') : 'same';
        scope.querySelectorAll('.product-variant-price-col').forEach((col) => {
            col.classList.toggle('d-none', mode !== 'individual');
        });
        scope.querySelectorAll('.product-variant-header-price-col').forEach((col) => {
            col.classList.toggle('d-none', mode !== 'individual');
        });
    };

    const updateVariantCountBadge = (scope) => {
        const rowsContainer = scope.querySelector('.product-variant-rows');
        const countBadge = scope.querySelector('.product-variant-combos-count');
        if (!rowsContainer || !countBadge) {
            return;
        }

        const count = rowsContainer.querySelectorAll('.product-variant-row').length;
        countBadge.textContent = count === 1 ? '1 variación' : `${count} variaciones`;
    };

    const updateVariantRowName = (row) => {
        const hiddenNameInput = row.querySelector('.product-variant-name-input');
        const previewNode = row.querySelector('.product-variant-name-preview');
        const selects = Array.from(row.querySelectorAll('.product-variant-attr-select'));
        if (!hiddenNameInput || !previewNode) {
            return;
        }

        if (selects.length === 0) {
            hiddenNameInput.value = '';
            previewNode.textContent = 'Define atributos para crear esta variación.';
            return;
        }

        const hasEmpty = selects.some((select) => String(select.value || '').trim() === '');
        if (hasEmpty) {
            hiddenNameInput.value = '';
            previewNode.textContent = 'Selecciona todos los atributos para completar la variación.';
            return;
        }

        const composedName = buildVariationNameFromSelects(selects);
        hiddenNameInput.value = composedName;
        previewNode.textContent = composedName;
    };

    const getRowSelectionHints = (row) => {
        const byLabel = {};
        const byIndex = [];
        const selects = Array.from(row.querySelectorAll('.product-variant-attr-select'));

        selects.forEach((select, index) => {
            const selectedValue = String(select.value || '').trim();
            const label = String(select.dataset.attributeLabel || '').trim();
            if (selectedValue === '') {
                return;
            }
            byIndex[index] = selectedValue;
            if (label !== '') {
                byLabel[normalizeKey(label)] = selectedValue;
            }
        });

        return {byLabel, byIndex};
    };

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

        selectContainer.innerHTML = '';
        if (attributes.length === 0) {
            selectContainer.innerHTML = `
                <div class="col-12">
                    <div class="alert alert-light border py-2 px-3 mb-0 small">
                        Define atributos y valores en la pestaña <strong>Atributos</strong>.
                    </div>
                </div>
            `;
            hiddenNameInput.value = '';
            previewNode.textContent = 'Sin atributos disponibles.';
            return;
        }

        const hints = selectionHints || {byLabel: {}, byIndex: []};
        attributes.forEach((attribute, index) => {
            const col = document.createElement('div');
            col.className = attributes.length >= 3 ? 'col-md-4' : 'col-md-6';

            const select = document.createElement('select');
            select.className = 'form-select form-select-sm product-variant-attr-select';
            select.dataset.attributeLabel = attribute.name;
            select.dataset.attributeIndex = String(index);

            const emptyOption = document.createElement('option');
            emptyOption.value = '';
            emptyOption.textContent = `${attribute.name}: seleccionar`;
            select.appendChild(emptyOption);

            let candidate = '';
            const labelKey = normalizeKey(attribute.name);
            if (hints.byLabel && hints.byLabel[labelKey]) {
                candidate = String(hints.byLabel[labelKey]);
            } else if (Array.isArray(hints.byIndex) && hints.byIndex[index]) {
                candidate = String(hints.byIndex[index]);
            }

            const selectedValue = findMatchingValue(attribute.values, candidate);
            attribute.values.forEach((value) => {
                const option = document.createElement('option');
                option.value = value;
                option.textContent = value;
                if (selectedValue !== '' && normalizeKey(selectedValue) === normalizeKey(value)) {
                    option.selected = true;
                }
                select.appendChild(option);
            });

            select.addEventListener('change', () => {
                updateVariantRowName(row);
            });

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

        updateVariantRowName(row);
    };

    const renderVariationHeader = (scope, attributes = null) => {
        const headerContainer = scope.querySelector('.product-variant-attributes-header');
        if (!headerContainer) {
            return;
        }

        const parsedAttributes = Array.isArray(attributes) ? attributes : collectAttributes(scope);
        headerContainer.innerHTML = '';

        if (parsedAttributes.length === 0) {
            const col = document.createElement('div');
            col.className = 'col-12';
            const title = document.createElement('span');
            title.className = 'product-variant-col-title';
            title.textContent = 'Atributos';
            col.appendChild(title);
            headerContainer.appendChild(col);
            return;
        }

        parsedAttributes.forEach((attribute) => {
            const col = document.createElement('div');
            col.className = parsedAttributes.length >= 3 ? 'col-md-4' : 'col-md-6';
            const title = document.createElement('span');
            title.className = 'product-variant-col-title';
            title.textContent = String(attribute.name || 'Atributo');
            col.appendChild(title);
            headerContainer.appendChild(col);
        });
    };

    const syncVariationRowsWithAttributes = (scope) => {
        const attributes = collectAttributes(scope);
        const rowsContainer = scope.querySelector('.product-variant-rows');
        if (!rowsContainer) {
            return;
        }

        renderVariationHeader(scope, attributes);

        rowsContainer.querySelectorAll('.product-variant-row').forEach((row) => {
            const currentHints = getRowSelectionHints(row);
            const hasCurrentSelection = Object.keys(currentHints.byLabel).length > 0 || currentHints.byIndex.some((item) => String(item || '').trim() !== '');

            let hints = currentHints;
            if (!hasCurrentSelection) {
                const hiddenNameInput = row.querySelector('.product-variant-name-input');
                const fallbackName = String(hiddenNameInput?.value || row.getAttribute('data-variant-name') || '').trim();
                hints = parseVariantNameSelections(fallbackName);
            }

            renderVariationSelects(row, attributes, hints);
        });

        updateVariantCountBadge(scope);
    };

    const cartesianProduct = (arrays) => {
        if (arrays.length === 0) {
            return [];
        }

        return arrays.reduce((accumulator, current) => {
            const next = [];
            accumulator.forEach((prefix) => {
                current.forEach((value) => {
                    next.push([...prefix, value]);
                });
            });
            return next;
        }, [[]]);
    };

    const openAttributesTab = (scope) => {
        if (typeof bootstrap === 'undefined') {
            return;
        }
        const attributesTabButton = scope.querySelector('.product-variant-tabs .nav-link[data-bs-target*="AttributesTab"]');
        if (!attributesTabButton) {
            return;
        }
        bootstrap.Tab.getOrCreateInstance(attributesTabButton).show();
    };

    const bindVariantsScope = (scope) => {
        const toggle = scope.querySelector('.product-variants-toggle');
        const modeSelect = scope.querySelector('.product-variants-mode');
        const addButton = scope.querySelector('.product-variant-add-row');
        const generateCombosButton = scope.querySelector('.product-variant-generate-combos');
        const addAttributeButton = scope.querySelector('.product-attribute-add-row');
        const attributesContainer = scope.querySelector('.product-variant-attributes');
        const rowsContainer = scope.querySelector('.product-variant-rows');
        const variationTabButtons = scope.querySelectorAll('.product-variants-tab-button');
        const globalStockFields = Array.from(scope.querySelectorAll('.product-global-stock-field'));
        if (!toggle || !modeSelect || !addButton || !rowsContainer || !attributesContainer) {
            return;
        }

        const boxTarget = toggle.getAttribute('data-target');
        const box = boxTarget ? document.querySelector(boxTarget) : null;
        if (!box) {
            return;
        }

        const syncGlobalStockFields = () => {
            const hideGlobal = toggle.checked;
            globalStockFields.forEach((field) => {
                field.classList.toggle('d-none', hideGlobal);
                field.querySelectorAll('input, select, textarea').forEach((input) => {
                    input.disabled = hideGlobal;
                });
            });
        };

        toggle.addEventListener('change', () => {
            box.classList.toggle('d-none', !toggle.checked);
            syncGlobalStockFields();
        });

        modeSelect.addEventListener('change', () => {
            syncVariantPriceColumns(box);
        });

        variationTabButtons.forEach((button) => {
            button.addEventListener('shown.bs.tab', () => {
                syncVariationRowsWithAttributes(scope);
            });
        });

        addButton.addEventListener('click', () => {
            const attributes = collectAttributes(scope);
            if (attributes.length === 0) {
                notifyWarning('Primero atributos', 'Debes crear atributos con valores antes de añadir variaciones.');
                openAttributesTab(scope);
                return;
            }

            const row = createVariantRow(String(modeSelect.value || 'same'));
            rowsContainer.appendChild(row);
            renderVariationSelects(row, attributes);
            renderVariationHeader(scope, attributes);
            syncVariantPriceColumns(box);
            updateVariantCountBadge(scope);
        });

        if (addAttributeButton) {
            addAttributeButton.addEventListener('click', () => {
                attributesContainer.appendChild(createAttributeRow());
                renderVariationHeader(scope);
            });
        }

        attributesContainer.addEventListener('click', (event) => {
            const removeAttributeButton = event.target.closest('.product-attribute-remove-row');
            if (!removeAttributeButton) {
                return;
            }

            const row = removeAttributeButton.closest('.product-attribute-row');
            if (!row) {
                return;
            }

            const totalRows = attributesContainer.querySelectorAll('.product-attribute-row').length;
            if (totalRows <= 1) {
                const nameInput = row.querySelector('.product-attribute-name');
                const valuesInput = row.querySelector('.product-attribute-values');
                if (nameInput) {
                    nameInput.value = '';
                }
                if (valuesInput) {
                    valuesInput.value = '';
                }
                return;
            }

            row.remove();
            renderVariationHeader(scope);
            if (rowsContainer.querySelectorAll('.product-variant-row').length > 0) {
                syncVariationRowsWithAttributes(scope);
            }
        });

        attributesContainer.addEventListener('change', (event) => {
            if (!event.target.closest('.product-attribute-row')) {
                return;
            }
            renderVariationHeader(scope);
            if (rowsContainer.querySelectorAll('.product-variant-row').length > 0) {
                syncVariationRowsWithAttributes(scope);
            }
        });

        if (generateCombosButton) {
            generateCombosButton.addEventListener('click', () => {
                const attributes = collectAttributes(scope);
                if (attributes.length === 0) {
                    notifyWarning('Sin atributos', 'Debes crear atributos con valores para generar variaciones.');
                    openAttributesTab(scope);
                    return;
                }
                renderVariationHeader(scope, attributes);

                const combinationMatrix = cartesianProduct(attributes.map((attribute) => attribute.values));
                if (combinationMatrix.length === 0) {
                    notifyWarning('Sin combinaciones', 'No se encontraron valores suficientes para mezclar variaciones.');
                    return;
                }

                if (combinationMatrix.length > 200) {
                    notifyWarning(
                        'Demasiadas variaciones',
                        `Generaste ${combinationMatrix.length} variaciones. Reduce valores por atributo para no saturar el formulario.`
                    );
                    return;
                }

                toggle.checked = true;
                box.classList.remove('d-none');

                const existingData = new Map();
                rowsContainer.querySelectorAll('.product-variant-row').forEach((row) => {
                    const rowName = String(row.querySelector('.product-variant-name-input')?.value || '').trim();
                    if (rowName === '') {
                        return;
                    }
                    const key = normalizeKey(rowName);
                    if (existingData.has(key)) {
                        return;
                    }
                    existingData.set(key, {
                        price: row.querySelector('input[name="variante_precio[]"]')?.value || '',
                        quantity: row.querySelector('input[name="variante_cantidad[]"]')?.value || '0',
                        minStock: row.querySelector('input[name="variante_stock_minimo[]"]')?.value || '0',
                    });
                });

                rowsContainer.innerHTML = '';
                const created = new Set();
                combinationMatrix.forEach((comboValues) => {
                    const name = buildVariationName(attributes, comboValues);
                    const key = normalizeKey(name);
                    if (name === '' || created.has(key)) {
                        return;
                    }
                    created.add(key);

                    const previous = existingData.get(key);
                    const row = createVariantRow(String(modeSelect.value || 'same'), {
                        name,
                        price: previous ? previous.price : '',
                        quantity: previous ? previous.quantity : 0,
                        minStock: previous ? previous.minStock : 0,
                    });

                    const hintsByLabel = {};
                    attributes.forEach((attribute, index) => {
                        hintsByLabel[normalizeKey(attribute.name)] = comboValues[index] || '';
                    });

                    renderVariationSelects(row, attributes, {
                        byLabel: hintsByLabel,
                        byIndex: comboValues,
                    });

                    rowsContainer.appendChild(row);
                });

                syncVariantPriceColumns(box);
                updateVariantCountBadge(scope);
            });
        }

        rowsContainer.addEventListener('click', (event) => {
            const removeButton = event.target.closest('.product-variant-remove-row');
            if (!removeButton) {
                return;
            }

            const row = removeButton.closest('.product-variant-row');
            if (!row) {
                return;
            }

            const totalRows = rowsContainer.querySelectorAll('.product-variant-row').length;
            if (totalRows <= 1) {
                const hiddenNameInput = row.querySelector('.product-variant-name-input');
                const priceInput = row.querySelector('input[name="variante_precio[]"]');
                const quantityInput = row.querySelector('input[name="variante_cantidad[]"]');
                const minStockInput = row.querySelector('input[name="variante_stock_minimo[]"]');
                if (hiddenNameInput) {
                    hiddenNameInput.value = '';
                }
                if (priceInput) {
                    priceInput.value = '';
                }
                if (quantityInput) {
                    quantityInput.value = '0';
                }
                if (minStockInput) {
                    minStockInput.value = '0';
                }
                renderVariationSelects(row, collectAttributes(scope));
                updateVariantCountBadge(scope);
                return;
            }

            row.remove();
            updateVariantCountBadge(scope);
        });

        syncGlobalStockFields();
        syncVariantPriceColumns(box);
        syncVariationRowsWithAttributes(scope);
    };

    document.querySelectorAll('.product-variants-box').forEach((box) => {
        const form = box.closest('form');
        if (!form) {
            return;
        }
        bindVariantsScope(form);
    });

    const fileInputs = document.querySelectorAll('input[type="file"][data-preview-target]');
    fileInputs.forEach((input) => {
        const targetId = input.getAttribute('data-preview-target');
        if (!targetId) {
            return;
        }

        const previewImage = document.getElementById(targetId);
        if (!previewImage) {
            return;
        }

        const fallbackSrc = previewImage.getAttribute('data-fallback-src') || previewImage.src;
        input.addEventListener('change', () => {
            const file = input.files && input.files[0] ? input.files[0] : null;
            if (!file) {
                previewImage.src = fallbackSrc;
                return;
            }

            const reader = new FileReader();
            reader.onload = (event) => {
                const result = event.target && typeof event.target.result === 'string' ? event.target.result : '';
                previewImage.src = result !== '' ? result : fallbackSrc;
            };
            reader.readAsDataURL(file);
        });
    });

    const defaultImageToggles = document.querySelectorAll('input[name="usar_imagen_defecto"][data-preview-target]');
    defaultImageToggles.forEach((toggle) => {
        const targetId = toggle.getAttribute('data-preview-target');
        const defaultSrc = toggle.getAttribute('data-preview-default');
        if (!targetId || !defaultSrc) {
            return;
        }

        const previewImage = document.getElementById(targetId);
        if (!previewImage) {
            return;
        }

        toggle.addEventListener('change', () => {
            if (toggle.checked) {
                previewImage.src = defaultSrc;
            }
        });
    });

    const taxSelectors = document.querySelectorAll('.product-tax-select[data-tax-hidden]');
    const formatTaxRate = (rate) => {
        const numeric = Number(rate);
        if (!Number.isFinite(numeric) || numeric < 0) {
            return '0.00';
        }
        return numeric.toFixed(2);
    };

    taxSelectors.forEach((select) => {
        const hiddenTarget = select.getAttribute('data-tax-hidden');
        if (!hiddenTarget) {
            return;
        }

        const hiddenInput = document.querySelector(hiddenTarget);
        const labelTarget = select.getAttribute('data-tax-label');
        const labelNode = labelTarget ? document.querySelector(labelTarget) : null;
        if (!hiddenInput) {
            return;
        }

        const syncTaxSelection = () => {
            const selectedOption = select.options[select.selectedIndex];
            const rateRaw = selectedOption ? selectedOption.getAttribute('data-rate') : '0';
            const taxRate = formatTaxRate(rateRaw);
            const optionLabel = selectedOption ? String(selectedOption.textContent || '').trim() : 'Sin impuesto';

            hiddenInput.value = taxRate;
            if (labelNode) {
                labelNode.textContent = optionLabel !== '' ? optionLabel : 'Sin impuesto';
            }
        };

        select.addEventListener('change', syncTaxSelection);
        syncTaxSelection();
    });
});
</script>
