            <?php
            if (session_status() !== PHP_SESSION_ACTIVE) {
                session_start();
            }
            require_once __DIR__ . '/../includes/session_control.php';
            require_once __DIR__ . '/../cotizaciones/api/_node.php';

            /**
             * Devuelve "#000" o "#fff" según contraste con $hex
             */
            function getTextColor(string $hex): string
            {
                $h = ltrim($hex, '#');
                $r = hexdec(substr($h, 0, 2));
                $g = hexdec(substr($h, 2, 2));
                $b = hexdec(substr($h, 4, 2));
                $lum = ($r * 0.299 + $g * 0.587 + $b * 0.114) / 255;
                return $lum > 0.5 ? '#000000' : '#ffffff';
            }

            // ID de la venta
            $idVenta = isset($_GET['id']) ? intval($_GET['id']) : 0;
            if (!$idVenta) {
                die('ID de venta inválido');
            }

            // AJAX: actualizar campos en tb_ventas
            if (isset($_POST['action']) && $_POST['action'] === 'update_field') {
                $field = $_POST['field'];
                $value = $_POST['value'];
                $allowed = ['refExt', 'idEstado', 'idTipoVenta', 'idMedioVenta', 'idUsuario', 'fechaOrden', 'observaciones', 'idEmpresa'];
                if (in_array($field, $allowed, true)) {
                    $token = cpn_node_token_or_fail();
                    $base = cpn_node_api_base();
                    $url = $base . '/api/ventas/ordenes/' . urlencode((string)$idVenta);
                    $r = cpn_node_request('PATCH', $url, $token, ['field' => $field, 'value' => $value]);
                    if (!isset($r['ok']) || $r['ok'] !== true) {
                        http_response_code($r['_http'] ?? 500);
                        $msg = $r['error']['message'] ?? 'Error actualizando venta.';
                        echo json_encode(['success' => false, 'error' => $msg]);
                        exit;
                    }
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Campo no permitido']);
                }
                exit;
            }

            $token = cpn_node_token_or_fail();
            $base = cpn_node_api_base();

            $ventaResp = cpn_node_request('GET', $base . '/api/ventas/ordenes/' . urlencode((string)$idVenta), $token);
            if (!isset($ventaResp['ok']) || $ventaResp['ok'] !== true) {
                http_response_code($ventaResp['_http'] ?? 500);
                die('Error consultando venta en Node');
            }
            $venta = $ventaResp['data'] ?? null;
            if (!is_array($venta)) {
                http_response_code(500);
                die('Venta inválida');
            }

            $metaResp = cpn_node_request('GET', $base . '/api/ventas/meta', $token);
            if (!isset($metaResp['ok']) || $metaResp['ok'] !== true) {
                http_response_code($metaResp['_http'] ?? 500);
                die('Error consultando meta en Node');
            }
            $meta = $metaResp['data'] ?? [];

            $estados = $meta['estados'] ?? [];
            $tipos = $meta['tipos'] ?? [];
            $medios = $meta['medios'] ?? [];
            $empresas = $meta['empresas'] ?? [];
            $allServiceTypes = $meta['serviciosTipo'] ?? [];

            ?>
            <?php include '../templates/header.php'; ?>

            <div class="venta-container">
                <h1 class="h3 mb-4 text-gray-800">Venta No. <?= $idVenta ?></h1>

                <ul class="nav nav-tabs" id="ventaTabs" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="tab" href="#general">Información General</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#envios">Envíos</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#facturas">Facturas</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#estados">Estados</a>
                    </li>
                    <?php if ($venta['idTipoVenta'] == 2): ?>
                        <li class="nav-item">
                            <a class="nav-link" data-bs-toggle="tab" href="#impresion">Impresión</a>
                        </li>
                    <?php endif; ?>
                </ul>
                <div class="tab-content mt-3">
                    <div class="tab-pane fade show active" id="general">
                        <div class="row">
                            <div class="col-12">
                                <!-- Usuario -->
                                <div id="usuario-info" class="mb-3">
                                    <h2 class="d-inline"><?= htmlspecialchars("{$venta['nombre']} {$venta['apellido']}") ?></h2>
                                    <small class="text-muted ml-2">
                                        (<?= htmlspecialchars("{$venta['Ciudad']} — {$venta['Departamento']}") ?>)
                                    </small>
                                    <p class="mt-1">
                                        <small><?= htmlspecialchars($venta['email']) ?> &bull; <?= htmlspecialchars($venta['telefono']) ?></small>
                                        <button id="editUserBtn" class="btn btn-sm btn-primary ml-3">Editar Usuario</button>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="row align-items-start">
                            <div class="col-lg-9">
                                <!-- Selectores -->
                                <div class="row mb-3">
                                    <div class="form-group col">
                                        <label for="inpFecha">Fecha</label>
                                        <input type="date" id="inpFecha" name="fechaOrden" class="form-control"
                                            value="<?= date('Y-m-d', strtotime($venta['fechaOrden'])) ?>">
                                    </div>
                                    <div class="form-group col">
                                        <label for="inpRefExt">Ref Ext.</label>
                                        <input type="text" id="inpRefExt" name="refExt" class="form-control"
                                            value="<?= htmlspecialchars($venta['refExt']) ?>">
                                    </div>
                                    <div class="form-group col">
                                        <label>Estado</label>
                                        <select id="selEstado" name="idEstado" class="form-control"
                                            style="background-color:<?= $venta['estadoColor'] ?>;
                               color:<?= getTextColor($venta['estadoColor']) ?>;">
                                            <?php foreach ($estados as $e): ?>
                                                <option value="<?= $e['id'] ?>" <?= $e['id'] == $venta['idEstado'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($e['estado']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <!-- ======== Nuevo SELECT “Empresa” ======== -->
                                    <div class="form-group col">
                                        <label>Empresa</label>
                                        <select id="selEmpresa" name="idEmpresa" class="form-control">
                                            <option value="">Sin asignar</option>
                                            <?php foreach ($empresas as $emp): ?>
                                                <option
                                                    value="<?= $emp['id'] ?>"
                                                    <?= $emp['id'] == $venta['idEmpresa'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($emp['sigla']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label>Tipo</label>
                                        <select id="selTipo" name="idTipoVenta" class="form-control"
                                            style="background-color:<?= $venta['tipoColor'] ?>;
                               color:<?= getTextColor($venta['tipoColor']) ?>;">
                                            <?php foreach ($tipos as $t): ?>
                                                <option value="<?= $t['id'] ?>" <?= $t['id'] == $venta['idTipoVenta'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($t['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label>Medio</label>
                                        <select id="selMedio" name="idMedioVenta" class="form-control"
                                            style="background-color:<?= $venta['medioColor'] ?>;
                               color:<?= getTextColor($venta['medioColor']) ?>;">
                                            <?php foreach ($medios as $m): ?>
                                                <option value="<?= $m['id'] ?>" <?= $m['id'] == $venta['idMedioVenta'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($m['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group mb-3">
                                    <label for="obsInput">Observaciones</label>
                                    <textarea id="obsInput" class="form-control" rows="2"><?= htmlspecialchars((string)($venta['observaciones'] ?? '')) ?></textarea>
                                </div>
                            </div>

                            <!-- Resumen a la derecha (como cotizaciones) -->
                            <div class="col-lg-3">
                                <div id="resumen-container">
                                    <?php include __DIR__ . '/ventas_resumen.php'; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Detalle (full width) -->
                        <div class="row">
                            <div class="col-12">
                                <div id="detalle-container">
                                    <?php include __DIR__ . '/venta_detalle.php'; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Envíos -->
                    <div class="tab-pane fade" id="envios">
                        <?php include __DIR__ . '/ventas_envios.php'; ?>
                    </div>

                    <!-- Facturas -->
                    <div class="tab-pane fade" id="facturas">
                        <?php include __DIR__ . '/ventas_facturas.php'; ?>
                    </div>

                    <!-- Estados -->
                    <div class="tab-pane fade" id="estados">
                        <?php include __DIR__ . '/ventas_estados.php'; ?>
                    </div>

                    <!-- Impresión -->
                    <?php if ($venta['idTipoVenta'] == 2): ?>
                        <div class="tab-pane fade" id="impresion">
                            <?php
                            $_GET['idVenta'] = $idVenta;
                            include __DIR__ . '/../marcacion/trabajos.php';
                            ?>
                        </div>
                    <?php endif; ?>
                </div> <!-- CIERRE de .tab-content -->
            </div> <!-- CIERRE de .venta-container -->
            <!-- Modal Usuario -->



            <div class="modal fade" id="userModal" tabindex="-1">
                <div class="modal-dialog modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Seleccionar Usuario</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <select id="userSelect" style="width:100%;"></select>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                            <button id="btnActualizarUsuario" class="btn btn-primary">Actualizar</button>
                        </div>

                    </div>
                </div>
            </div>
            <!-- Modal Servicios -->
            <div class="modal fade" id="serviceModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Servicios</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <input type="hidden" id="srvDetalleId">
                            <table class="table table-sm mb-3">
                                <thead>
                                    <tr>
                                        <th>Tipo</th>
                                        <th>Nombre</th>
                                        <th class="text-end">Precio</th>
                                        <th>Obs</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody id="srvList"></tbody>
                            </table>
                            <!-- formulario -->
                            <select id="srvTipo" class="form-select mb-2">
                                <option value="">Seleccione...</option>
                                <?php foreach ($allServiceTypes as $st): ?>
                                    <option value="<?= $st['id'] ?>"><?= htmlspecialchars($st['nombreCol']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <input id="srvNombre" class="form-control mb-2" placeholder="Nombre">
                            <input id="srvPrecio" type="number" class="form-control mb-2" placeholder="Precio">
                            <input id="srvObservaciones" class="form-control mb-2" placeholder="Observaciones">
                        </div>
                        <div class="modal-footer">
                            <button id="closeSrv" class="btn btn-secondary">Cerrar</button>
                            <button id="saveSrv" class="btn btn-primary">Guardar</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Pagos -->
            <div class="modal fade" id="modalPagos" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content p-3">
                        <h5>Editar Pagos</h5>
                        <table class="table table-sm mb-3">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Tipo</th>
                                    <th>Medio</th>
                                    <th>Ref</th>
                                    <th class="text-end">Valor</th>
                                    <th>×</th>
                                </tr>
                            </thead>
                            <tbody id="modalPagosList"></tbody>
                        </table>
                        <!-- campos para agregar -->
                        <input type="date" id="pagoFecha" class="form-control mb-2" value="<?= date('Y-m-d') ?>">
                        <select id="pagoTipo" class="form-select mb-2"></select>
                        <select id="pagoMedio" class="form-select mb-2"></select>
                        <input id="pagoRef" class="form-control mb-2" placeholder="Ref">
                        <input id="pagoValor" type="number" class="form-control mb-2" placeholder="Valor">
                        <div class="text-end">
                            <button id="closePago" class="btn btn-secondary">Finalizar</button>
                            <button id="savePago" class="btn btn-primary">Guardar</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Deducciones -->
            <div class="modal fade" id="modalDeds" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content p-3">
                        <h5>Editar Deducciones</h5>
                        <table class="table table-sm mb-3">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Concepto</th>
                                    <th class="text-end">% </th>
                                    <th class="text-end">Valor</th>
                                    <th>Ref</th>
                                    <th>×</th>
                                </tr>
                            </thead>
                            <tbody id="modalDedsList"></tbody>
                        </table>
                        <!-- campos para agregar -->
                        <input type="date" id="dedFecha" class="form-control mb-2" value="<?= date('Y-m-d') ?>">
                        <select id="dedTipo" class="form-select mb-2"></select>
                        <input id="dedPct" type="number" class="form-control mb-2" placeholder="%">
                        <input id="dedValor" type="number" class="form-control mb-2" placeholder="Valor">
                        <input id="dedRef" class="form-control mb-2" placeholder="Ref">
                        <div class="text-end">
                            <button id="closeDed" class="btn btn-secondary">Finalizar</button>
                            <button id="saveDed" class="btn btn-primary">Guardar</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal fade" id="modalKardex" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Kardex Producto</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body p-0">
                            <iframe src="" frameborder="0" style="width:100%;height:80vh;"></iframe>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                window.trabajosAjaxUrl = '/marcacion/trabajos.php?idVenta=<?= $idVenta ?>';
            </script>
            <!-- Dependencias JS: jQuery, Select2, Bootstrap Bundle -->
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
            <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

            <script>
                let usuarioSeleccionadoId = null;


                $(function() {
                    const idVenta = <?= $idVenta ?>;

                    function reloadUsuario() {
                        $('#usuario-info').load(`venta.php?id=${idVenta} #usuario-info > *`);
                    }

                    // — Instancias de modales BS5 —
                    const userModal = new bootstrap.Modal(document.getElementById('userModal'));
                    const svcModal = new bootstrap.Modal(document.getElementById('serviceModal'));
                    const pagoModal = new bootstrap.Modal(document.getElementById('modalPagos'));
                    const dedModal = new bootstrap.Modal(document.getElementById('modalDeds'));

                    $('#closePago').off('click').on('click', () => {
                        pagoModal.hide();
                    });

                    $('#closeDed').off('click').on('click', () => {
                        dedModal.hide();
                    });

                    // — Helper para formatear fechas a 25-Jun-25 8:30 pm —
                    function fmtFechaSQL(fecha) {
                        if (!fecha) return '';

                        let dt;
                        if (typeof fecha === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(fecha)) {
                            const [y, mo, d] = fecha.split('-').map(Number);
                            dt = new Date(y, mo - 1, d);
                        } else {
                            dt = new Date(fecha);
                        }

                        if (Number.isNaN(dt.getTime())) return String(fecha);

                        const m = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
                        const dd = dt.getDate();
                        const mon = m[dt.getMonth()];
                        const yy = String(dt.getFullYear()).slice(-2);

                        let hh = dt.getHours();
                        const ampm = hh >= 12 ? 'pm' : 'am';
                        hh = hh % 12;
                        if (hh === 0) hh = 12;
                        const mm = String(dt.getMinutes()).padStart(2, '0');

                        return `${dd}-${mon}-${yy} ${hh}:${mm} ${ampm}`;
                    }

                    // — Recarga parcial de DETALLE y luego REINICIALIZA su comportamiento —
                    function reloadDetalle() {
                        const url = 'venta_detalle.php?id=' + idVenta + '&_ts=' + Date.now();
                        $('#detalle-container')
                            .load(url + ' #detalle-venta', () => {
                                initDetalle();
                                initResumen(); // <-- esto es lo que faltaba
                            });
                    }

                    // — Recarga parcial de RESUMEN y luego REINICIALIZA su comportamiento —
                    function reloadResumen() {
                        const url = 'ventas_resumen.php?id=' + idVenta + '&_ts=' + Date.now();
                        $('#resumen-container')
                            .load(url + ' #ventasresumen', initResumen);
                    }

                    // — Inicializa select2 y handlers dentro de DETALLE —
                    function initDetalle() {
                        const $variants = $('#detalle-container .variant-select');

                        // 1. Antes de aplicar Select2, elimina elementos clonados por select2 si quedaron en el DOM
                        $variants.each(function() {
                            const $this = $(this);
                            try {
                                if ($this.hasClass('select2-hidden-accessible')) {
                                    $this.select2('destroy');
                                }
                                // Elimina cualquier contenedor visual dejado por select2
                                if ($this.next().hasClass('select2')) {
                                    $this.next('.select2').remove();
                                }
                            } catch (e) {
                                console.warn('Error limpiando select2:', e);
                            }
                        });


                        // 2. Reinicializar Select2
                        $variants
                            .select2({
                                dropdownParent: $('#detalle-container'),
                                ajax: {
                                    url: '../productos/producto_search.php',
                                    dataType: 'json',
                                    delay: 250,
                                    data: params => ({
                                        q: params.term
                                    }),
                                    processResults: data => ({
                                        results: data.results
                                    })
                                },
                                minimumInputLength: 2,
                                placeholder: 'Variante…'
                            })
                            .off('select2:select')
                            .on('select2:select', function() {
                                const idDet = this.dataset.id;
                                const url = idDet ? 'update_venta_detalle.php' : 'add_venta_item.php';
                                const payload = idDet ? {
                                    id: idDet,
                                    field: 'idProductoVariante',
                                    value: this.value
                                } : {
                                    idVenta: idVenta,
                                    idProductoVariante: this.value
                                };

                                $.post(url, payload)
                                    .done(() => {
                                        if (!idDet) {
                                            location.reload();
                                            return;
                                        }
                                        reloadDetalle();
                                        reloadResumen();
                                    })
                                    .fail(xhr => {
                                        const msg = xhr.responseJSON?.message || xhr.responseJSON?.error || 'No se pudo agregar la referencia a la venta.';
                                        alert(msg);
                                        if (!idDet) {
                                            $(this).val(null).trigger('change');
                                        }
                                    });
                            });
                        // Live‐edit para inputs .edit

                        // 1) Handler para el selector de impuesto
                        $('#detalle-container')
                            .off('change', '.select-impuesto')
                            .on('change', '.select-impuesto', function() {
                                const idDet = this.dataset.id;
                                const idImpuesto = this.value;
                                const valorPct = parseFloat($(this).find('option:selected').data('valor'));
                                // actualiza idImpuesto
                                $.post('update_venta_detalle.php', {
                                    id: idDet,
                                    field: 'idImpuesto',
                                    value: idImpuesto
                                });
                                // actualiza porcentajeImpuesto y refresca
                                $.post('update_venta_detalle.php', {
                                    id: idDet,
                                    field: 'porcentajeImpuesto',
                                    value: valorPct
                                }).always(() => {
                                    reloadDetalle();
                                    reloadResumen();
                                });
                            });

                        // 2) Handler para cantidad, precio y cualquier campo .edit
                        $('#detalle-container')
                            .off('change', '.edit')
                            .on('change', '.edit', function() {
                                const $t = $(this);
                                const idDet = $t.data('id');
                                const field = $t.data('field');
                                let value = $t.val();
                                const $tr = $t.closest('tr');
                                if (field === 'cantidad') {
                                    const qty = parseInt(String(value || ''), 10);
                                    const minVenta = Math.max(1, parseInt(String($tr.data('minventa') || 1), 10) || 1);
                                    const multiplo = Math.max(1, parseInt(String($tr.data('multiplo') || 1), 10) || 1);
                                    const isValid = Number.isInteger(qty) && qty >= minVenta && ((qty - minVenta) % multiplo) === 0;
                                    if (!isValid) {
                                        alert(`Cantidad inválida. Mínimo ${minVenta} y en múltiplos de ${multiplo}.`);
                                        reloadDetalle();
                                        return;
                                    }
                                }
                                if (field === 'porcentajeImpuesto') value = value / 100;
                                $.post('update_venta_detalle.php', {
                                        id: idDet,
                                        field: field,
                                        value: value
                                    })
                                    .done(() => {
                                        reloadDetalle();
                                        reloadResumen();
                                    })
                                    .fail(xhr => {
                                        const msg = xhr.responseJSON?.error || xhr.responseJSON?.message || 'No se pudo actualizar el detalle.';
                                        alert(msg);
                                        reloadDetalle();
                                        reloadResumen();
                                    });
                            });


                        // Eliminar ítem
                        $('#detalle-container').off('click', '.remove-item')
                            .on('click', '.remove-item', function() {
                                if (!confirm('¿Eliminar este ítem?')) return;
                                $.post('delete_venta_item.php', {
                                        id: this.dataset.id
                                    })
                                    .always(() => {
                                        reloadDetalle();
                                        reloadResumen();
                                    });
                            });

                        // Abrir modal de Servicios
                        $('#detalle-container').off('click', '.add-service')
                            .on('click', '.add-service', function(e) {
                                e.preventDefault();
                                const idDet = this.dataset.id || $(this).data('id');
                                if (!idDet) {
                                    alert('No se pudo identificar el detalle de la venta.');
                                    return;
                                }
                                $('#srvDetalleId').val(idDet);
                                $('#serviceModal').data('idVentaDetalle', idDet);
                                loadServices(idDet);
                                bootstrap.Modal.getOrCreateInstance(document.getElementById('serviceModal')).show();
                            });
                    }

                    // — Carga y pinta los servicios en el modal —
                    function loadServices(idDet) {
                        $('#srvList').empty();
                        $.getJSON('venta_servicios_api.php?action=list', {
                            idVentaDetalle: idDet
                        }, data => {
                            data.forEach(s => {
                                $('#srvList').append(`
                <tr data-id="${s.idRegistro}">
                    <td>${s.tipoNombre}</td>
                    <td>${s.nombre}</td>
                    <td class="text-end">${s.precioVentaAntesImpuestos}</td>
                    <td>${s.observaciones}</td>
                    <td><button class="btn btn-sm btn-danger del-srv" data-id="${s.idRegistro}">×</button></td>
                </tr>
                `);
                            });
                        });
                    }
                    function showServiceModal() {
                        try {
                            if (svcModal && typeof svcModal.show === 'function') {
                                svcModal.show();
                                return;
                            }
                        } catch (e) {}
                        try {
                            if (window.bootstrap && bootstrap.Modal) {
                                bootstrap.Modal.getOrCreateInstance(document.getElementById('serviceModal')).show();
                                return;
                            }
                        } catch (e) {}
                        $('#serviceModal').addClass('show').css('display', 'block').attr('aria-modal', 'true');
                        if (!$('.modal-backdrop').length) {
                            $('body').append('<div class="modal-backdrop fade show"></div>');
                        }
                        $('body').addClass('modal-open');
                    }
                    window.openVentaServiceModal = function(idDet) {
                        const detalleId = Number(idDet || $('#srvDetalleId').val() || $('#serviceModal').data('idVentaDetalle') || 0);
                        if (!detalleId) {
                            alert('No se pudo identificar el detalle de la venta.');
                            return;
                        }
                        $('#srvDetalleId').val(detalleId);
                        $('#serviceModal').data('idVentaDetalle', detalleId);
                        loadServices(detalleId);
                        showServiceModal();
                    };
                    // *** Añade esto justo después de la definición de loadServices(), fuera de initDetalle/initResumen ***

                    // Eliminar un servicio
                    $(document).on('click', '.del-srv', function() {
                        const idReg = $(this).data('id'),
                            idDet = $('#srvDetalleId').val();
                        $.post('venta_servicios_api.php?action=delete', {
                                idRegistro: idReg
                            })
                            .done(() => loadServices(idDet));
                    });

                    // Guardar un servicio nuevo
                    $('#saveSrv').off('click').on('click', function() {
                        const idDet = $('#srvDetalleId').val(),
                            tipo = $('#srvTipo').val(),
                            nombre = $('#srvNombre').val().trim(),
                            precio = $('#srvPrecio').val(),
                            obs = $('#srvObservaciones').val().trim();
                        if (!tipo || !nombre) return alert('Seleccione tipo y escriba un nombre');
                        $.post(
                            'venta_servicios_api.php?action=add', {
                                idVentaDetalle: idDet,
                                idServicioTipo: tipo,
                                nombre,
                                precioVentaAntesImpuestos: precio,
                                observaciones: obs
                            },
                            function(resp) {
                                if (!resp.success) return alert('Error al guardar');
                                $('#srvNombre,#srvPrecio,#srvObservaciones').val('');
                                loadServices(idDet);
                            },
                            'json'
                        );
                    });

                    // Cerrar el modal
                    $('#closeSrv').off('click').on('click', () => {
                        bootstrap.Modal.getOrCreateInstance(document.getElementById('serviceModal')).hide();
                        $('#serviceModal').one('hidden.bs.modal', () => {
                            reloadDetalle();
                            reloadResumen();
                        });
                    });



                    $(document).on('hidden.bs.modal', function() {
                        if ($('.modal.show').length === 0) {
                            $('body').removeClass('modal-open');
                            $('.modal-backdrop').remove();
                        }
                    });


                    // — Inicializa el resumen (Pagos / Deducciones) —
                    function initResumen() {
                        // abrir modales
                        $('#addPagoBtn').off('click').on('click', () => {
                            loadPagos(); // recarga la tabla/modal
                            pagoModal.show();
                        });
                        $('#addDedBtn').off('click').on('click', () => {
                            loadDeds();
                            dedModal.show();
                        });


                        // guardar pago
                        $('#savePago').off('click').on('click', function() {
                            $.post('ventas_pagos_api.php', {
                                action: 'add',
                                idVenta,
                                fecha: $('#pagoFecha').val(),
                                idTipo: $('#pagoTipo').val(),
                                idMedio: $('#pagoMedio').val(),
                                refPago: $('#pagoRef').val(),
                                valorPago: $('#pagoValor').val()
                            }, function(resp) {
                                if (resp.success) {

                                    loadPagos();
                                    reloadResumen();
                                } else {
                                    alert('Error guardando pago');
                                }
                            }, 'json');
                        });


                        // guardar deducción
                        $('#saveDed').off('click').on('click', function() {
                            $.post('ventas_deducciones_api.php', {
                                action: 'add',
                                idVenta,
                                fecha: $('#dedFecha').val(),
                                idDeduccion: $('#dedTipo').val(),
                                porcentajeDeduccion: $('#dedPct').val() / 100,
                                valorDeduccion: $('#dedValor').val(),
                                refPago: $('#dedRef').val()
                            }, function(resp) {
                                if (resp.success) {

                                    loadDeds();
                                    reloadResumen();
                                } else {
                                    alert('Error guardando deducción');
                                }
                            }, 'json');
                        });

                        // live‐edit de observaciones
                        $('#obsInput').off('change').on('change', function() {
                            $.post(`venta.php?id=${idVenta}`, {
                                action: 'update_field',
                                field: 'observaciones',
                                value: this.value
                            }).always(reloadResumen);
                        });


                    }




                    // Recarga tabla de Pagos y modal de Pagos
                    function loadPagos() {
                        $.getJSON('ventas_pagos_api.php?action=list&idVenta=' + idVenta, data => {
                            // 1) llena la tabla resumen
                            let resumenHtml = '';
                            data.forEach(p => {
                                resumenHtml += `
                <tr data-id="${p.id}">
                <td>${fmtFechaSQL(p.fecha)}</td>
                <td>${p.Tipo}</td>
                <td>${p.Medio}</td>
                <td>${p.Ref || '-'}</td>
                <td class="text-end">$ ${Number(p.Valor).toLocaleString('es-CO')}</td>
                </tr>`;
                            });
                            $('#tablaPagos tbody').html(resumenHtml);

                            // 2) llena la tabla dentro del modal
                            let modalRows = '';
                            data.forEach(p => {
                                modalRows += `
                <tr data-id="${p.id}">
                <td>${fmtFechaSQL(p.fecha)}</td>
                <td>${p.Tipo}</td>
                <td>${p.Medio}</td>
                <td>${p.Ref || '-'}</td>
                <td class="text-end">$ ${Number(p.Valor).toLocaleString('es-CO')}</td>
                <td><button class="btn btn-sm btn-danger del-pago">×</button></td>
                </tr>`;
                            });
                            $('#modalPagosList').html(modalRows);

                            // 3) carga los <select> de Tipo y Medio dentro del modal
                            $.getJSON('ventas_pagos_api.php?action=listsel', sel => {
                                $('#pagoTipo').html(
                                    '<option></option>' +
                                    sel.tipos.map(o => `<option value="${o.id}">${o.nombre}</option>`).join('')
                                );
                                $('#pagoMedio').html(
                                    '<option></option>' +
                                    sel.medios.map(o => `<option value="${o.id}">${o.nombre}</option>`).join('')
                                );
                            });
                        });
                    }

                    // Recarga tabla de Deducciones y modal de Deducciones
                    function loadDeds() {
                        $.getJSON('ventas_deducciones_api.php?action=list&idVenta=' + idVenta, data => {
                            // 1) llena la tabla resumen
                            let resumenHtml = '';
                            data.forEach(d => {
                                resumenHtml += `
                <tr data-id="${d.id}">
                <td>${fmtFechaSQL(d.fecha)}</td>
                <td>${d.nombre}</td>
                <td class="text-end">${(d.porcentajeDeduccion * 100).toFixed(0)}%</td>
                <td class="text-end">$ ${Number(d.valorDeduccion).toLocaleString('es-CO')}</td>
                <td>${d.refPago || '-'}</td>
                </tr>`;
                            });
                            $('#tablaDeducciones tbody').html(resumenHtml);

                            // 2) llena la tabla dentro del modal
                            let modalRows = '';
                            data.forEach(d => {
                                modalRows += `
                <tr data-id="${d.id}">
                <td>${fmtFechaSQL(d.fecha)}</td>
                <td>${d.nombre}</td>
                <td class="text-end">${(d.porcentajeDeduccion * 100).toFixed(0)}%</td>
                <td class="text-end">$ ${Number(d.valorDeduccion).toLocaleString('es-CO')}</td>
                <td>${d.refPago || '-'}</td>
                <td><button class="btn btn-sm btn-danger del-ded">×</button></td>
                </tr>`;
                            });
                            $('#modalDedsList').html(modalRows);

                            // 3) carga el <select> de tipos de deducción dentro del modal
                            $.getJSON('ventas_deducciones_api.php?action=listsel', sel => {
                                $('#dedTipo').html(
                                    '<option></option>' +
                                    sel.lista.map(o => `<option value="${o.id}">${o.nombre}</option>`).join('')
                                );
                            });
                        });
                    }







                    // — Delegación global para borrar pagos/deducciones —
                    $(document).on('click', '.del-pago', function() {
                        const id = $(this).closest('tr').data('id');
                        $.post('ventas_pagos_api.php', {
                            action: 'delete',
                            idRegistro: id
                        }, loadPagos);
                    });
                    $(document).on('click', '.del-ded', function() {
                        const id = $(this).closest('tr').data('id');
                        $.post('ventas_deducciones_api.php', {
                            action: 'delete',
                            idRegistro: id
                        }, loadDeds);
                    });

                    // — Select2 para usuario en cabecera —
                    $('#editUserBtn').off('click').on('click', () => userModal.show());


                    $('#userSelect').select2({
                            ajax: {
                                url: 'users_search.php',
                                dataType: 'json',
                                delay: 250,
                                data: params => ({
                                    q: params.term
                                }),
                                processResults: data => ({
                                    results: data.items
                                })
                            },
                            placeholder: 'Buscar usuario...',
                            minimumInputLength: 2,
                            dropdownParent: $('#userModal')
                        })
                        .on('select2:select', e => {
                            usuarioSeleccionadoId = e.params.data.id;
                        });

                    $('#btnActualizarUsuario').off('click').on('click', () => {
                        if (!usuarioSeleccionadoId) return alert('Debe seleccionar un usuario');

                        $.post(`venta.php?id=${idVenta}`, {
                            action: 'update_field',
                            field: 'idUsuario',
                            value: usuarioSeleccionadoId
                        }).always(() => {
                            reloadDetalle();
                            reloadResumen();
                            reloadUsuario(); // ← este
                            userModal.hide();
                            usuarioSeleccionadoId = null;
                        });
                    });

                    // — Selects de cabecera y fecha —
                    $('#selEstado,#selTipo,#selMedio,#selEmpresa,#inpFecha,#inpRefExt').off('change').on('change', function() {
                        $.post(`venta.php?id=${idVenta}`, {
                            action: 'update_field',
                            field: this.name,
                            value: this.value
                        }).always(() => {
                            reloadDetalle();
                            reloadResumen();
                        });
                    });

                    // — Inicialización al cargar la página —
                    initDetalle();
                    initResumen();
                    loadPagos();
                    loadDeds();
                });

                $(document).on('hidden.bs.modal', function() {
                    if ($('.modal.show').length === 0) {
                        $('body').removeClass('modal-open');
                        $('.modal-backdrop').remove();
                    }
                });

                // Kardex en detalle de venta (delegado: funciona también después de reloadDetalle())
                $(document).off('click', '.btn-kardex').on('click', '.btn-kardex', function() {
                    const idVar = $(this).data('var-id') ?? $(this).data('varId') ?? this.dataset.varId ?? this.dataset.varid;
                    $('#modalKardex iframe')
                        .attr('src', '/productos/kardex_producto.php?id=' + encodeURIComponent(String(idVar ?? '')));

                    const modalEl = document.getElementById('modalKardex');
                    if (window.bootstrap && typeof window.bootstrap.Modal === 'function') {
                        new window.bootstrap.Modal(modalEl).show();
                    } else {
                        // Bootstrap 4 fallback
                        $('#modalKardex').modal('show');
                    }
                });
            </script>

            <?php include '../templates/footer.php'; ?>
