        <?php
        // producto.php
        session_start();
        include '../includes/session_control.php';
        require_once '../includes/user_activity_log.php';
        require_once '../cotizaciones/api/_node.php';

        $token = cpn_node_token_or_fail();
        $base = cpn_node_api_base();

        // ─── DEBUG & MITIGACIÓN de OOM ───
        // ——— AJAX: actualizar checklist via procedimiento almacenado ———
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_checklist') {
            header('Content-Type: application/json');
            $pid = isset($_POST['id']) ? intval($_POST['id']) : 0;
            if ($pid) {
                $r = cpn_node_request('POST', $base . '/api/productos/' . urlencode((string)$pid) . '/checklist', $token, []);
                if (!empty($r['ok'])) {
                    echo json_encode([
                        'success' => true,
                        'checklistInfo' => ($r['data']['checklistInfo'] ?? ''),
                    ]);
                } else {
                    echo json_encode(['success' => false]);
                }
            } else {
                echo json_encode(['success' => false]);
            }
            exit;
        }

        // ——— AJAX: publicar/sincronizar un producto en Woo (Node) ———
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && in_array($_POST['action'], ['woo_publish', 'woo_sync'], true)) {
            header('Content-Type: application/json');

            $pid = isset($_POST['id']) ? intval($_POST['id']) : 0;
            // Por seguridad, si no viene definido dejamos apagado; los botones lo envían explícito.
            $syncInventory = !empty($_POST['syncInventory']) ? 1 : 0;
            // includeImages=1 fuerza el flujo de "subir imágenes" (links -> adjuntos WP/Woo)
            $includeImages = !empty($_POST['includeImages']) ? 1 : 0;
            // forceImages=1 ignora el guard de .env en Node
            $forceImages = !empty($_POST['forceImages']) ? 1 : 0;

            // Publicación inicial: siempre subir imágenes, sin depender de .env.
            if ($_POST['action'] === 'woo_publish') {
                $includeImages = 1;
                $forceImages = 1;
            }
            // background=1: responder rápido y continuar best-effort sin bloquear navegación.
            $background = !empty($_POST['background']) ? 1 : 0;
            $isBackgroundSync = ($background === 1 && $_POST['action'] === 'woo_sync');

            if (!$pid) {
                echo json_encode(['success' => false, 'error' => 'ID de producto inválido']);
                exit;
            }

            $endpoint = ($_POST['action'] === 'woo_publish')
                ? ($base . '/api/woocommerce/productos/' . urlencode((string)$pid) . '/publish')
                : ($base . '/api/woocommerce/productos/' . urlencode((string)$pid) . '/sync');

            // Si es background, liberar lock de sesión y responder de inmediato.
            if ($isBackgroundSync) {
                ignore_user_abort(true);
                if (session_status() === PHP_SESSION_ACTIVE) {
                    session_write_close();
                }
                echo json_encode(['success' => true, 'queued' => true]);
                if (function_exists('fastcgi_finish_request')) {
                    fastcgi_finish_request();
                } else {
                    @ob_flush();
                    @flush();
                }
            }

            try {
                $r = cpn_node_request('POST', $endpoint, $token, [
                    'syncInventory' => $syncInventory,
                    'includeImages' => $includeImages,
                    'forceImages' => $forceImages,
                ]);

                if (!empty($r['ok'])) {
                    $eventKey = ($_POST['action'] === 'woo_publish') ? 'productos.woo_publish' : 'productos.woo_sync';
                    $msg = ($_POST['action'] === 'woo_publish') ? 'Publicó producto en Woo' : 'Sincronizó producto en Woo';
                    cpn_activity_log_event('productos', $eventKey, $msg, 'producto', $pid, [
                        'syncInventory' => $syncInventory,
                        'includeImages' => $includeImages,
                        'wp_id' => $r['data']['wp_id'] ?? null,
                        'background' => $isBackgroundSync ? 1 : 0,
                    ]);

                    if (!$isBackgroundSync) {
                        echo json_encode([
                            'success' => true,
                            'data' => ($r['data'] ?? null),
                            'inventory' => ($r['inventory'] ?? null),
                        ]);
                    }
                } else {
                    $msg = '';
                    if (isset($r['error']['message'])) $msg = $r['error']['message'];
                    elseif (isset($r['error'])) $msg = is_string($r['error']) ? $r['error'] : '';
                    if (!$isBackgroundSync) {
                        echo json_encode(['success' => false, 'error' => ($msg ?: 'No se pudo ejecutar la acción en Woo')]);
                    }
                }
            } catch (Throwable $e) {
                if (!$isBackgroundSync) {
                    echo json_encode(['success' => false, 'error' => 'Error interno al ejecutar la acción en Woo']);
                }
            }

            exit;
        }

        // ——— Obtener ID y datos del producto ———
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$id) {
            echo "ID de producto inválido.";
            exit;
        }

        // Recuperar lista de items y posición actual
        $itemList    = array_map('intval', $_SESSION['item_list'] ?? []);
        $currentIndex = array_search($id, $itemList);
        $prevId       = $itemList[$currentIndex - 1] ?? null;
        $nextId       = $itemList[$currentIndex + 1] ?? null;

        // Obtener datos del producto (Node)
        $rProducto = cpn_node_request('GET', $base . '/api/productos/' . urlencode((string)$id), $token, null);
        if (empty($rProducto['ok'])) {
            echo "Producto no encontrado.";
            exit;
        }
        $product = $rProducto['data']['product'] ?? null;
        if (!$product) {
            echo "Producto no encontrado.";
            exit;
        }

        $checklistOk = ((int)($product['checklistStatus'] ?? 0) === 1);
        $estadoOk = !in_array((int)($product['idEstado'] ?? 0), [2, 3, 4], true);
        $wooPublished = !empty($product['wp_id']);

        // Meta general (Node) para selects
        $rMeta = cpn_node_request('GET', $base . '/api/productos/meta/general', $token, null);
        $metaGeneral = !empty($rMeta['ok']) ? ($rMeta['data'] ?? []) : [];

        // Colores de estado
        $estadoColors = [
            1 => '#28a745',
            2 => '#6c757d',
            3 => '#dc3545',
            4 => '#6c757d'
        ];
        $bgEstado = $estadoColors[$product['idEstado']] ?? '';

        // Función genera <option> desde listas (Node)
        function opcionesLista($items, $seleccionado)
        {
            $opt = '';
            if (!is_array($items)) return $opt;
            foreach ($items as $r) {
                $id = (int)($r['id'] ?? 0);
                $label = (string)($r['nombre'] ?? '');
                if (!$id) continue;
                $sel = ($id === (int)$seleccionado) ? 'selected' : '';
                $opt .= "<option value=\"" . htmlspecialchars((string)$id) . "\" $sel>"
                    . htmlspecialchars($label) . "</option>";
            }
            return $opt;
        }

        // Campos técnicos
        $tech = [
            'txtMedidas'          => 'Medidas:',
            'txtMaterial'         => 'Material:',
            'txtMarca'            => 'Marca:',
            'txtAreaLogo'         => 'Área Logo:',
            'txtEmpaque'          => 'Empaque:',
            'txtObservaciones'    => 'Obs:',
            'txtObservacionesMarca' => 'Obs Marca:',
            'notasInternas'       => 'Notas Int:'
        ];
        ?>
        <?php include '../templates/header.php'; ?>
        <!-- CHECKLIST -->
        <?php if (!empty($product['checkListInfo'])): ?>
            <div class="checklist-container">
                <span id="checklistInfoText"><?= htmlspecialchars($product['checkListInfo']) ?></span>
                <button type="button" id="btnActualizarChecklist" class="btn btn-sm btn-outline-secondary">
                    Actualizar Checklist
                </button>
            </div>
        <?php endif; ?>

        <div class="row mb-2 align-items-center">
            <div class="col-sm-8">
                <h1 class="h3 font-weight-bold mb-0">
                    <span class="text-primary">
                        <?= htmlspecialchars($product['referenciaCPN'] . ' – ' . $product['nombre']) ?>
                    </span>
                    <small class="text-muted">ID: <?= $id ?></small>
                </h1>
            </div>
            <div class="col-sm-4 text-right">
                <?php if (!$wooPublished && $checklistOk && $estadoOk): ?>
                    <button id="btnWooPublish" type="button" class="btn btn-success" title="Crea el producto en Woo (variaciones incluidas)">
                        Publicar en Woo
                    </button>
                <?php elseif ($wooPublished): ?>
                    <button id="btnWooSyncNow" type="button" class="btn btn-outline-success" title="Sincroniza título/desc/SEO/dimensiones/categorías a Woo">
                        Sync Woo
                    </button>
                    <div class="custom-control custom-switch d-inline-block ml-2" style="vertical-align: middle;">
                        <input type="checkbox" class="custom-control-input" id="wooAutoSync">
                        <label class="custom-control-label" for="wooAutoSync">Auto</label>
                    </div>
                    <div class="custom-control custom-switch d-inline-block ml-2" style="vertical-align: middle;">
                        <input type="checkbox" class="custom-control-input" id="wooIncludeImages" checked>
                        <label class="custom-control-label" for="wooIncludeImages">Imágenes</label>
                    </div>
                    <small id="wooSyncStatus" class="text-muted ml-2"></small>
                <?php endif; ?>
                <button id="copyTitulo" class="btn btn-info">Instrucción Título</button>
                <button id="copyDescripcion" class="btn btn-info">Instrucción Descripción</button>
            </div>
        </div>

        <div class="d-flex justify-content-between mb-4">
            <?php if ($prevId): ?>
                <a href="producto.php?id=<?= $prevId ?>" class="btn btn-outline-primary">&laquo; Anterior</a>
            <?php else: ?>
                <div></div>
            <?php endif; ?>
            <?php if ($nextId): ?>
                <a href="producto.php?id=<?= $nextId ?>" class="btn btn-outline-primary">Siguiente &raquo;</a>
            <?php else: ?>
                <div></div>
            <?php endif; ?>
        </div>

        <!-- Pestañas superiores -->
        <ul class="nav nav-tabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" data-toggle="tab" href="#info">Información General</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-toggle="tab" href="#envio">Envío</a>
            </li>

            <?php if (!empty($product['urlExterna'])): ?>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="tab" href="#prov">Página Proveedor</a>
                </li>
            <?php endif; ?>
            <?php if (!empty($product['wp_id'])): ?>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="tab" href="#cmp">Página Compranet (<?= $product['wp_id'] ?>)</a>
                </li>
            <?php endif; ?>
            <?php if (empty($product['wp_id'])): ?>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="tab" href="#importacion">Importación</a>
                </li>
            <?php endif; ?>
        </ul>


        <div class="tab-content mt-3">
            <!-- Info General -->
            <div class="tab-pane fade show active" id="info">
                <!-- Fila 1: campos básicos -->
                <div class="form-row first-row">
                    <div class="form-group col">
                        <label class="field-label">CPN</label>
                        <input type="text" class="form-control" data-field="referenciaCPN" value="<?= htmlspecialchars($product['referenciaCPN']) ?>" readonly>
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Ref Prv</label>
                        <input type="text" class="form-control" data-field="referenciaProveedor" value="<?= htmlspecialchars($product['referenciaProveedor']) ?>" readonly>
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Prov</label>
                        <select class="form-control live-field" data-field="idProveedor">
                            <?= opcionesLista($metaGeneral['proveedores'] ?? [], $product['idProveedor']) ?>
                        </select>
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Estado</label>
                        <select id="idEstado" class="form-control live-field" data-field="idEstado" style="background-color:<?= $bgEstado ?>;color:#fff">
                            <?php
                            foreach (($metaGeneral['estados'] ?? []) as $r) {
                                $rid = (int)($r['id'] ?? 0);
                                $rnom = (string)($r['nombre'] ?? '');
                                if (!$rid) continue;
                                $sel = $rid == (int)$product['idEstado'] ? 'selected' : '';
                                echo "<option value=\"" . htmlspecialchars((string)$rid) . "\" $sel>" . htmlspecialchars($rnom) . "</option>";
                            }
                            ?>
                        </select>
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Pend</label>
                        <?php $isPendiente = isset($product['isPendiente']) ? !empty($product['isPendiente']) : ((int)($product['checklistStatus'] ?? -1) === 0); ?>
                        <input type="text" class="form-control" readonly value="<?= $isPendiente ? 'Si' : 'No' ?>">
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Tipo</label>
                        <select class="form-control live-field" data-field="idTipoProducto">
                            <?= opcionesLista($metaGeneral['tiposProducto'] ?? [], $product['idTipoProducto']) ?>
                        </select>
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Envío</label>
                        <select class="form-control live-field" data-field="idTipoEnvio">
                            <?= opcionesLista($metaGeneral['tiposEnvio'] ?? [], $product['idTipoEnvio']) ?>
                        </select>
                    </div>
                    <div class="form-group col">
                        <label class="field-label">Impuesto</label>
                        <select class="form-control live-field" data-field="idImpuesto">
                            <?= opcionesLista($metaGeneral['impuestos'] ?? [], $product['idImpuesto']) ?>
                        </select>
                    </div>
                </div>

                <!-- Contenedor principal: Publicación/SEO y campos técnicos -->
                <div class="row mt-3">
                    <!-- Publicación / SEO -->
                    <div class="col-md-6">
                        <ul class="nav nav-tabs" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link active" data-toggle="tab" href="#tab-publicacion">Publicación</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" data-toggle="tab" href="#tab-seo">SEO</a>
                            </li>
                        </ul>
                        <div class="tab-content mt-3">
                            <!-- Publicación -->
                            <div class="tab-pane fade show active" id="tab-publicacion">
                                <div class="form-row align-items-center mb-3">
                                    <div class="col-auto">
                                        <label class="field-label text-primary mb-0">Título</label>
                                    </div>
                                    <div class="col">
                                        <input type="text" id="nombre" class="form-control live-field" data-field="nombre" value="<?= htmlspecialchars($product['nombre']) ?>">
                                    </div>
                                    <div class="col-auto">
                                        <span id="nombreCount" class="char-count"></span>
                                    </div>
                                </div>
                                <div class="form-group mb-2">
                                    <label class="field-label text-primary">Descripción</label>
                                    <textarea id="descripcion" class="form-control live-field auto-resize" data-field="descripcion" rows="3"><?= htmlspecialchars($product['descripcion']) ?></textarea>
                                </div>
                                <?php if (!empty($product['wp_id'])): ?>
                                    <div class="mb-3">
                                        <button class="btn btn-sm btn-outline-secondary" type="button" data-toggle="collapse" data-target="#wooLegacyTools" aria-expanded="false" aria-controls="wooLegacyTools">
                                            Herramientas Woo (legacy)
                                        </button>
                                    </div>
                                    <div class="collapse" id="wooLegacyTools">
                                        <div class="mb-3">
                                            <button type="button" id="btnActImgs" class="btn btn-secondary mr-2">Subir Img</button>
                                            <button type="button" id="btnReemImgs" class="btn btn-secondary mr-2">Reemp Img</button>
                                            <button type="button" id="btnActCats" class="btn btn-secondary">Subir Cat.</button>
                                            <button type="button" id="btnActDesc" class="btn btn-secondary">Subir Desc.</button>
                                            <button type="button" id="btnActVar" class="btn btn-secondary">Subir Var.</button>
                                            <button type="button" id="btnReemVar" class="btn btn-secondary">Forzar Var.</button>
                                        </div>
                                        <div id="frameContainer" style="display:none; margin-bottom:1rem;">
                                            <iframe id="iframeAct" src="" style="width:100%; height:200px; border:1px solid #ddd;"></iframe>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <!-- SEO -->
                            <div class="tab-pane fade" id="tab-seo">
                                <div class="form-group">
                                    <label class="field-label">SEO Title</label>
                                    <textarea class="form-control live-field" data-field="seo_title" rows="2"><?= htmlspecialchars($product['seo_title']) ?></textarea>
                                </div>
                                <div class="form-group">
                                    <label class="field-label">SEO Short Desc</label>
                                    <textarea class="form-control live-field" data-field="seo_short_desc" rows="2"><?= htmlspecialchars($product['seo_short_desc']) ?></textarea>
                                </div>
                                <div class="form-group">
                                    <label class="field-label">Meta Description (Yoast)</label>
                                    <textarea class="form-control live-field" data-field="yoast_meta_desc" rows="3"><?= htmlspecialchars($product['yoast_meta_desc']) ?></textarea>
                                </div>
                                <div class="form-group">
                                    <label class="field-label">SEO Keywords</label>
                                    <textarea class="form-control live-field" data-field="seo_keywords" rows="2"><?= htmlspecialchars($product['seo_keywords']) ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Campos técnicos a la derecha -->
                    <div class="col-md-6">
                        <?php foreach ($tech as $f => $lbl): ?>
                            <div class="inline-label">
                                <label><?= $lbl ?></label>
                                <textarea class="form-control live-field tech-field" data-field="<?= $f ?>" rows="1" style="resize: vertical; overflow:hidden;"><?= htmlspecialchars($product[$f] ?? '') ?></textarea>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <!-- Pestaña Envío -->
            <div class="tab-pane fade" id="envio">
                <?php

                $rEnvio = cpn_node_request('GET', $base . '/api/productos/' . urlencode((string)$id) . '/envio', $token, null);
                if (empty($rEnvio['ok'])) {
                    die('Producto no encontrado');
                }
                $prod = $rEnvio['data']['prod'] ?? [];
                $chars = $rEnvio['data']['chars'] ?? [];
                $opts = $rEnvio['data']['opts'] ?? [];
                ?>

                <div class="container-fluid">

                    <!-- ========== Fila superior: 3 columnas ========== -->
                    <div class="row gx-2">
                        <!-- 1: Caja (Medidas al por mayor) -->
                        <div class="col-md-4">
                            <fieldset class="border p-2">
                                <legend class="w-auto small text-secondary">Caja (Medidas al por mayor)</legend>
                                <?php // LargoCmCaja 
                                ?>
                                <div class="mb-1">
                                    <label class="form-label small">Largo</label>
                                    <input type="number" id="largoCmCaja" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['largoCmCaja'] ?>">
                                </div>
                                <?php // AnchoCmCaja 
                                ?>
                                <div class="mb-1">
                                    <label class="form-label small">Ancho</label>
                                    <input type="number" id="anchoCmCaja" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['anchoCmCaja'] ?>">
                                </div>
                                <?php // AltoCmCaja 
                                ?>
                                <div class="mb-1">
                                    <label class="form-label small">Alto</label>
                                    <input type="number" id="altoCmCaja" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['altoCmCaja'] ?>">
                                </div>
                                <?php // UndsCaja 
                                ?>
                                <div class="mb-1">
                                    <label class="form-label small">Unid/caja</label>
                                    <input type="number" id="undsCaja" class="form-control form-control-sm"
                                        step="1" min="1" value="<?= $prod['undsCaja'] ?>">
                                </div>
                                <?php // PesoKgCaja 
                                ?>
                                <div class="mb-1">
                                    <label class="form-label small">Peso (kg)</label>
                                    <input type="number" id="pesoKgCaja" class="form-control form-control-sm"
                                        step="0.001" min="0" value="<?= $prod['pesoKgCaja'] ?>">
                                </div>
                                <?php // Volumen Caja 
                                ?>
                                <div>
                                    <label class="form-label small">Volumen Caja (cm³)</label>
                                    <div><span id="volumenCaja"><?= round($prod['largoCmCaja'] * $prod['anchoCmCaja'] * $prod['altoCmCaja'], 1) ?></span></div>
                                </div>
                                <div class="mb-1">
                                    <label class="form-label small">Acomodación</label>
                                    <div>
                                        <?php
                                        $ac = $prod['acomodacion'];          // e.g. "3x24x14"
                                        $total = array_product(explode('x', $ac));
                                        ?>
                                        <?= htmlspecialchars($ac) ?> (<?= $total ?>)
                                    </div>
                                </div>
                            </fieldset>
                        </div>

                        <!-- 2: Unidad ajustada + Datos del producto -->
                        <div class="col-md-4">
                            <fieldset class="border p-2 mb-2">
                                <legend class="w-auto small text-secondary">Unidad ajustada (cm)</legend>
                                <div class="mb-1">
                                    <label class="form-label small">Largo</label>
                                    <input type="number" id="largoProductoEnvioAjustado" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['largoProductoEnvioAjustado'] ?>">
                                </div>
                                <div class="mb-1">
                                    <label class="form-label small">Ancho</label>
                                    <input type="number" id="anchoProductoEnvioAjustado" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['anchoProductoEnvioAjustado'] ?>">
                                </div>
                                <div class="mb-1">
                                    <label class="form-label small">Alto</label>
                                    <input type="number" id="altoProductoEnvioAjustado" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['altoProductoEnvioAjustado'] ?>">
                                </div>
                            </fieldset>
                            <fieldset class="border p-2">
                                <legend class="w-auto small text-secondary">Datos del producto</legend>
                                <div class="mb-1">
                                    <label class="form-label small">Peso Und (kg)</label>
                                    <div><span id="pesoReal"><?= $prod['pesoKgProducto'] ?></span></div>
                                </div>
                                <div class="mb-1">
                                    <label class="form-label small">Peso Vol. Und (kg)</label>
                                    <div><span id="pesoVolumetricoProducto"><?= $prod['pesoVolumetricoProducto'] ?></span></div>
                                </div>
                                <div class="mb-1">
                                    <label class="form-label small">Peso Env. Und (kg)</label>
                                    <div>
                                        <span id="pesoEnvioUnidadKG" style="color:#006400;"><?= $prod['pesoEnvioUnidadKG'] ?></span>
                                        <span id="envioMetodo" style="color:#006400;"></span>
                                    </div>
                                </div>

                            </fieldset>
                        </div>

                        <!-- 3: Canvas pequeño + Revisión debajo -->
                        <div class="col-md-4">
                            <canvas id="boxCanvasSmall" width="300" height="200" style="border:1px solid #ccc; display:block; margin-bottom:1rem;"></canvas>
                            <fieldset class="border p-2">
                                <legend class="w-auto small text-secondary">Revisión</legend>
                                <div class="mb-1">
                                    <label class="form-label small">Vol Caja (cm³)</label>
                                    <div><span id="revVolCaja"><?= round($prod['largoCmCaja'] * $prod['anchoCmCaja'] * $prod['altoCmCaja'], 1) ?></span></div>
                                </div>
                                <div class="mb-1">
                                    <label class="form-label small">Vol Cálculo (cm³)</label>
                                    <div><span id="revVolCal"><?= $prod['volumenCm3ProductoAjustado'] ?></span></div>
                                </div>
                                <?php
                                $diff = round(
                                    $prod['volumenCm3ProductoAjustado'] * $prod['undsCaja']
                                        - ($prod['largoCmCaja'] * $prod['anchoCmCaja'] * $prod['altoCmCaja']),
                                    1
                                );
                                ?>
                                <div>
                                    <label class="form-label small">Diferencia (cm³)</label>
                                    <div>
                                        <span id="revDiferencia" class="<?= $diff > 0 ? 'text-success' : 'text-danger' ?>">
                                            <?= $diff ?>
                                        </span>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>

                    <!-- ========== Fila siguiente: Producto, Características, Paquetes ========== -->
                    <div class="row gx-2 mt-3">
                        <!-- Producto (txtMedidas + txtEmpaque) -->
                        <div class="col-md-4">
                            <fieldset class="border p-2 mb-3">
                                <legend class="w-auto small text-secondary">Producto</legend>
                                <div class="mb-2">
                                    <label class="form-label small">Medidas</label>
                                    <input type="text" id="txtMedidas" class="form-control form-control-sm"
                                        value="<?= htmlspecialchars($prod['txtMedidas']) ?>">
                                </div>
                                <div class="mb-2">
                                    <label class="form-label small">Empaque</label>
                                    <textarea id="txtEmpaque" class="form-control form-control-sm" rows="3"><?= htmlspecialchars($prod['txtEmpaque']) ?></textarea>
                                </div>
                                <button id="btnRedimensionar" class="btn btn-sm btn-outline-secondary">
                                    Redimensionar
                                </button>
                            </fieldset>
                        </div>

                        <!-- Características -->
                        <div class="col-md-3">
                            <fieldset class="border p-2 mb-3">
                                <legend class="w-auto small text-secondary">Envío original (cm)</legend>

                                <!-- Largo -->
                                <div class="mb-1">
                                    <label class="form-label small">Largo</label>
                                    <input type="number" id="largoProductoEnvio" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['largoProductoEnvio'] ?>">
                                </div>

                                <!-- Swap Largo ↔ Ancho -->
                                <div class="text-center mb-2">
                                    <button type="button" id="swapLA" class="btn btn-sm btn-outline-secondary">↔ Largo/Ancho</button>
                                </div>

                                <!-- Ancho -->
                                <div class="mb-1">
                                    <label class="form-label small">Ancho</label>
                                    <input type="number" id="anchoProductoEnvio" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['anchoProductoEnvio'] ?>">
                                </div>

                                <!-- Swap Ancho ↔ Alto -->
                                <div class="text-center mb-2">
                                    <button type="button" id="swapAH" class="btn btn-sm btn-outline-secondary">↔ Ancho/Alto</button>
                                </div>

                                <!-- Alto -->
                                <div class="mb-1">
                                    <label class="form-label small">Alto</label>
                                    <input type="number" id="altoProductoEnvio" class="form-control form-control-sm"
                                        step="0.1" min="0" value="<?= $prod['altoProductoEnvio'] ?>">
                                </div>

                            </fieldset>
                        </div>



                        <!-- Calculadora de paquetes -->
                        <div class="col-md-5">
                            <fieldset class="border p-2 mb-3">
                                <legend class="w-auto small text-secondary">Calculadora de paquetes</legend>
                                <div class="mb-2">
                                    <label class="form-label small">Cant. unidades</label>
                                    <input type="number" id="cantidad" class="form-control form-control-sm"
                                        value="1" min="1" step="1">
                                </div>
                                <div style="overflow-x:auto">
                                    <table class="table table-sm table-bordered mb-0" id="packagesTable">
                                        <thead>
                                            <tr>
                                                <th>No Caja</th>
                                                <th>Unidades</th>
                                                <th>Largo</th>
                                                <th>Ancho</th>
                                                <th>Alto</th>
                                                <th>Volumen</th>
                                                <th>Peso</th>
                                                <th>Dibujo</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                        <tfoot>
                                            <tr>
                                                <th colspan="6" class="text-end">Total Cajas:</th>
                                                <th id="totalCajas"></th>
                                                <th></th>
                                            </tr>
                                            <tr>
                                                <th colspan="6" class="text-end">Volumen Total:</th>
                                                <th id="totalVolumen"></th>
                                                <th></th>
                                            </tr>
                                            <tr>
                                                <th colspan="6" class="text-end">Peso Total:</th>
                                                <th id="totalPeso"></th>
                                                <th></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Página Proveedor -->
            <?php if (!empty($product['urlExterna'])): ?>
                <div class="tab-pane fade" id="prov">
                    <div class="mb-2">
                        <button id="refreshProv" class="btn btn-secondary">Refresh</button>
                        <button id="openProv" class="btn btn-secondary">Ver en nueva pestaña</button>
                    </div>
                    <iframe id="iframeProv" src="<?= htmlspecialchars($product['urlExterna']) ?>" class="w-100" style="height:600px;border:1px solid #ddd"></iframe>
                </div>
            <?php endif; ?>

            <!-- Página Compranet -->
            <?php if (!empty($product['wp_id'])): ?>
                <div class="tab-pane fade" id="cmp">
                    <div class="mb-2">
                        <button id="refreshCmp" class="btn btn-secondary">Refresh</button>
                        <button id="openCmp" class="btn btn-secondary">Ver en nueva pestaña</button>
                    </div>
                    <iframe id="iframeCmp" src="https://compranet.com.co/?p=<?= intval($product['wp_id']) ?>" class="w-100" style="height:600px;border:1px solid #ddd"></iframe>
                </div>
            <?php endif; ?>

            <!-- Solo se muestra si NO hay wp_id -->
            <?php if (empty($product['wp_id'])): ?>
                <div class="tab-pane fade" id="importacion">
                    <iframe src="https://sistema.compranet.com.co/conexiones/conexionwp/importacion.php?id=<?= $id ?>"
                        style="width:100%; height:600px; border:none;"></iframe>
                </div>
            <?php endif; ?>
        </div>

        <!-- Pestañas Variaciones, Imágenes, Categorías, Escalas, Características -->
        <ul class="nav nav-tabs mt-4" role="tablist">
            <?php foreach (
                [
                    'variaciones'     => 'Variaciones',
                    'imagenes'        => 'Imágenes',
                    'categorias'      => 'Categorías',
                    'escalas'         => 'Escalas',
                    'caracteristicas' => 'Características',
                    'precio_escala'   => 'Precio Escala Proveedor'

                ] as $k => $lbl
            ): ?>
                <li class="nav-item">
                    <a class="nav-link <?= $k === 'variaciones' ? 'active' : '' ?>"
                        data-toggle="tab" href="#tab-<?= $k ?>"><?= $lbl ?></a>
                </li>
            <?php endforeach; ?>
        </ul>
        <div class="tab-content">
            <div class="tab-pane fade show active" id="tab-variaciones">
                <?php include __DIR__ . '/variacionesproducto.php'; ?>
            </div>
            <div class="tab-pane fade" id="tab-imagenes">
                <?php include __DIR__ . '/imagenesproducto.php'; ?>
            </div>
            <div class="tab-pane fade" id="tab-categorias">
                <?php include __DIR__ . '/categoriasproducto.php'; ?>
            </div>
            <div class="tab-pane fade" id="tab-escalas">
                <?php include __DIR__ . '/escalasproducto.php'; ?>
            </div>
            <div class="tab-pane fade" id="tab-caracteristicas">
                <?php include __DIR__ . '/caracteristicasproducto.php'; ?>
            </div>
            <div class="tab-pane fade" id="tab-precio_escala">
                <?php
                $rEsc = cpn_node_request('GET', $base . '/api/productos/' . urlencode((string)$id) . '/escala-proveedor', $token, null);
                $rows = (!empty($rEsc['ok']) && isset($rEsc['data']['rows']) && is_array($rEsc['data']['rows']))
                    ? $rEsc['data']['rows']
                    : [];
                ?>
                <button id="addEscalaRow" class="btn btn-sm btn-primary mb-2">Agregar fila</button>
                <table class="table table-sm table-bordered">
                    <thead>
                        <tr>
                            <th>Cant. Desde</th>
                            <th>Precio Antes Impuestos</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody id="escalaProveedorBody">
                        <?php foreach ($rows as $r): ?>
                            <tr data-id="<?= $r['id'] ?>">
                                <td><input type="number" class="form-control live-field"
                                        data-field="cantDesde" data-id="<?= $r['id'] ?>"
                                        value="<?= $r['cantDesde'] ?>"></td>
                                <td><input type="number" step="0.01" class="form-control live-field"
                                        data-field="precioAntesImpuestos" data-id="<?= $r['id'] ?>"
                                        value="<?= $r['precioAntesImpuestos'] ?>"></td>
                                <td>
                                    <button class="btn btn-sm btn-danger delete-escala"
                                        data-id="<?= $r['id'] ?>">Eliminar</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

        </div>

        </div>
        </div>

        <!-- Modal imagen ampliada -->
        <div class="modal fade" id="parentImgModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-body p-0">
                        <img src="" id="parentModalImg" class="img-fluid" style="width:100%">
                    </div>
                </div>
            </div>
        </div>

        <!-- Scripts -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
        <script src="../js/sb-admin-2.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

        <script>
            // ——— Actualizar Checklist (procedimiento almacenado) ———
            $(function() {
                $('#btnActualizarChecklist').on('click', function(e) {
                    e.preventDefault(); // por si acaso
                    $.ajax({
                            url: window.location.pathname, // llama al mismo producto.php
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                id: <?= $id ?>,
                                action: 'update_checklist'
                            }
                        })
                        .done(function(res) {
                            if (res.success) {
                                // actualiza sólo el texto
                                $('#checklistInfoText').text(res.checklistInfo);
                            } else {
                                alert('No se pudo actualizar el checklist.');
                            }
                        })
                        .fail(function(xhr, status, err) {
                            console.error(err);
                            alert('Error al comunicarse con el servidor.');
                        });
                });
            });

            // Mostrar imagen en modal
            function showImage(src) {
                $('#parentModalImg').attr('src', src);
                $('#parentImgModal').modal('show');
            }

            // Compat: algunos scripts legacy esperan esta función global.
            // Evita el error "normalizeImageUrl is not defined".
            window.normalizeImageUrl = window.normalizeImageUrl || function(url) {
                let u = (url == null) ? '' : String(url);
                u = u.trim().replace(/^['\"]|['\"]$/g, '');
                if (!u) return '';

                // Protocol-relative
                if (u.startsWith('//')) {
                    u = 'https:' + u;
                }

                // Normaliza espacios típicos de imports
                u = u.replace(/\s/g, '%20');
                return u;
            };

            // Live-save SOLO para el tab Información General
            $('#info').on('change blur', '.live-field', function() {
                const field = $(this).data('field');
                const value = $(this).val();
                $.post('update_producto.php', {
                    id: <?= $id ?>,
                    field: field,
                    value: value
                }, function(res) {
                    if (res && res.status === 'ok') {
                        maybeScheduleWooSync(field);
                    }
                }, 'json');
            });

            const WOO_PUBLISHED = <?= $wooPublished ? 'true' : 'false' ?>;
            const CHECKLIST_OK = <?= $checklistOk ? 'true' : 'false' ?>;
            const ID_PRODUCTO = <?= (int)$id ?>;

            function setWooStatus(text, isError) {
                if (!$('#wooSyncStatus').length) return;
                $('#wooSyncStatus')
                    .text(text || '')
                    .toggleClass('text-danger', Boolean(isError))
                    .toggleClass('text-muted', !isError);
            }

            function wooAutoKey() {
                return 'wooAutoSync_' + ID_PRODUCTO;
            }

            function isWooAutoEnabled() {
                return localStorage.getItem(wooAutoKey()) === '1';
            }

            function setWooAutoEnabled(enabled) {
                localStorage.setItem(wooAutoKey(), enabled ? '1' : '0');
            }

            (function initWooAutoToggle() {
                if (!$('#wooAutoSync').length) return;
                $('#wooAutoSync').prop('checked', isWooAutoEnabled());
                $('#wooAutoSync').on('change', function() {
                    setWooAutoEnabled(this.checked);
                    setWooStatus(this.checked ? 'Auto ON' : 'Auto OFF', false);
                    setTimeout(() => setWooStatus('', false), 1500);
                });
            })();

            let wooSyncTimer = null;

            function maybeScheduleWooSync(changedField) {
                if (!WOO_PUBLISHED) return;
                if (!$('#wooAutoSync').length) return;
                if (!isWooAutoEnabled()) return;

                // Only auto-sync fields that affect the public product content.
                const allowed = new Set([
                    'nombre',
                    'descripcion',
                    'seo_title',
                    'seo_short_desc',
                    'yoast_meta_desc',
                    'seo_keywords'
                ]);
                if (changedField && !allowed.has(String(changedField))) return;

                clearTimeout(wooSyncTimer);
                setWooStatus('Sync programado…', false);
                wooSyncTimer = setTimeout(() => {
                    // Auto-sync: solo contenido (evita sync pesado de inventario en cada cambio)
                    doWooSync(false);
                }, 1500);
            }

            function doWooSync(syncInventory) {
                if (!WOO_PUBLISHED) return;
                setWooStatus('Sincronizando…', false);
                const includeImages = $('#wooIncludeImages').length ? $('#wooIncludeImages').is(':checked') : true;
                return $.ajax({
                        url: window.location.pathname,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'woo_sync',
                            id: ID_PRODUCTO,
                            syncInventory: syncInventory ? 1 : 0,
                            includeImages: includeImages ? 1 : 0,
                            forceImages: includeImages ? 1 : 0
                        }
                    })
                    .done(function(res) {
                        if (res && res.success) {
                            const created = Number(res && res.inventory && res.inventory.createdVariations) || 0;
                            if (created > 0) {
                                setWooStatus('Sincronizado (creadas ' + created + ' variaciones)', false);
                            } else {
                                setWooStatus('Sincronizado', false);
                            }
                            setTimeout(() => setWooStatus('', false), 2500);
                        } else {
                            setWooStatus((res && res.error) ? res.error : 'Error al sincronizar', true);
                        }
                    })
                    .fail(function(xhr) {
                        setWooStatus('Error de red al sincronizar', true);
                        console.error('Woo sync error:', xhr && xhr.responseText);
                    });
            }

            function doWooSyncBackground(syncInventory) {
                if (!WOO_PUBLISHED) return;

                // No bloquear navegación: enviar request y permitir seguir.
                setWooStatus('Sync enviado (segundo plano)…', false);
                const includeImages = $('#wooIncludeImages').length ? $('#wooIncludeImages').is(':checked') : true;

                try {
                    const data = new URLSearchParams();
                    data.set('action', 'woo_sync');
                    data.set('id', String(ID_PRODUCTO));
                    data.set('syncInventory', syncInventory ? '1' : '0');
                    data.set('includeImages', includeImages ? '1' : '0');
                    data.set('forceImages', includeImages ? '1' : '0');
                    data.set('background', '1');

                    // Best effort: intenta sobrevivir navegación.
                    if (navigator && typeof navigator.sendBeacon === 'function') {
                        const ok = navigator.sendBeacon(window.location.pathname, data);
                        if (ok) {
                            setTimeout(() => setWooStatus('Sync en cola… puedes seguir', false), 600);
                            setTimeout(() => setWooStatus('', false), 3500);
                            return;
                        }
                    }

                    fetch(window.location.pathname, {
                        method: 'POST',
                        cache: 'no-store',
                        credentials: 'same-origin',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: data.toString(),
                        keepalive: true
                    }).catch(function() {});

                    setTimeout(() => setWooStatus('Sync en cola… puedes seguir', false), 600);
                    setTimeout(() => setWooStatus('', false), 3500);
                } catch (e) {
                    setWooStatus('No se pudo enviar el sync en segundo plano', true);
                    console.error('Woo sync bg error:', e);
                }
            }

            $('#btnWooSyncNow').on('click', function(e) {
                if (e && e.preventDefault) e.preventDefault();
                if (e && e.stopPropagation) e.stopPropagation();

                // Click normal: segundo plano (no bloquea). Shift+click: esperar respuesta.
                if (e && e.shiftKey) {
                    // Sync manual: incluye inventario/precios para dejar Woo al día.
                    doWooSync(true);
                } else {
                    doWooSyncBackground(true);
                }
            });

            $('#btnWooPublish').on('click', function(e) {
                if (e && e.preventDefault) e.preventDefault();
                if (e && e.stopPropagation) e.stopPropagation();
                if (!CHECKLIST_OK) return;
                if (!confirm('¿Publicar este producto en Woo?')) return;
                const $btn = $(this);
                $btn.prop('disabled', true).text('Publicando…');
                const includeImages = $('#wooIncludeImages').length ? $('#wooIncludeImages').is(':checked') : true;

                $.ajax({
                        url: window.location.pathname,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'woo_publish',
                            id: ID_PRODUCTO,
                            syncInventory: 1,
                            includeImages: includeImages ? 1 : 0,
                            forceImages: includeImages ? 1 : 0
                        }
                    })
                    .done(function(res) {
                        if (res && res.success) {
                            const created = Number(res && res.inventory && res.inventory.createdVariations) || 0;
                            alert(created > 0 ?
                                ('Publicado. Se crearon ' + created + ' variaciones. Recargando…') :
                                'Publicado. Recargando…'
                            );
                            location.reload();
                        } else {
                            alert((res && res.error) ? res.error : 'No se pudo publicar');
                            $btn.prop('disabled', false).text('Publicar en Woo');
                        }
                    })
                    .fail(function(xhr) {
                        console.error('Woo publish error:', xhr && xhr.responseText);
                        alert('Error de red al publicar');
                        $btn.prop('disabled', false).text('Publicar en Woo');
                    });
            });


            // Contador para título
            $('#nombre').on('input', function() {
                const len = this.value.length,
                    max = 60;
                $('#nombreCount').text(len + '/' + max)
                    .toggleClass('ok', len <= max)
                    .toggleClass('exceed', len > max);
            }).trigger('input');

            // Auto–resize de tech-fields y .auto-resize
            $('.tech-field, .auto-resize').each(function() {
                this.style.height = 'auto';
                this.style.height = this.scrollHeight + 'px';
            }).on('input', function() {
                this.style.height = 'auto';
                this.style.height = this.scrollHeight + 'px';
            });

            // Color dinámico de estado
            const estadoColors = {
                1: '#28a745',
                2: '#6c757d',
                3: '#dc3545',
                4: '#6c757d'
            };

            function actualizarColorEstado() {
                const v = $('#idEstado').val(),
                    c = estadoColors[v] || '';
                $('#idEstado').css({
                    'background-color': c,
                    'color': '#fff'
                });
            }
            $(document).ready(function() {
                actualizarColorEstado();
                $('#idEstado').on('change', actualizarColorEstado);

                // Iframes Proveedor y Compranet
                $('#refreshProv').click(() => $('#iframeProv').attr('src', $('#iframeProv').attr('src')));
                $('#openProv').click(() => window.open($('#iframeProv').attr('src'), '_blank'));
                $('#refreshCmp').click(() => $('#iframeCmp').attr('src', $('#iframeCmp').attr('src')));
                $('#openCmp').click(() => window.open($('#iframeCmp').attr('src'), '_blank'));

                // Copiar instrucciones
                function copiar(text) {
                    navigator.clipboard.writeText(text);
                    alert('Copiado');
                }
                $('#copyTitulo').click(function() {
                    copiar([
                        "Envíame 3 opciones de título (≤60 caracteres) para:",
                        "Título actual: " + $('#nombre').val(),
                        "Descripción: " + $('#descripcion').val()
                    ].join("\n"));
                });
                $('#copyDescripcion').click(function() {
                    copiar([
                        "Envíame una descripción para:",
                        "Título: " + $('#nombre').val(),
                        "Descripción actual: " + $('#descripcion').val()
                    ].join("\n"));
                });

                // Inicializar Select2 en categorías
                $('#newCategoria').select2({
                    placeholder: 'Buscar categoría',
                    allowClear: true,
                    width: '100%'
                });
            });

            // ——— Handlers originales para variaciones ———
            $('#tab-variaciones').on('change blur', '.live-field', function() {
                const $el = $(this),
                    idVar = $el.data('id'),
                    field = $el.data('field'),
                    value = $el.val();
                $.post('update_variacion.php', {
                    id: idVar,
                    field,
                    value
                }, function(res) {
                    if (res.status !== 'ok') console.error('Variación error:', res.msg);
                }, 'json');
            });
            $('#tab-variaciones').on('click', '.delete-variant', function() {
                if (!confirm('¿Eliminar esta variante?')) return;
                const idVar = $(this).data('id');
                $.post('delete_variacion.php', {
                    id: idVar
                }, () => {
                    $('#tab-variaciones').find('tr[data-id="' + idVar + '"]').remove();
                });
            });

            // ——— Handlers originales para imágenes ———
            (function() {
                const idProducto = <?= $id ?>;

                function refreshImages() {
                    $('#imagenes-contenedor').load('imagenesproducto.php?id=' + idProducto + ' #imagenes-contenedor > *');
                }
                $('#tab-imagenes').on('submit', '#uploadForm', function(e) {
                    e.preventDefault();
                    const url = $('#urlImagen').val().trim();
                    if (!url) return alert('Por favor ingresa la URL');
                    $.ajax({
                        url: 'https://sistema.compranet.com.co/conexiones/extracciones/guardarimagenmanual.php',
                        data: {
                            idProducto,
                            urlImagen: url
                        }
                    }).always(() => {
                        $('#urlImagen').val('');
                        refreshImages();
                    });
                });
                $('#tab-imagenes').on('click', '.btn-delete-principal', function() {
                    if (!confirm('¿Eliminar imagen principal?')) return;
                    $.post('imagenesproducto.php', {
                        action: 'deletePrincipal',
                        id: $(this).data('id')
                    }, res => res.success && refreshImages(), 'json');
                });
                $('#tab-imagenes').on('click', '.btn-principal', function() {
                    $.post('imagenesproducto.php', {
                        action: 'setPrincipal',
                        id: $(this).data('id'),
                        idProducto
                    }, res => res.success && refreshImages(), 'json');
                });
                let lastCopiedLink = '';
                $('#tab-imagenes').on('click', '.btn-copy', function() {
                    lastCopiedLink = $(this).data('link');
                    navigator.clipboard.writeText(lastCopiedLink);
                    alert('Ruta copiada');
                });
                $('#tab-imagenes').on('click', '.btn-paste-variant', function() {
                    const idVar = $(this).data('id');
                    if (!lastCopiedLink) return alert('Primero copia la ruta con el botón C');
                    $.post('imagenesproducto.php', {
                        action: 'pasteVariant',
                        idVariante: idVar,
                        link: lastCopiedLink
                    }, res => {
                        if (res.success) refreshImages();
                    }, 'json');
                });
                $('#tab-imagenes').on('click', '.btn-delete-variant', function() {
                    if (!confirm('¿Eliminar imágenes de variante?')) return;
                    $.post('imagenesproducto.php', {
                        action: 'deleteVariant',
                        idVariante: $(this).data('id')
                    }, res => res.success && refreshImages(), 'json');
                });
            })();

            // ——— Handlers originales para categorías ———
            $(document).on('click', '#addCategoria', function() {
                var idCat = $('#newCategoria').val();
                if (!idCat) return alert('Selecciona una categoría');
                $.post('categoriasproducto.php?id=<?= $id ?>', {
                    action: 'add',
                    idCategoria: idCat
                }, function(res) {
                    if (res.success) {
                        $('#categorias-contenedor').load('categoriasproducto.php?id=<?= $id ?> #categorias-contenedor > *');
                    }
                }, 'json');
            });
            $('#categorias-contenedor').on('click', '.delete-cat', function() {
                if (!confirm('¿Eliminar esta categoría?')) return;
                var idCat = $(this).closest('tr').data('idcategoria');
                $.post('categoriasproducto.php?id=<?= $id ?>', {
                    action: 'delete',
                    idCategoria: idCat
                }, function(res) {
                    if (res.success) {
                        $('#categorias-contenedor').load('categoriasproducto.php?id=<?= $id ?> #categorias-contenedor > *');
                    }
                }, 'json');
            });

            // ——— Handlers para características (tab) ———
            (function() {
                const idProducto = <?= $id ?>;

                function initSelect2Caracteristicas() {
                    if (!$('#newCaracteristica').length) return;
                    $('#newCaracteristica').addClass('select2-dark');
                    $('#newCaracteristica').select2({
                        placeholder: 'Buscar característica',
                        allowClear: true,
                        width: '100%'
                    });
                }

                function refreshCaracteristicas() {
                    $('#caracteristicas-contenedor').load('caracteristicasproducto.php?id=' + idProducto + ' #caracteristicas-contenedor > *', function() {
                        initSelect2Caracteristicas();
                    });
                }

                $(document).ready(function() {
                    initSelect2Caracteristicas();
                });

                $('#tab-caracteristicas').on('click', '#addCaracteristica', function() {
                    const idCaracteristica = $('#newCaracteristica').val();
                    const valor = ($('#newValorCaracteristica').val() || '').trim();
                    if (!idCaracteristica) return alert('Selecciona una característica');

                    ajaxUpdate(
                        'update_caracteristica.php', {
                            action: 'add',
                            idProducto: idProducto,
                            idCaracteristica: idCaracteristica,
                            valor: valor
                        },
                        function() {
                            refreshCaracteristicas();
                        },
                        false
                    );
                });

                $('#tab-caracteristicas').on('click', '.delete-char', function() {
                    if (!confirm('¿Eliminar esta característica?')) return;
                    const $tr = $(this).closest('tr');
                    const cid = parseInt($tr.attr('data-char-id'), 10);
                    if (!cid) return;

                    ajaxUpdate(
                        'update_caracteristica.php', {
                            action: 'delete',
                            id: cid
                        },
                        function() {
                            $tr.remove();
                        },
                        false
                    );
                });
            })();

            // ——— Iframe actions ———
            $('#btnActImgs').on('click', function() {
                $('#iframeAct').attr('src', 'https://sistema.compranet.com.co/conexiones/conexionwp/actualizarimageneswp.php?id=<?= $id ?>');
                $('#frameContainer').slideDown();
            });
            $('#btnReemImgs').on('click', function() {
                $('#iframeAct').attr('src', 'https://sistema.compranet.com.co/conexiones/conexionwp/actualizarimageneswp.php?id=<?= $id ?>&force=1');
                $('#frameContainer').slideDown();
            });
            $('#btnActCats').on('click', function() {
                $('#iframeAct').attr('src', 'https://sistema.compranet.com.co/conexiones/conexionwp/actualizarcategorias.php?id=<?= $id ?>');
                $('#frameContainer').slideDown();
            });
            $('#btnActDesc').on('click', function() {
                $('#iframeAct').attr('src', 'https://sistema.compranet.com.co/conexiones/conexionwp/actualizardescripcioneswp.php?id=<?= $id ?>');
                $('#frameContainer').slideDown();
            });
            $('#btnActVar').on('click', function() {
                $('#iframeAct').attr('src', 'https://sistema.compranet.com.co/conexiones/conexionwp/actualizarvariaciones.php?id=<?= $id ?>');
                $('#frameContainer').slideDown();
            });
            $('#btnReemVar').on('click', function() {
                $('#iframeAct').attr('src', 'https://sistema.compranet.com.co/conexiones/conexionwp/actualizarvariaciones.php?id=<?= $id ?>&force=1');
                $('#frameContainer').slideDown();
            });

            // — Datos iniciales desde PHP —
            const datos = <?= json_encode([
                                'largoCaja'               => (float)$prod['largoCmCaja'],
                                'anchoCaja'               => (float)$prod['anchoCmCaja'],
                                'altoCaja'                => (float)$prod['altoCmCaja'],
                                'unds'                    => max(1, (int)$prod['undsCaja']),
                                'pesoReal'                => (float)$prod['pesoKgProducto'],
                                'largo'                   => (float)$prod['largoProductoEnvioAjustado'],
                                'ancho'                   => (float)$prod['anchoProductoEnvioAjustado'],
                                'alto'                    => (float)$prod['altoProductoEnvioAjustado'],
                                'volumenUnidad'           => (float)$prod['volumenCm3ProductoAjustado'],
                                'pesoVolumetricoProducto' => (float)$prod['pesoVolumetricoProducto'],
                                'pesoEnvioUnidadKG'       => (float)$prod['pesoEnvioUnidadKG'],
                                'acomodacion'             => $prod['acomodacion']
                            ], JSON_NUMERIC_CHECK) ?>;

            // — Función AJAX genérica —
            /**
             * Función AJAX genérica.
             * @param {string} url      — URL de endpoint.
             * @param {object} data     — Objeto con los campos a enviar.
             * @param {function} onDone — Callback a ejecutar si todo OK.
             * @param {boolean} isProd  — true si es update_producto.php (inyecta idProducto), false si no.
             */
            function ajaxUpdate(url, data, onDone, isProd = true) {
                if (isProd) {
                    // sólo inyectamos aquí el id del producto
                    data.id = <?= $id ?>;
                }
                $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType: 'json'
                    })
                    .done(function(res) {
                        if (res.ok) {
                            if (typeof onDone === 'function') onDone();
                        } else {
                            alert('Error al guardar: ' + formatAjaxError(res));
                        }
                    })
                    .fail(function(xhr, status, err) {
                        console.error('AJAX Error:', status, err, xhr.responseText);
                        alert('Error de red al guardar');
                    });
            }

            function formatAjaxError(res) {
                if (!res) return 'respuesta inválida';

                // Common PHP shape: { ok:false, error:"..." }
                if (typeof res.error === 'string' && res.error) return res.error;

                // Common Node shape: { ok:false, error:{ message, details } }
                var message = (res.error && res.error.message) ? res.error.message : '';
                var details = (res.error && res.error.details) ? res.error.details : null;

                if (message && !details) return message;

                // Prefer first field error, if present
                try {
                    if (details && details.fieldErrors) {
                        for (var key in details.fieldErrors) {
                            if (!Object.prototype.hasOwnProperty.call(details.fieldErrors, key)) continue;
                            var arr = details.fieldErrors[key];
                            if (arr && arr.length) {
                                return (message ? message : 'Validation error') + "\n" + key + ': ' + arr[0];
                            }
                        }
                    }
                } catch (e) {}

                return message || (res.error ? String(res.error) : 'respuesta inválida');
            }


            // — Dibuja la caja pequeña + interior 1 und —
            function drawBoxSmall() {
                const cv = document.getElementById('boxCanvasSmall'),
                    ctx = cv.getContext('2d');
                ctx.clearRect(0, 0, cv.width, cv.height);

                // escala
                const iso = (x, y, z) => ({
                        x: x - y,
                        y: (x + y) / 2 - z
                    }),
                    maxD = Math.max(datos.largoCaja, datos.anchoCaja, datos.altoCaja),
                    s = Math.min((cv.height * 0.5) / maxD, (cv.width * 0.5) / maxD),
                    Lc = datos.largoCaja * s,
                    Ac = datos.anchoCaja * s,
                    Hc = datos.altoCaja * s;

                // vértices exterior
                let [A, B, C, D, E, F, G, H] = [
                    iso(0, 0, 0), iso(Lc, 0, 0), iso(Lc, Ac, 0), iso(0, Ac, 0),
                    iso(0, 0, Hc), iso(Lc, 0, Hc), iso(Lc, Ac, Hc), iso(0, Ac, Hc)
                ];
                const pts = [A, B, C, D, E, F, G, H],
                    xs = pts.map(p => p.x),
                    ys = pts.map(p => p.y),
                    offX = (cv.width - (Math.max(...xs) - Math.min(...xs))) / 2 - Math.min(...xs),
                    offY = (cv.height - (Math.max(...ys) - Math.min(...ys))) / 2 + Math.max(...ys),
                    mv = p => [p.x + offX, offY - p.y];

                // dibujar exterior
                ctx.strokeStyle = '#444';
                ctx.fillStyle = 'rgba(173,216,230,0.15)';
                [
                    [A, B, C, D],
                    [E, F, G, H],
                    [A, E, H, D],
                    [B, F, G, C]
                ].forEach((face, i) => {
                    ctx.beginPath();
                    face.map(mv).forEach((pt, j) => j ? ctx.lineTo(...pt) : ctx.moveTo(...pt));
                    ctx.closePath();
                    ctx.stroke();
                    if (i === 0) ctx.fill();
                });

                // dibujar 1 unidad interior
                drawPackage(cv, 1);
            }

            // — Dibuja un paquete dentro de cualquier canvas —
            function drawPackage(canvas, units) {
                const iso = (x, y, z) => ({
                        x: x - y,
                        y: (x + y) / 2 - z
                    }),
                    [n1, n2, n3] = datos.acomodacion.split('x').map(Number),
                    ctx = canvas.getContext('2d'),
                    maxD = Math.max(datos.largoCaja, datos.anchoCaja, datos.altoCaja),
                    s = Math.min((canvas.height * 0.4) / maxD, (canvas.width * 0.4) / maxD),
                    Lc = datos.largoCaja * s,
                    Ac = datos.anchoCaja * s,
                    Hc = datos.altoCaja * s;
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                let [A, B, C, D, E, F, G, H] = [
                    iso(0, 0, 0), iso(Lc, 0, 0), iso(Lc, Ac, 0), iso(0, Ac, 0),
                    iso(0, 0, Hc), iso(Lc, 0, Hc), iso(Lc, Ac, Hc), iso(0, Ac, Hc)
                ];
                const pts = [A, B, C, D, E, F, G, H],
                    xs = pts.map(p => p.x),
                    ys = pts.map(p => p.y),
                    offX = (canvas.width - (Math.max(...xs) - Math.min(...xs))) / 2 - Math.min(...xs),
                    offY = (canvas.height - (Math.max(...ys) - Math.min(...ys))) / 2 + Math.max(...ys),
                    mv = p => [p.x + offX, offY - p.y];

                // exterior
                ctx.strokeStyle = '#444';
                ctx.fillStyle = 'rgba(173,216,230,0.1)';
                [
                    [A, B, C, D],
                    [E, F, G, H],
                    [A, E, H, D],
                    [B, F, G, C]
                ].forEach(face => {
                    ctx.beginPath();
                    face.map(mv).forEach((pt, i) => i ? ctx.lineTo(...pt) : ctx.moveTo(...pt));
                    ctx.closePath();
                    ctx.stroke();
                });

                // interior units
                const uL = datos.largo * s,
                    uA = datos.ancho * s,
                    uH = datos.alto * s,
                    zSh = (datos.altoCaja - datos.alto) * s;
                let drawn = 0;
                for (let z = 0; z < n3 && drawn < units; z++) {
                    for (let y = 0; y < n2 && drawn < units; y++) {
                        for (let x = 0; x < n1 && drawn < units; x++) {
                            drawn++;
                            const P = iso(x * uL, y * uA, z * uH + zSh),
                                Q = iso((x + 1) * uL, y * uA, z * uH + zSh),
                                R = iso((x + 1) * uL, (y + 1) * uA, z * uH + zSh),
                                S = iso(x * uL, (y + 1) * uA, z * uH + zSh),
                                U = iso(x * uL, y * uA, z * uH + uH + zSh),
                                V = iso((x + 1) * uL, y * uA, z * uH + uH + zSh),
                                W = iso((x + 1) * uL, (y + 1) * uA, z * uH + uH + zSh),
                                X = iso(x * uL, (y + 1) * uA, z * uH + uH + zSh);
                            ctx.strokeStyle = '#c00';
                            ctx.fillStyle = 'rgba(232,62,140,0.6)';
                            [
                                [P, Q, R, S],
                                [U, V, W, X],
                                [P, U, X, S],
                                [Q, V, W, R]
                            ].forEach(face => {
                                ctx.beginPath();
                                face.map(mv).forEach((pt, i) => i ? ctx.lineTo(...pt) : ctx.moveTo(...pt));
                                ctx.closePath();
                                ctx.stroke();
                                ctx.fill();
                            });
                        }
                    }
                }
                if (units === datos.unds) {
                    ctx.font = '12px sans-serif';
                    ctx.fillStyle = 'rgba(0,0,0,0.5)';
                    ctx.fillText('×1', 5, 12);
                }
            }

            // — Genera la tabla de paquetes —
            function recalcPackages() {
                const cnt = parseInt($('#cantidad').val(), 10) || 1,
                    perBox = datos.unds,
                    full = Math.floor(cnt / perBox),
                    rem = cnt % perBox,
                    $tb = $('#packagesTable tbody');
                let totalVol = 0,
                    totalPeso = 0,
                    cajaNo = 1;

                $tb.empty();

                function addRow(units) {
                    // 1) Si está completa, usamos dimensiones de caja entera
                    let boxL, boxA, boxH;
                    if (units === perBox) {
                        boxL = datos.largoCaja;
                        boxA = datos.anchoCaja;
                        boxH = datos.altoCaja;
                    } else {
                        // 2) paquete parcial: respetar la acomodación máxima (n1 x n2 x n3)
                        const parts = String(datos.acomodacion || '').split('x').map(Number);
                        const n1 = Math.max(1, parts[0] || 1);
                        const n2 = Math.max(1, parts[1] || 1);
                        const n3 = Math.max(1, parts[2] || 1);

                        const xCount = Math.min(n1, units);
                        const yCount = Math.min(n2, Math.ceil(units / xCount));
                        const zCount = Math.min(n3, Math.max(1, Math.ceil(units / (xCount * yCount))));

                        boxL = xCount * datos.largo;
                        boxA = yCount * datos.ancho;
                        boxH = zCount * datos.alto;
                    }

                    // Volumétrico por caja (kg)
                    const vol = +((boxL * boxA * boxH) / 5000).toFixed(4);

                    // Real por caja (kg): viene de pesoKgCaja/undsCaja (o lo que tengas cargado ahí)
                    const pesoRealCaja = +(units * (Number(datos.pesoReal) || 0)).toFixed(4);

                    // Peso cobrado por caja (kg)
                    const peso = +Math.max(pesoRealCaja, vol).toFixed(4);

                    totalVol += vol;
                    totalPeso += peso;

                    const $tr = $(`
        <tr>
            <td>${cajaNo}</td>
            <td>${units}</td>
            <td>${boxL.toFixed(1)}</td>
            <td>${boxA.toFixed(1)}</td>
            <td>${boxH.toFixed(1)}</td>
            <td>${vol}</td>
            <td>${peso}</td>
            <td><canvas width="120" height="80"></canvas></td>
        </tr>
        `);
                    $tb.append($tr);
                    drawPackage($tr.find('canvas')[0], units);
                    cajaNo++;
                }

                // filas completas
                for (let i = 0; i < full; i++) addRow(perBox);
                // fila parcial
                if (rem > 0) addRow(rem);

                $('#totalCajas').text(cajaNo - 1);
                $('#totalVolumen').text(totalVol.toFixed(1));
                $('#totalPeso').text(totalPeso.toFixed(1));
            }


            // — Redibuja todo —
            function recalcUI() {
                const volCaja = +(datos.largoCaja * datos.anchoCaja * datos.altoCaja).toFixed(4);
                $('#volumenCaja').text(volCaja);
                $('#revVolCaja').text(volCaja);

                const volUni = +(datos.largo * datos.ancho * datos.alto).toFixed(4);
                $('#revVolCal').text(volUni);

                const volTotal = +(volUni * datos.unds).toFixed(1);
                // Diferencia (cm³): positivo = espacio libre; negativo = no cabe
                const diff = +(volCaja - volTotal).toFixed(4)
                $('#revDiferencia')
                    .text(diff)
                    .toggleClass('text-success', diff >= 0)
                    .toggleClass('text-danger', diff < 0);

                // 2) pesos
                // 2) pesos
                const pesoVol = +((volUni / 5000).toFixed(4));
                datos.pesoVolumetricoProducto = pesoVol;
                $('#pesoVolumetricoProducto').text(pesoVol.toFixed(4));

                const pesoEnv = +(Math.max(datos.pesoReal, pesoVol).toFixed(4));
                datos.pesoEnvioUnidadKG = pesoEnv;
                $('#pesoEnvioUnidadKG').text(pesoEnv.toFixed(4));

                // etiqueta condicional:
                const metodo = (pesoEnv === datos.pesoReal) ?
                    ' (Envio por Peso)' :
                    ' (Envio por Volumen)';
                $('#envioMetodo').text(metodo);


                drawBoxSmall();
                recalcPackages();
            }

            let recalcPackagesTimer = null;

            function scheduleRecalcPackages() {
                clearTimeout(recalcPackagesTimer);
                recalcPackagesTimer = setTimeout(recalcPackages, 80);
            }

            $(function() {
                // live-edit producto
                $('#largoCmCaja, #anchoCmCaja, #altoCmCaja, #undsCaja, #pesoKgCaja')
                    .on('change', function() {
                        datos.largoCaja = parseFloat($('#largoCmCaja').val()) || 0;
                        datos.anchoCaja = parseFloat($('#anchoCmCaja').val()) || 0;
                        datos.altoCaja = parseFloat($('#altoCmCaja').val()) || 0;
                        datos.unds = parseInt($('#undsCaja').val(), 10) || 1;

                        if (!datos.unds || datos.unds <= 0) {
                            console.warn('undsCaja inválido, usando 1 en su lugar');
                            datos.unds = 1;
                        }

                        // recalcula peso real por unidad = pesoKgCaja / undsCaja
                        let pCaja = parseFloat($('#pesoKgCaja').val()) || 0;
                        datos.pesoReal = pCaja / datos.unds;
                        $('#pesoReal').text(datos.pesoReal.toFixed(4));
                        ajaxUpdate('update_producto_envio.php', {
                            largoCmCaja: $('#largoCmCaja').val(),
                            anchoCmCaja: $('#anchoCmCaja').val(),
                            altoCmCaja: $('#altoCmCaja').val(),
                            undsCaja: $('#undsCaja').val(),
                            pesoKgCaja: $('#pesoKgCaja').val()
                        }, recalcUI);
                    });


                // live-edit: dimensiones ajustadas de la unidad
                $('#largoProductoEnvioAjustado, #anchoProductoEnvioAjustado, #altoProductoEnvioAjustado').on('change', function() {
                    datos.largo = parseFloat($('#largoProductoEnvioAjustado').val()) || 0;
                    datos.ancho = parseFloat($('#anchoProductoEnvioAjustado').val()) || 0;
                    datos.alto = parseFloat($('#altoProductoEnvioAjustado').val()) || 0;

                    // mandamos también unidades y peso de caja
                    ajaxUpdate('update_producto_envio.php', {
                        largoProductoEnvioAjustado: $('#largoProductoEnvioAjustado').val(),
                        anchoProductoEnvioAjustado: $('#anchoProductoEnvioAjustado').val(),
                        altoProductoEnvioAjustado: $('#altoProductoEnvioAjustado').val(),
                        undsCaja: $('#undsCaja').val(),
                        pesoKgCaja: $('#pesoKgCaja').val()
                    }, recalcUI);
                });

                // live-edit: envío original
                $('#largoProductoEnvio, #anchoProductoEnvio, #altoProductoEnvio').on('change', function() {
                    ajaxUpdate('update_producto_envio.php', {
                        largoProductoEnvio: $('#largoProductoEnvio').val(),
                        anchoProductoEnvio: $('#anchoProductoEnvio').val(),
                        altoProductoEnvio: $('#altoProductoEnvio').val()
                    }, function() {
                        recalcUI();
                    });
                });

                // botones de swap
                // swap valores, sin reordenar DOM
                // swap Largo↔Ancho
                $('#swapLA').on('click', function() {
                    const l = $('#largoProductoEnvio').val();
                    const a = $('#anchoProductoEnvio').val();

                    // intercambia y dispara el change para que tu live-edit haga AJAX
                    $('#largoProductoEnvio').val(a).trigger('change');
                    $('#anchoProductoEnvio').val(l).trigger('change');

                    // luego redimensiona y recarga
                    $('#btnRedimensionar').click();
                    setTimeout(() => location.reload(), 500);
                });

                // swap Ancho↔Alto
                $('#swapAH').on('click', function() {
                    const a = $('#anchoProductoEnvio').val();
                    const h = $('#altoProductoEnvio').val();

                    $('#anchoProductoEnvio').val(h).trigger('change');
                    $('#altoProductoEnvio').val(a).trigger('change');

                    $('#btnRedimensionar').click();
                    setTimeout(() => location.reload(), 500);
                });





                // txtMedidas / txtEmpaque
                $('#txtMedidas,#txtEmpaque').on('change', function() {
                    ajaxUpdate('update_producto_envio.php', {
                        txtMedidas: $('#txtMedidas').val(),
                        txtEmpaque: $('#txtEmpaque').val()
                    }, () => {});
                });

                // Redimensionar button: AJAX then refresh
                $('#btnRedimensionar').on('click', function() {
                    $.getJSON('dimensiones_envios.php', {
                            id: <?= $id ?>
                        })
                        .done(function(resp) {
                            if (resp && resp.ok) {
                                setTimeout(() => location.reload(), 500);
                                return;
                            }
                            const msg = (resp && resp.error) ? resp.error : 'No se pudo redimensionar';
                            alert(msg);
                        })
                        .fail(function(xhr) {
                            console.error('Redimensionar error:', xhr && xhr.responseText);
                            alert('Error al redimensionar (respuesta inválida)');
                        });
                });

                // Características live-edit (delegado para funcionar tras .load)
                $(document).on('change', '.selChar, .valChar', function() {
                    const $tr = $(this).closest('tr');
                    const cid = parseInt($tr.attr('data-char-id'), 10);
                    const newC = $tr.find('.selChar').val();
                    const newV = $tr.find('.valChar').val();

                    ajaxUpdate(
                        'update_caracteristica.php', {
                            id: cid, // id de tb_caracteristicas_productos
                            idCaracteristica: newC,
                            valor: newV
                        },
                        () => {
                            console.log('Característica actualizada');
                        },
                        false // ¡IMPORTANTE! no inyectar aquí idProducto
                    );
                });

                // Características: agregar / eliminar + select2
                (function() {
                    const idProducto = <?= $id ?>;

                    function initSelect2Caracteristicas() {
                        if (!$('#newCaracteristica').length) return;
                        $('#newCaracteristica').addClass('select2-dark');
                        if ($.fn.select2) {
                            $('#newCaracteristica').select2({
                                placeholder: 'Buscar característica',
                                allowClear: true,
                                width: '100%'
                            });
                        }
                    }

                    function refreshCaracteristicas() {
                        $('#caracteristicas-contenedor').load(
                            'caracteristicasproducto.php?id=' + idProducto + ' #caracteristicas-contenedor > *',
                            function() {
                                initSelect2Caracteristicas();
                            }
                        );
                    }

                    $(document).ready(function() {
                        initSelect2Caracteristicas();
                    });

                    $('#tab-caracteristicas').on('click', '#addCaracteristica', function() {
                        const idCaracteristica = $('#newCaracteristica').val();
                        const valor = ($('#newValorCaracteristica').val() || '').trim();
                        if (!idCaracteristica) return alert('Selecciona una característica');

                        ajaxUpdate(
                            'update_caracteristica.php', {
                                action: 'add',
                                idProducto: idProducto,
                                idCaracteristica: idCaracteristica,
                                valor: valor
                            },
                            function() {
                                refreshCaracteristicas();
                            },
                            false
                        );
                    });

                    $('#tab-caracteristicas').on('click', '.delete-char', function() {
                        if (!confirm('¿Eliminar esta característica?')) return;
                        const $tr = $(this).closest('tr');
                        const cid = parseInt($tr.attr('data-char-id'), 10);
                        if (!cid) return;

                        ajaxUpdate(
                            'update_caracteristica.php', {
                                action: 'delete',
                                id: cid
                            },
                            function() {
                                $tr.remove();
                            },
                            false
                        );
                    });
                })();

                // paquetes (debounced para que sea ágil al teclear)
                $('#cantidad').on('input', scheduleRecalcPackages);

                // inicial
                recalcUI();
            });

            // ——— Precio Escala Proveedor ———
            $('#tab-precio_escala').on('change blur', '.live-field', function() {
                const rowId = $(this).data('id'),
                    field = $(this).data('field'),
                    value = $(this).val();
                $.post('update_producto_escala.php', {
                    id: rowId,
                    field: field,
                    value: value
                }, function(res) {
                    if (res.status !== 'ok') console.error('Escala error:', res.msg);
                }, 'json');
            });

            $('#addEscalaRow').click(function() {
                $.post('update_producto_escala.php', {
                    action: 'add',
                    idProducto: <?= $id ?>
                }, function(res) {
                    if (res.status === 'ok') {
                        // marcamos la pestaña en el hash para que al recargar sepamos cuál abrir
                        window.location.hash = '#tab-precio_escala';
                        location.reload();
                    } else alert('Error al agregar');
                }, 'json');
            });

            $('#tab-precio_escala').on('click', '.delete-escala', function() {
                const rowId = $(this).data('id');
                if (!confirm('¿Eliminar esta fila?')) return;
                $.post('update_producto_escala.php', {
                    action: 'delete',
                    id: rowId
                }, function(res) {
                    if (res.status === 'ok') $('tr[data-id="' + rowId + '"]').remove();
                    else alert('Error al eliminar');
                }, 'json');
            });
            // Mantener pestaña activa tras reload
            $(function() {
                // si la URL trae un hash, abrimos esa pestaña
                var h = window.location.hash;
                if (h) {
                    $('.nav-tabs a[href="' + h + '"]').tab('show');
                }
                // y cada vez que el usuario cambie de pestaña, actualizamos el hash
                $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
                    window.location.hash = e.target.hash;
                });
            });
        </script>
        <?php include '../templates/footer.php'; ?>
