            <?php
            session_start();
            include '../includes/session_control.php';
            require_once __DIR__ . '/../cotizaciones/api/_node.php';

            $idGasto = intval($_GET['id'] ?? $_GET['idGasto'] ?? 0);
            if (!$idGasto) die('ID inválido');

            $token = cpn_node_token_or_fail();
            $base = cpn_node_api_base();
            $resp = cpn_node_request('GET', $base . '/api/gastos/detalle/view?id=' . urlencode((string)$idGasto), $token, null);
            if (!($resp['ok'] ?? false)) die('Gasto no encontrado');

            $view = $resp['data'] ?? null;
            $g = $view['gasto'] ?? null;
            $t = $view['totales'] ?? null;
            if (!$g || !$t) die('Gasto no encontrado');

            $idOrigen = intval($_GET['idOrigen'] ?? ($g['idOrigen'] ?? 0));

            $idUsuario = $view['idUsuario'] ?? 0;
            $empresas = $view['empresasSigla'] ?? [];
            $empresasNombre = $view['empresasNombre'] ?? [];
            $deduccionesCatalog = $view['deduccionesCatalog'] ?? [];
            $hasFactura = (bool)($view['hasFactura'] ?? false);
            $pagosSoportes = $view['pagosSoportes'] ?? [];
            $pagosRelacion = $view['pagosRelacion'] ?? [];
            // 2) Estado con umbral de 5 pesos
            $sumaPagos = $g['sumaPagos'];
            $diff = abs($t['total'] - $sumaPagos);
            if ($diff <= 5) {
                $statusText  = 'Pagado';
                $statusClass = 'badge bg-success text-white';
            } elseif ($sumaPagos == 0) {
                $statusText  = 'No Pagado';
                $statusClass = 'badge bg-danger text-white';
            } else {
                $statusText  = 'Abonado';
                $statusClass = 'badge bg-warning text-white';
            }


            function getTextColor($hex)
            {
                $h = ltrim($hex, '#');
                $r = hexdec(substr($h, 0, 2));
                $g = hexdec(substr($h, 2, 2));
                $b = hexdec(substr($h, 4, 2));
                return (($r * 0.299 + $g * 0.587 + $b * 0.114) / 255 > 0.5) ? '#000' : '#fff';
            }

            // Texto beneficiario
            $nombreCompleto = trim("{$g['nombre']} {$g['apellido']}");
            $razonSocial    = trim($g['razonSocial']);
            $benText = (!empty($razonSocial) && $razonSocial !== $nombreCompleto)
                ? "$nombreCompleto ($razonSocial)"
                : $nombreCompleto;

            // Soportes: factura (string) y pagos (para galerías por id)
            $factura = ($g['prefijoFactura'] ?? '') . ($g['noFactura'] ?? '');

            ?>
            <?php include '../templates/header.php'; ?>
            <?php include 'modals_gastos_reusable.php'; ?>

            <div id="pageContent" class="container-fluid">

                <h1 class="h3 mb-4">
                    Relación de Gasto No. <?= $idGasto ?> —
                    <small>Beneficiario: <?= htmlspecialchars($benText) ?></small>
                </h1>

                <div class="mb-3">
                    <button
                        type="button"
                        id="btnChangeBen"
                        class="btn btn-secondary"
                        data-bs-toggle="modal"
                        data-bs-target="#changeBenModal">
                        Cambiar beneficiario/Empresa
                    </button>
                    <a href="/usuarios/administrar_usuario.php?id=<?= $idUsuario ?>"
                        target="_blank" class="btn btn-info">Editar Beneficiario</a>
                    <button id="btnPay" class="btn btn-warning">Pagar/Abonar</button>

                </div>

                <div class="row">
                    <!-- IZQUIERDA: contenido y pestañas -->
                    <div class="col-md-8">
                        <!-- Nav tabs -->
                        <ul class="nav nav-tabs" id="gastoTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <a class="nav-link active"
                                    id="info-tab"
                                    data-toggle="tab"
                                    href="#info"
                                    role="tab"
                                    aria-controls="info"
                                    aria-selected="true">
                                    Información General
                                </a>
                            </li>
                            <li class="nav-item" role="presentation">
                                <a class="nav-link"
                                    id="soportes-tab"
                                    data-toggle="tab"
                                    href="#soportes"
                                    role="tab"
                                    aria-controls="soportes"
                                    aria-selected="false">
                                    Soportes (<?= $g['archivos'] ?>)
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="anexos-tab"
                                    data-toggle="tab" href="#anexos"
                                    role="tab">Anexos</a>
                            </li>

                        </ul>

                        <!-- Tab panes -->
                        <div class="tab-content border border-top-0 p-3" id="gastoTabContent">
                            <!-- Información General -->
                            <div class="tab-pane fade show active" id="info" role="tabpanel" aria-labelledby="info-tab">
                                <div class="row g-3">
                                    <div class="col-md-2">
                                        <label class="form-label">Fecha</label>
                                        <input type="date" id="field-fecha" class="form-control"
                                            value="<?= htmlspecialchars(substr($g['fecha'], 0, 10)) ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Empresa</label>
                                        <select
                                            id="field-idEmpresa"
                                            class="form-control"
                                            style="background: <?= htmlspecialchars($g['empColor']) ?>; color: <?= getTextColor($g['empColor']) ?>;">
                                            <?php foreach ($empresas as $e): ?>
                                                <option
                                                    value="<?= $e['id'] ?>"
                                                    <?= $e['id'] == $g['idEmpresa'] ? 'selected' : '' ?>
                                                    style="background: <?= htmlspecialchars($e['colorHexa']) ?>; color: <?= getTextColor($e['colorHexa']) ?>;">
                                                    <?= htmlspecialchars($e['sigla']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Prefijo</label>
                                        <input type="text" id="field-prefijoFactura" class="form-control"
                                            value="<?= htmlspecialchars($g['prefijoFactura']) ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">No. Factura</label>
                                        <input type="text" id="field-noFactura" class="form-control"
                                            value="<?= htmlspecialchars($g['noFactura']) ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Fecha Venc.</label>
                                        <input type="date" id="field-fechaVencimiento" class="form-control"
                                            value="<?= htmlspecialchars(substr($g['fechaVencimiento'], 0, 10)) ?>">
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label">Observaciones</label>
                                        <textarea id="field-observaciones" class="form-control" rows="2"><?= htmlspecialchars($g['observaciones']) ?></textarea>
                                    </div>
                                </div>


                                <!-- Detalle de ítems -->
                                <div id="detalle-gasto" class="mt-4">
                                    <table class="table table-sm table-bordered align-middle small">
                                        <thead>
                                            <tr>
                                                <th>Descripción</th>
                                                <th class="text-right" style="width:80px">Cant</th>
                                                <th class="text-right" style="width:100px">Vr Unit.</th>
                                                <th>Impuesto</th>
                                                <th class="text-right">Subtotal / Total</th>
                                                <th class="text-right">Abono / Saldo</th>
                                                <th>Cuenta</th>
                                                <th>Concepto</th>
                                                <th>Mes</th>
                                                <th>X</th>
                                            </tr>
                                        </thead>
                                        <tbody id="items-body"><!-- AJAX --></tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="10" class="text-center">
                                                    <button id="btnAddItem" class="btn btn-sm btn-primary">+ Nuevo Item</button>
                                                </td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>

                            <!-- Soportes -->
                            <?php
                            ?>
                            <div class="tab-pane fade" id="soportes" role="tabpanel">
                                <!-- Soporte del gasto -->
                                <h5>Soporte del gasto</h5>
                                <div id="soportes-list" class="soportes-list mb-4"></div>
                                <div id="soportes-empty" class="text-muted small mb-3" style="display:none;">No hay soportes cargados.</div>
                                <form id="form-soportes" enctype="multipart/form-data">
                                    <input type="hidden" name="idGasto" value="<?= $idGasto ?>">
                                    <input type="file" name="soporteGasto[]" multiple class="form-control mb-2">
                                    <small>Puedes pegar imágenes aquí:</small>
                                    <div id="paste-area-gasto" contenteditable="true" class="form-control mb-2" style="min-height:100px;"></div>
                                    <button class="btn btn-primary">Subir Soportes</button>
                                </form>

                                <!-- Factura electrónica -->
                                <h5 class="mt-4">Factura electrónica</h5>
                                <?php if ($hasFactura): ?>
                                    <a href="/archivoDigital/<?= $g['noDocumento'] ?>/<?= $factura ?>.pdf"
                                        target="_blank">
                                        <img src="/img/pdf-icon.png" style="width:50px" alt="Factura PDF">
                                    </a>
                                <?php else: ?>
                                    <p><em>No hay factura electrónica cargada.</em></p>
                                <?php endif; ?>

                                <!-- Soportes de pago -->
                                <?php if (!empty($pagosSoportes)): ?>
                                    <h5 class="mt-4">Soportes de pago</h5>
                                    <div class="soportes-pagos-gallery d-flex flex-wrap gap-2">
                                        <?php
                                        // listar carpeta uploads/pagos/{id}/…
                                        foreach ($pagosSoportes as $p) {
                                            $dir = __DIR__ . "/../archivoDigital/soportePagos/{$p['id']}";
                                            if (!is_dir($dir)) continue;
                                            foreach (scandir($dir) as $f) {
                                                // saltar . .. Thumbs.db y todo lo que no sea imagen
                                                $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
                                                if (
                                                    $f === '.' ||
                                                    $f === '..' ||
                                                    strtolower($f) === 'thumbs.db' ||
                                                    !in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])
                                                ) {
                                                    continue;
                                                }
                                                $url = "/archivoDigital/soportePagos/{$p['id']}/{$f}";
                                        ?>
                                                <a href="<?= $url ?>" target="_blank">
                                                    <img src="<?= $url ?>" class="img-thumb">
                                                </a>
                                        <?php
                                            }
                                        }
                                        ?>


                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="tab-pane fade" id="anexos" role="tabpanel">
                                <div id="anexos-wrapper"><!-- AJAX --></div>
                                <div id="anexos-empty" class="text-muted small" style="display:none;">No hay anexos para este gasto.</div>
                            </div>


                        </div>
                    </div>

                    <!-- DERECHA: Resumen y deducciones -->
                    <div class="col-md-4">
                        <div id="resumen-gasto">
                            <h5>Resumen</h5>
                            <dl class="row">
                                <dt class="col-6">Subtotal</dt>
                                <dd id="res-subtotal" class="col-6 text-right">$ <?= number_format($t['subtotal'], 0, ',', '.') ?></dd>
                                <dt class="col-6">Impuestos</dt>
                                <dd id="res-impuesto" class="col-6 text-right">$ <?= number_format($t['impuesto'], 0, ',', '.') ?></dd>
                                <dt class="col-6">Deducciones</dt>
                                <dd id="res-deducciones" class="col-6 text-right">$ <?= number_format($t['deducciones'], 0, ',', '.') ?></dd>
                                <dt class="col-6">Total</dt>
                                <dd id="res-total" class="col-6 text-right fw-bold">$ <?= number_format($t['total'], 0, ',', '.') ?></dd>
                            </dl>
                            <button
                                type="button"
                                id="btnAddDed"
                                class="btn btn-sm btn-primary mb-2"
                                data-bs-toggle="modal"
                                data-bs-target="#deductionModal">
                                Deducción
                            </button>
                            <table class="table table-sm table-bordered" id="deducciones-table">
                                <thead>
                                    <tr>
                                        <th>Concepto</th>
                                        <th class="text-right">%</th>
                                        <th class="text-right">Valor</th>
                                        <th>Notas</th>
                                        <th>×</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                            <div class="my-3"></div>
                            <!-- fila ancha con estado -->
                            <div class="w-100 mb-3">
                                <div id="statusBadgeRight"
                                    class="<?= $statusClass ?> d-block w-100 text-center py-1">
                                    <?= $statusText ?>
                                </div>
                            </div>


                            <!-- Nueva consulta de pagos -->
                            <h5>Relación de pagos</h5>
                            <table class="table table-sm mb-3" id="pagos-relacion-table">
                                <thead>
                                    <tr>
                                        <th>Fecha</th>
                                        <th>Banco</th>
                                        <th class="text-right">Total</th>
                                        <th style="width:40px;" class="text-center">×</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $totalPagado = 0;
                                    foreach ($pagosRelacion as $p): ?>
                                        <?php $totalPagado += $p['totalPago']; ?>
                                        <tr data-id-pago="<?= (int)($p['idPago'] ?? 0) ?>">
                                            <td><?= date('d-M-y g:i a', strtotime($p['fecha'])) ?></td>
                                            <td><?= htmlspecialchars($p['banco']) ?></td>
                                            <td class="text-right"><?= number_format($p['totalPago'], 0, ',', '.') ?></td>
                                            <td class="text-center">
                                                <?php if (!empty($p['idPago'])): ?>
                                                    <button type="button" class="btn btn-sm btn-danger del-pago">×</button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <tr>
                                        <td colspan="2"><strong>Total Pagado</strong></td>
                                        <td class="text-right"><strong><?= number_format($totalPagado, 0, ',', '.') ?></strong></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="2"><strong>Saldo</strong></td>
                                        <td class="text-right"><strong><?= number_format($t['total'] - $totalPagado, 0, ',', '.') ?></strong></td>
                                        <td></td>
                                    </tr>
                                </tbody>
                            </table>

                            <!-- Factura electrónica -->
                            <?php if ($hasFactura): ?>
                                <h5>Factura electrónica</h5>
                                <a href="/archivoDigital/<?= $g['noDocumento'] ?>/<?= "{$g['prefijoFactura']}{$g['noFactura']}" ?>.pdf"
                                    target="_blank">
                                    <img src="/img/pdf-icon.png" style="width:50px" alt="Factura PDF">
                                </a>
                            <?php endif; ?>


                        </div>
                    </div>
                </div>
            </div>

            <!-- Modales -->
            <div class="modal fade" id="changeBenModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog">
                    <form id="changeBenForm" class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Cambiar Beneficiario / Empresa</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">Empresa</label>
                                <select name="idEmpresa" class="form-select" required>
                                    <?php foreach ($empresasNombre as $e): ?>
                                        <option value="<?= $e['id'] ?>" <?= $e['id'] == $g['idEmpresa'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($e['nombre']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Beneficiario</label>
                                <select id="changeTercero" name="idTercero" class="form-select" style="width:100%" required>
                                    <option value="<?= $g['idTercero'] ?>"><?= htmlspecialchars($benText) ?></option>
                                </select>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                            <button type="submit" class="btn btn-primary">Guardar Cambio</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="modal fade" id="deductionModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog">
                    <form id="deductionForm" class="modal-content">
                        <input type="hidden" name="action" value="add">
                        <div class="modal-header">
                            <h5 class="modal-title">Nueva Deducción</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">Concepto</label>
                                <select name="idDeduccion" class="form-select" required>
                                    <option value=""></option>
                                    <?php foreach ($deduccionesCatalog as $d): ?>
                                        <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['nombre']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">% Deducción</label>
                                <input type="number" name="porcentajeDeduccion" class="form-control" step="0.01">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Valor</label>
                                <input type="number" name="valorDeduccion" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Notas</label>
                                <textarea name="notas" class="form-control" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                            <button type="submit" class="btn btn-primary">Agregar</button>
                        </div>
                    </form>
                </div>
            </div>

            <?php include '../templates/footer.php'; ?>
            <!-- === JS específico de detalle_gasto === -->
            <script>
                /*═══════════════════════════════════════════════════════
        CONTEXTO
        ═══════════════════════════════════════════════════════*/
                const idG = <?= $idGasto ?>; // id del gasto
                const benTx = <?= json_encode($benText) ?>; // texto beneficiario
                const idTercero = <?= $g['idTercero'] ?>; // para anexos
                const archivos = <?= (int)$g['archivos'] ?>; // nº soportes

                /*═══════════════════════════════════════════════════════
                HELPERS
                ═══════════════════════════════════════════════════════*/
                function money(v) {
                    return '$ ' + Number(v).toLocaleString('es-CO');
                }

                function refrescaResumen(r) {
                    $('#res-subtotal').text(money(r.subtotal));
                    $('#res-impuesto').text(money(r.impuesto));
                    $('#res-deducciones').text(money(r.deducciones));
                    $('#res-total').text(money(r.total));
                }

                /* genérico Select-2 en tablas */
                function sel2($e, url, ph) {
                    return $e.select2({
                        dropdownParent: $('#pageContent'),
                        ajax: {
                            url,
                            dataType: 'json',
                            delay: 250,
                            data: p => ({
                                q: p.term
                            })
                        },
                        placeholder: ph,
                        width: '100px',
                        dropdownAutoWidth: true
                    });
                }

                /*═══════════════════════════════════════════════════════
                ÍTEMS
                ═══════════════════════════════════════════════════════*/
                function renderItems(d) {
                    const $tb = $('#items-body').empty();
                    d.forEach(r => {
                        const sub = +r.subtotalItem,
                            tot = +r.totalItem,
                            abo = +r.abonadoItem,
                            sal = tot - abo;

                        $tb.append(`<tr data-id="${r.id}">
        <td><input class="form-control edit desc" value="${r.description}"></td>
        <td><input class="form-control edit qty text-right" value="${r.cantidad}"></td>
        <td><input type="number" step="1"
                    class="form-control edit vu text-right" style="max-width:90px; font-size:0.8rem;"
                    value="${(+r.valorUnitarioGasto).toFixed(0)}"></td>
        <td><select class="form-select sel-impuesto">
                <option value="${r.idImpuesto}" selected>
                ${r.idImpuesto} – ${r.impuestoNombre}
                </option></select></td>
        <td class="text-right">
                <div>${(+r.subtotalItem).toLocaleString('es-CO')}</div>
                <div class="small text-muted">${(+r.totalItem).toLocaleString('es-CO')}</div>
        </td>
        <td class="text-right">
                <div>${(+r.abonadoItem).toLocaleString('es-CO')}</div>
                <div class="small text-muted">${((+r.totalItem - +r.abonadoItem)).toLocaleString('es-CO')}</div>
        </td>
        <td><select class="form-select sel-cuenta">
                <option value="${r.idCuenta}" selected>
                ${r.idCuenta} – ${r.cuentaNombre}
                </option></select></td>
        <td><select class="form-select sel-concepto">
                <option value="${r.idConcepto}" selected>
                ${r.idConcepto} – ${r.conceptoNombre}
                </option></select></td>
        <td><select class="form-select sel-mes">
                <option value="${r.idMesContable}" selected>
                ${r.idMesContable} – ${r.mesNombre}
                </option></select></td>
        <td><button class="btn btn-sm btn-danger del-item">×</button></td>
        </tr>`);
                    });

                    sel2($('.sel-cuenta'), 'cuentas_search.php', 'Cuenta…');
                    sel2($('.sel-impuesto'), 'impuestos_search.php', 'Impuesto…');
                    sel2($('.sel-concepto'), 'conceptos_search.php', 'Concepto…');
                    sel2($('.sel-mes'), 'meses_search.php', 'Mes…');
                }

                function loadItems() {
                    $.getJSON('get_gasto_items.php', {
                        id: idG
                    }, renderItems);
                }

                /*═══════════════════════════════════════════════════════
                DEDUCCIONES
                ═══════════════════════════════════════════════════════*/
                function loadDeds() {
                    $.getJSON('gasto_deducciones_api.php', {
                        action: 'list',
                        idGasto: idG
                    }, d => {
                        const $t = $('#deducciones-table tbody').empty();
                        d.forEach(x => $t.append(`<tr data-id="${x.id}">
                    <td>${x.nombre}</td>
                    <td class="text-right">${(x.porcentajeDeduccion*100).toFixed(0)}%</td>
                    <td class="text-right">${money(x.valorDeduccion)}</td>
                    <td>${x.notas||''}</td>
                    <td><button class="btn btn-sm btn-danger del-ded">×</button></td>
                </tr>`));
                    });
                }

                /*═══════════════════════════════════════════════════════
                ANEXOS
                ═══════════════════════════════════════════════════════*/
                function renderAnexos(arr) {
                    const $w = $('#anexos-wrapper').empty();
                    arr.forEach(it => {
                        const ok = (Number(it.sumaAnexos) === Number(it.totalItem)) || it.idOrigen === 4;
                        $w.append(`<div class="card mb-3" data-item="${it.id}">
                <div class="card-header d-flex justify-content-between">
                <span>${it.description} – ${money(it.totalItem)}</span>
                <span class="badge ${ok?'bg-success':'bg-danger'}">
                        ${money(it.sumaAnexos)}</span></div>
                <div class="card-body p-2">
                <table class="table table-sm mb-2"><tbody>${
                    it.anexos.map(a=>`<tr data-anexo="${a.id}">
                        <td>#${a.texto}</td>
                        <td class="text-right">${money(a.valor)}</td>
                        <td><button class="btn btn-sm btn-danger del-anexo">×</button></td>
                    </tr>`).join('')
                }</tbody></table>
                <select class="form-select sel-anexo" style="width:100%"></select>
                </div></div>`);
                    });

                    $('.sel-anexo').each(function() {
                        const idItem = $(this).closest('.card').data('item'),
                            origen = arr.find(x => x.id === idItem).idOrigen,
                            url = `search_anexo.php?idOrigen=${origen}&idTercero=${idTercero}`;

                        $(this).select2({
                            dropdownParent: $(this).parent(),
                            ajax: {
                                url,
                                dataType: 'json',
                                delay: 250,
                                data: p => ({
                                    q: p.term
                                })
                            },
                            placeholder: 'Buscar…',
                            width: '100%'
                        }).on('select2:select', e => {
                            $.post('add_anexo.php', {
                                    idItem,
                                    idOrigen: origen,
                                    noDocumento: e.params.data.id
                                },
                                resp => {
                                    if (!resp.success) {
                                        alert(resp.msg);
                                        return;
                                    }
                                    loadAnexos();
                                    loadItems();
                                    refrescaResumen(resp);
                                }, 'json');
                            $(this).val(null).trigger('change');
                        });
                    });
                }

                function loadAnexos() {
                    $.getJSON('get_anexos.php', {
                        idGasto: idG
                    }, arr => {
                        const has = Array.isArray(arr) && arr.length;
                        $('#anexos-empty').toggle(!has);
                        renderAnexos(Array.isArray(arr) ? arr : []);
                    });
                }

                /*═══════════════════════════════════════════════════════
                SOPORTES  (pegado desde portapapeles)
                ═══════════════════════════════════════════════════════*/
                const pastedGastoFiles = [];
                $('#paste-area-gasto').on('paste', e => {
                    e.preventDefault();
                    const f = (e.originalEvent || e).clipboardData.files;
                    for (const file of f) {
                        pastedGastoFiles.push(file);
                        $('#paste-area-gasto').append(
                            $('<img>', {
                                src: URL.createObjectURL(file)
                            })
                            .css({
                                maxWidth: 100,
                                margin: 4,
                                objectFit: 'contain'
                            }));
                    }
                });

                $('#form-soportes').on('submit', function(e) {
                    e.preventDefault();
                    const fd = new FormData(this);
                    pastedGastoFiles.forEach((f, i) => {
                        const ext = f.type.split('/').pop();
                        fd.append('soporteGasto[]', f, `gasto_${Date.now()}_${i}.${ext}`);
                    });
                    $.ajax({
                        url: 'process_gasto_files.php',
                        type: 'POST',
                        data: fd,
                        processData: false,
                        contentType: false,
                        success: loadSoportes
                    });
                });

                function loadSoportes() {
                    $.getJSON('listado_soportes.php', {
                        idGasto: idG
                    }, files => {
                        const $l = $('#soportes-list').empty();
                        const has = Array.isArray(files) && files.length;
                        $('#soportes-empty').toggle(!has);
                        files.forEach(f => $l.append(`
                <div class="soporte-item">
                    <img src="${f.url}" class="img-thumb">
                    <button class="delete-soporte btn btn-sm btn-danger"
                            data-file="${f.name}">×</button>
                </div>`));
                    });
                }

                function renderPagosRelacion(pagos, totalGasto) {
                    const $tb = $('#pagos-relacion-table tbody');

                    if (!$tb.length) return;

                    $tb.empty();
                    let totalPagado = 0;
                    (Array.isArray(pagos) ? pagos : []).forEach(p => {
                        const totalPago = Number(p.totalPago || 0);
                        totalPagado += totalPago;
                        const idPago = Number(p.idPago || 0);
                        $tb.append(`
                            <tr data-id-pago="${idPago}">
                                <td>${p.fecha_fmt || ''}</td>
                                <td>${$('<div>').text(p.banco || '').html()}</td>
                                <td class="text-right">${Math.round(totalPago).toLocaleString('es-CO')}</td>
                                <td class="text-center">${idPago ? '<button type="button" class="btn btn-sm btn-danger del-pago">×</button>' : ''}</td>
                            </tr>
                        `);
                    });

                    $tb.append(`
                        <tr>
                            <td colspan="2"><strong>Total Pagado</strong></td>
                            <td class="text-right"><strong>${Math.round(totalPagado).toLocaleString('es-CO')}</strong></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2"><strong>Saldo</strong></td>
                            <td class="text-right"><strong>${Math.round(Number(totalGasto || 0) - totalPagado).toLocaleString('es-CO')}</strong></td>
                            <td></td>
                        </tr>
                    `);
                }

                $('#soportes-list').on('click', '.delete-soporte', function() {
                    $.post('delete_gasto_file.php', {
                        idGasto: idG,
                        file: $(this).data('file')
                    }, loadSoportes);
                });

                /*═══════════════════════════════════════════════════════
                EVENTOS GLOBAL ITEM-TABLE
                ═══════════════════════════════════════════════════════*/
                $('#items-body')
                    /* eliminar item */
                    .on('click', '.del-item', function() {
                        if (!confirm('¿Eliminar ítem?')) return;
                        $.post('delete_gasto_item.php', {
                                id: $(this).closest('tr').data('id'),
                                idGasto: idG
                            },
                            resp => {
                                loadItems();
                                refrescaResumen(resp);
                            }, 'json');
                    })
                    /* cambios en celdas/selects */
                    .on('change', '.edit, .sel-cuenta, .sel-concepto, .sel-mes, .sel-impuesto',
                        function() {

                            const $tr = $(this).closest('tr'),
                                idItem = $tr.data('id'),
                                isTax = $(this).hasClass('sel-impuesto');

                            const field = isTax ? 'idImpuesto' :
                                $(this).hasClass('sel-cuenta') ? 'idCuenta' :
                                $(this).hasClass('desc') ? 'description' :
                                $(this).hasClass('qty') ? 'cantidad' :
                                $(this).hasClass('vu') ? 'valorUnitarioGasto' :
                                $(this).hasClass('sel-concepto') ? 'idConcepto' :
                                'idMesContable';

                            const value = isTax ? $(this).select2('data')[0].id : $(this).val();

                            $.post('update_gasto_item.php', {
                                    id: idItem,
                                    field,
                                    value,
                                    idGasto: idG
                                },
                                resp => {
                                    if (!resp.success) {
                                        console.error('update error');
                                        return;
                                    }

                                    if (isTax) {
                                        const porc = $(this).select2('data')[0].valor;
                                        $.post('update_gasto_item.php', {
                                                id: idItem,
                                                field: 'porcentajeImpuesto',
                                                value: porc,
                                                idGasto: idG
                                            },
                                            r2 => {
                                                loadItems();
                                                refrescaResumen(r2);
                                            }, 'json');
                                    } else {
                                        loadItems();
                                        refrescaResumen(resp);
                                    }
                                }, 'json');
                        });

                /*═══════════════════════════════════════════════════════
                DEDUCCIONES  (add / delete)
                ═══════════════════════════════════════════════════════*/
                $('#deductionForm').on('submit', function(e) {
                    e.preventDefault();
                    $.post('gasto_deducciones_api.php', $(this).serialize() + '&idGasto=' + idG,
                        resp => {
                            loadDeds();
                            refrescaResumen(resp);
                            bootstrap.Modal.getInstance('#deductionModal').hide();
                        }, 'json');
                });

                $('#deducciones-table').on('click', '.del-ded', function() {
                    $.post('gasto_deducciones_api.php', {
                            action: 'delete',
                            idRegistro: $(this).closest('tr').data('id'),
                            idGasto: idG
                        },
                        resp => {
                            loadDeds();
                            refrescaResumen(resp);
                        }, 'json');
                });

                /*═══════════════════════════════════════════════════════
                ANEXOS  (delete)
                ═══════════════════════════════════════════════════════*/
                $('#anexos-wrapper').on('click', '.del-anexo', function() {
                    $.post('del_anexo.php', {
                            id: $(this).closest('tr').data('anexo')
                        },
                        loadAnexos, 'json');
                });
                /* ─── añadir nuevo ítem ───────────────────────────────────────── */
                $('#btnAddItem').off('click').on('click', e => {
                    e.preventDefault();
                    $.post('add_gasto_item.php', {
                        idGasto: idG
                    }, resp => {
                        /* resp devuelve los nuevos totales del gasto */
                        loadItems(); // vuelve a dibujar la tabla
                        refrescaResumen(resp); // actualiza Subtotal / Impuesto / Total
                    }, 'json');
                });


                /*═══════════════════════════════════════════════════════
                CAMBIAR BENEFICIARIO / EMPRESA
                ═══════════════════════════════════════════════════════*/
                $('#changeBenForm').on('submit', function(e) {
                    e.preventDefault();
                    $.post('update_gasto_beneficiario.php',
                        $(this).serialize() + '&id=' + idG, () => location.reload());
                });


                /*═══════════════════════════════════════════════════════
                CARGA INICIAL
                ═══════════════════════════════════════════════════════*/

                $(function() {
                    // ── carga inicial ──
                    loadItems();
                    loadDeds();
                    loadAnexos();
                    loadSoportes();

                    // ── función genérica de update ──
                    function updateGeneral(field, value) {
                        console.log('▶ update_gasto_general:', field, value);
                        $.post('update_gasto_general.php', {
                                id: idG,
                                field: field,
                                value: value
                            })
                            .done(resp => console.log('← respuesta:', resp))
                            .fail(err => console.error('!!! AJAX error:', err));
                    }

                    // ── delegación para date y text/select fields ──
                    $(document).on('change blur', '#field-fecha, #field-fechaVencimiento', function() {
                        updateGeneral(this.id.replace('field-', ''), this.value);
                    });
                    $(document).on('change input', '#field-prefijoFactura, #field-noFactura, #field-observaciones, #field-idEmpresa', function() {
                        updateGeneral(this.id.replace('field-', ''), this.value);
                    });
                });


                /*═══════════════════════════════════════════════════════
                BOTÓN PAGO EN CABECERA
                ═══════════════════════════════════════════════════════*/
                $('#btnPay').on('click', () => openPaymentModal([idG], benTx, idTercero));


                /* ────────────────────────────────────────────────────────────────
                Reactivar Select2 en “Cambiar Beneficiario”
                ──────────────────────────────────────────────────────────────── */
                $('#changeBenModal').on('shown.bs.modal', function() {
                    const $sel = $('#changeTercero');
                    if (!$sel.hasClass('select2-hidden-accessible')) {
                        $sel
                            .addClass('select2')
                            .select2({
                                dropdownParent: $('#changeBenModal .modal-content'),
                                ajax: {
                                    url: 'terceros_search.php',
                                    dataType: 'json',
                                    delay: 250,
                                    data: params => ({
                                        q: params.term
                                    }),
                                    processResults: data => ({
                                        results: data.results
                                    })
                                },
                                placeholder: 'Buscar beneficiario…',
                                minimumInputLength: 1,
                                width: '100%'
                            });
                    }
                    $sel.select2('open');
                });

                // Eliminar pago (relación de pagos)
                $('#resumen-gasto').on('click', '.del-pago', function() {
                    const $tr = $(this).closest('tr');
                    const idPago = Number($tr.data('id-pago') || 0);
                    if (!idPago) return;
                    if (!confirm('¿Eliminar este pago de este gasto?')) return;

                    const delFiles = confirm('¿También eliminar los soportes de este pago? (solo si el pago queda sin cruces)') ? 1 : 0;

                    $.post('delete_pago.php', {
                            idGasto: idG,
                            idPago: idPago,
                            idOrigen: <?= (int)$idOrigen ?>,
                            deleteFiles: delFiles
                        },
                        resp => {
                            if (!resp || resp.ok !== true) {
                                alert(resp?.error?.message || 'No se pudo eliminar el pago');
                                return;
                            }

                            const warnings = resp?.meta?.warnings || [];
                            if (Array.isArray(warnings) && warnings.length) {
                                alert(warnings.join('\n'));
                            }

                            // Refrescar resumen + tabla pagos
                            if (resp.data?.totales) refrescaResumen(resp.data.totales);
                            const totalGasto = resp.data?.totales?.total ?? 0;

                            function fmtCompranetDate(raw) {
                                const d = raw ? new Date(raw) : null;
                                if (!d || isNaN(d.getTime())) return '';
                                const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                                const dd = String(d.getDate()).padStart(2, '0');
                                const mon = months[d.getMonth()] || '';
                                const yy = String(d.getFullYear()).slice(-2);
                                let hh = d.getHours();
                                const ap = hh < 12 ? 'am' : 'pm';
                                hh = hh % 12;
                                if (hh === 0) hh = 12;
                                const mm = String(d.getMinutes()).padStart(2, '0');
                                return `${dd}-${mon}-${yy} ${hh}:${mm} ${ap}`;
                            }

                            const pagos = (resp.data?.pagosRelacion || []).map(p => ({
                                ...p,
                                fecha_fmt: fmtCompranetDate(p?.fecha)
                            }));
                            renderPagosRelacion(pagos, totalGasto);

                            // Si se borraron soportes del pago, quitar thumbnails del DOM.
                            if (delFiles && resp?.meta?.deletedFiles) {
                                const selector = `.soportes-pagos-gallery a[href^="/archivoDigital/soportePagos/${idPago}/"]`;
                                $(selector).remove();
                            }

                            // Ajustar badge estado (Pagado/Abonado/No Pagado) según sumaPagos
                            const sumaPagos = Number(resp.data?.gasto?.sumaPagos || 0);
                            const diff = Math.abs(Number(totalGasto || 0) - sumaPagos);
                            let text = 'Abonado';
                            let cls = 'badge bg-warning text-white';
                            if (diff <= 5) {
                                text = 'Pagado';
                                cls = 'badge bg-success text-white';
                            } else if (sumaPagos === 0) {
                                text = 'No Pagado';
                                cls = 'badge bg-danger text-white';
                            }
                            $('#statusBadgeRight').attr('class', cls + ' d-block w-100 text-center py-1').text(text);
                        }, 'json');
                });
            </script>
            <script src="/js/pago_modal.js"></script>