<?php
session_start();
include '../includes/session_control.php';
include '../db/db.php';

// → FUNCIONES AUXILIARES
function fmt($val)
{
    if ($val == 0) return '-';
    return '$ ' . number_format(abs($val), 0, '', '.');
}

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';
}

// → PAGINACIÓN
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit  = 50;
$offset = ($page - 1) * $limit;

// → CREAR NUEVO GASTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $idEmpresa = intval($_POST['idEmpresa']);
    $idTercero = intval($_POST['idTercero']);
    $fecha = date('Y-m-d');
    $conn->query("
    INSERT INTO tb_contabilidad_gastos (idEmpresa, idTercero, fecha)
    VALUES ($idEmpresa, $idTercero, '$fecha')
    ");
    $newId = $conn->insert_id;
    header("Location: detalle_gasto.php?id=$newId");
    exit;
}

// → FILTROS
$fi = $_GET['filter_id']           ?? '';
$ff = $conn->real_escape_string($_GET['filter_factura']      ?? '');
$fb = $conn->real_escape_string($_GET['filter_beneficiario'] ?? '');
$fe = $_GET['filter_estado']      ?? '';


$where = [];
$where[] = 'g.idOrigen = 4';
if ($fi !== '') $where[] = "g.id = $fi";
if ($ff !== '') $where[] = "CONCAT(g.prefijoFactura,g.noFactura) LIKE '%{$ff}%'";
if ($fb !== '') $where[] = "(t.nombre LIKE '%{$fb}%' OR t.apellido LIKE '%{$fb}%' OR t.razonSocial LIKE '%{$fb}%')";
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// → CONTAR TOTAL
$countRes = $conn->query(" 
    SELECT COUNT(DISTINCT g.id)
    FROM tb_contabilidad_gastos g
    INNER JOIN tb_empresas e ON g.idEmpresa = e.id
    INNER JOIN tb_terceros t ON g.idTercero = t.id
    LEFT JOIN tb_contabilidad_pagos_facturas p
      ON p.noDocumento   = g.id AND p.idOrigen = 4
    $where_sql
");
$totalCount = intval($countRes->fetch_row()[0]);
$totalPages = max(1, ceil($totalCount / $limit));

// → CONSULTA PRINCIPAL
// → CONSULTA PRINCIPAL
$sql = "
SELECT
  g.id,
  e.sigla,
  e.nit,
  g.fecha,
  t.noDocumento                               AS nitTercero,
  CONCAT(g.prefijoFactura,g.noFactura)        AS factura,
  t.nombre,
  t.apellido,
  t.razonSocial,

  ROUND(g.subtotal,0)      AS subtotal,
  ROUND(g.impuesto,0)      AS impuesto,
  ROUND(g.deducciones,0)   AS deducciones,
  ROUND(g.total,0)         AS total_gasto,     --  ← alias distinto
  g.archivos,
  g.siigo_id,
  g.idOrigen,

  ROUND(COALESCE(SUM(dt.valorPagado),0),0)    AS sumaPagos,
  ad.total                                    AS ad_total

FROM  tb_contabilidad_gastos            g
JOIN  tb_empresas                       e  ON g.idEmpresa = e.id
JOIN  tb_terceros                       t  ON g.idTercero = t.id
LEFT JOIN tb_contabilidad_gastos_items  gi ON gi.idGasto       = g.id
LEFT JOIN tb_contabilidad_pagos_detalle dt ON dt.idDocumento   = gi.id
LEFT JOIN tb_contabilidad_pagos_facturas p ON p.id             = dt.idPagoFactura
                                           AND p.noDocumento   = g.id
                                           AND p.idOrigen      = 4 
LEFT JOIN tb_archivo_digital            ad ON ad.noFactura     = CONCAT(g.prefijoFactura,g.noFactura)
                                           AND ad.nit          = t.noDocumento
$where_sql
GROUP BY
  g.id,e.sigla,e.nit,g.fecha,factura,
  t.nombre,t.apellido,t.razonSocial,
  g.subtotal,g.impuesto,g.deducciones,g.total,
  g.archivos,g.siigo_id,ad.total";

// → FILTRAR POR ESTADO

// → FILTRAR POR ESTADO
$having = [];
if ($fe === 'no')      $having[] = 'sumaPagos = 0';
if ($fe === 'abonado') $having[] = 'sumaPagos > 0 AND sumaPagos < total_gasto';
if ($fe === 'pagado')  $having[] = 'sumaPagos = total_gasto';
if ($having) $sql .= ' HAVING ' . implode(' AND ', $having);

$sql .= "
ORDER BY g.fecha DESC
LIMIT $limit OFFSET $offset
";

$result = $conn->query($sql);
// cargar todos los orígenes para tenerlos a mano con colorHexa
$origines = [];
$orRs = $conn->query("SELECT id, nombre, colorHexa FROM tb_contabilidad_origen_pago");
while ($o = $orRs->fetch_assoc()) {
    $origines[$o['id']] = $o;
}

?>
<?php include '../templates/header.php'; ?>

<h1 class="h3 mb-4 text-gray-800">Listado de Gastos</h1>

<button class="btn btn-success mb-3" data-bs-toggle="modal" data-bs-target="#newGastoModal">
    Ingresar nuevo gasto
</button>

<button type="button" id="bulk-pay" class="btn btn-warning mb-3" disabled>
    Pagar/Abonar facturas seleccionadas
</button>
<form class="row g-2 mb-4">


    <div class="col-auto">
        <input type="text" name="filter_id" class="form-control" placeholder="No." value="<?= htmlspecialchars($fi) ?>">
    </div>
    <div class="col-auto">
        <input type="text" name="filter_factura" class="form-control" placeholder="Factura" value="<?= htmlspecialchars($ff) ?>">
    </div>
    <div class="col-auto">
        <input type="text" name="filter_beneficiario" class="form-control" placeholder="Beneficiario" value="<?= htmlspecialchars($fb) ?>">
    </div>
    <div class="col-auto">
        <select name="filter_estado" class="form-control">
            <option value="">Todos</option>
            <option value="no" <?= $fe === 'no' ? 'selected' : '' ?>>No pagado</option>
            <option value="abonado" <?= $fe === 'abonado' ? 'selected' : '' ?>>Abonado</option>
            <option value="pagado" <?= $fe === 'pagado' ? 'selected' : '' ?>>Pagado</option>
        </select>
    </div>
    <div class="col-auto">
        <button class="btn btn-primary">Filtrar</button>
        <a href="listado_gastos.php" class="btn btn-secondary ms-2">Limpiar</a>
    </div>
</form>

<div class="table-responsive mb-4">
    <table class="table table-bordered table-sm align-middle">
        <thead class="thead-light">
            <tr>
                <th class="text-center"><input type="checkbox" id="select-all"></th>
                <th class="text-center">No.</th>
                <th class="text-center">Emp</th>
                <th class="text-center">Or</th>
                <th class="text-center">Fecha</th>
                <th class="text-center">Factura</th>
                <th>Beneficiario</th>
                <th class="text-right">Subtotal</th>
                <th class="text-right">Impuesto</th>
                <th class="text-right">Deducciones</th>
                <th class="text-right">Total</th>
                <th class="text-right">Abonado</th>
                <th class="text-right">Saldo</th>
                <th class="text-center">Doc</th>
                <th class="text-center">Conc.</th>
                <th class="text-center">Siigo</th>
                <th class="text-center">Estado</th>
                <th class="text-center">Acciones</th>
            </tr>
        </thead>
        <tbody>

            <?php while ($r = $result->fetch_assoc()):

                $selOr     = $r['idOrigen'] ?? null;
                $orColor   = $origines[$selOr]['colorHexa'] ?? '#ffffff';
                $orTxtColor = getTextColor($orColor);
                // Empresa color
                $bg = $r['sigla'] === 'CPN' ? '#00cc66' : ($r['sigla'] === 'KP' ? '#800080' : '#cccccc');
                $txt = htmlspecialchars($r['sigla']);
                // Beneficiario

                $nombreCompleto = trim("{$r['nombre']} {$r['apellido']}");
                $razonSocial    = trim((string)$r['razonSocial']);

                if (!empty($razonSocial) && $razonSocial !== $nombreCompleto) {
                    $ben = "$nombreCompleto ($razonSocial)";
                } else {
                    $ben = $nombreCompleto;
                }


                if ($r['sumaPagos'] == 0) {                   // sin abonos
                    $estTxt = 'No pagado';
                    $estBg  = '#ff6666';
                } elseif ($r['sumaPagos'] == $r['total_gasto']) {
                    $estTxt = 'Pagado';
                    $estBg  = '#00cc66';
                } else {
                    $estTxt = 'Abonado';
                    $estBg  = '#ffcc00';
                }

                // Conciliación
                if ($r['ad_total'] !== null) {
                    $diff = abs($r['ad_total'] - $r['total_gasto']);
                    $iconConc = $diff > 10
                        ? '<i class="fas fa-times text-danger" title="Δ > $10"></i>'
                        : '<i class="fas fa-check text-success" title="Δ ≤ $10"></i>';
                } else {
                    $iconConc = ($r['archivos'] > 0)
                        ? '<i class="fas fa-file-image"></i>'
                        : '&ndash;';
                }
                // Siigo
                $iconS = $r['siigo_id'] ? '<strong>S</strong>' : '';
            ?>
                <tr>
                    <td class="text-center">
                        <input type="checkbox" class="select-gasto" data-id="<?= $r['id'] ?>">
                    </td>
                    <td class="text-center"><strong><?= $r['id'] ?></strong></td>
                    <td class="text-center" style="background:<?= $bg ?>;color:#fff"><?= $txt ?></td>
                    <td class="text-center">
                        <select
                            class="form-select form-select-sm js-origen"
                            data-id="<?= $r['id'] ?>"
                            style="
      background: <?= $orColor ?>;
      color: <?= $orTxtColor ?>;
      text-align: center;
      /* para que el texto también salga centrado en Firefox */
      text-align-last: center;
    ">
                            <?php foreach ($origines as $o):
                                $sel = $o['id'] == $selOr ? 'selected' : '';
                            ?>
                                <option
                                    value="<?= $o['id'] ?>"
                                    <?= $sel ?>
                                    style="background: <?= $o['colorHexa'] ?>; color: <?= getTextColor($o['colorHexa']) ?>;">
                                    <?= htmlspecialchars($o['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td class="text-center"><?= date('d-M-y', strtotime($r['fecha'])) ?></td>
                    <td class="text-center"><strong><?= htmlspecialchars($r['factura'] ?: '-') ?></strong></td>
                    <td><?= htmlspecialchars($ben) ?></td>
                    <td class="text-right"><?= fmt($r['subtotal']) ?></td>
                    <td class="text-right"><?= fmt($r['impuesto']) ?></td>
                    <td class="text-right"><?= fmt($r['deducciones']) ?></td>
                    <td class="text-right"><?= fmt($r['total_gasto']) ?></td>
                    <td class="text-right"><?= fmt($r['sumaPagos'] ?? 0) ?></td>
                    <td class="text-right"><?= fmt(($r['total_gasto'] - ($r['sumaPagos'] ?? 0))) ?></td>
                    <td class="text-center">
                        <?php
                        // Determinar existencia de cada cosa
                        $hasPdf   = (bool)$r['ad_total'];
                        $hasGasto = $r['archivos'] > 0;
                        // ¿Algún pago con archivos?
                        $hasPago  = (int)$conn
                            ->query("SELECT COUNT(*) FROM tb_contabilidad_pagos p
               JOIN tb_contabilidad_pagos_facturas pf ON pf.idPago=p.id
               WHERE pf.noDocumento={$r['id']} AND p.archivos>0")
                            ->fetch_row()[0] > 0;
                        if ($hasPdf || $hasGasto || $hasPago):
                        ?>
                            <div class="btn-group btn-group-sm">
                                <?php if ($hasPdf): ?>
                                    <button class="btn btn-outline-secondary js-open-soportes" data-id="<?= $r['id'] ?>" data-tab="pdf">
                                        <i class="fas fa-file-pdf" title="Factura PDF"></i>
                                    </button>
                                <?php endif ?>
                                <?php if ($hasGasto): ?>
                                    <button class="btn btn-outline-secondary js-open-soportes" data-id="<?= $r['id'] ?>" data-tab="gasto">
                                        <i class="fas fa-image" title="Soporte Gasto"></i>
                                    </button>
                                <?php endif ?>
                                <?php if ($hasPago): ?>
                                    <button class="btn btn-outline-secondary js-open-soportes" data-id="<?= $r['id'] ?>" data-tab="pago">
                                        <i class="fas fa-money-check-alt" title="Soporte Pago"></i>
                                    </button>
                                <?php endif ?>
                            </div>
                        <?php endif ?>
                    </td>

                    <td class="text-center"><?= $iconConc ?></td>
                    <td class="text-center"><?= $iconS ?></td>
                    <td class="text-center" style="background:<?= $estBg ?>;color:<?= getTextColor($estBg) ?>">
                        <?= $estTxt ?>
                    </td>

                    <td class="text-center">
                        <?php if ($estTxt !== 'Pagado'): ?>
                            <button class="btn btn-sm btn-warning btn-pay"
                                data-id="<?= $r['id'] ?>"
                                data-name="<?= htmlspecialchars($ben) ?>"
                                data-total="<?= $r['total_gasto'] ?>">
                                Pagar/Abonar
                            </button>
                        <?php endif ?>
                        <a href="detalle_gasto.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-primary">Ver Detalle</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- PAGINACIÓN -->
<nav>
    <ul class="pagination justify-content-center">
        <?php if ($page > 1): ?>
            <li class="page-item">
                <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">&laquo;</a>
            </li>
        <?php endif; ?>
        <?php
        $start = max(1, $page - 2);
        $end   = min($totalPages, $page + 2);
        for ($p = $start; $p <= $end; $p++):
        ?>
            <li class="page-item<?= $p == $page ? ' active' : '' ?>">
                <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
            <li class="page-item">
                <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">&raquo;</a>
            </li>
        <?php endif; ?>
    </ul>
</nav>

<?php include '../templates/footer.php'; ?>

<!-- MODAL: Nuevo Gasto -->
<div class="modal fade" id="newGastoModal"
    tabindex="-1"
    data-bs-focus="false"><!-- ← aquí -->
    <div class="modal-dialog">
        <form method="post" class="modal-content">
            <input type="hidden" name="action" value="create">
            <div class="modal-header">
                <h5 class="modal-title">Ingresar nuevo gasto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label>Empresa</label>
                    <select name="idEmpresa" class="form-control" required>
                        <?php
                        $rs = $conn->query("SELECT id, nombre FROM tb_empresas ORDER BY nombre");
                        while ($e = $rs->fetch_assoc()) {
                            echo "<option value=\"{$e['id']}\">" . htmlspecialchars($e['nombre']) . "</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label>Beneficiario</label>
                    <select id="select-tercero" name="idTercero" class="form-control" style="width:100%" required></select>
                </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">Crear Gasto</button>
            </div>
        </form>
    </div>
</div>
<!-- Modal: Vista de Soportes -->
<div class="modal fade" id="soportesModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Soportes del Gasto <span id="soportesModalTitle"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="soportesModalBody">
                <!-- Se cargará vistaSoportes.php?idGasto=… aquí -->
                <div class="text-center py-5">
                    <i class="fas fa-spinner fa-spin"></i> Cargando…
                </div>
            </div>
        </div>
    </div>
</div>

<!-- MODAL: Pago/Abono -->
<div class="modal fade" id="paymentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form id="form-pago" class="modal-content" enctype="multipart/form-data">
            <input type="hidden" name="idGasto" id="pay-idGasto">
            <input type="hidden" name="idOrigen" value="4">
            <div class="modal-header">
                <h5 class="modal-title">Realizar un pago a <span id="pay-name"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-2 mb-3">
                    <div class="col"><label>Fecha</label>
                        <input type="date" name="fecha" class="form-control" required value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="col"><label>No. Comprobante</label>
                        <input type="text" name="noComprobante" class="form-control">
                    </div>
                    <div class="col">
                        <label>Banco</label>
                        <select name="idMedio" class="form-control" required>
                            <?php
                            $rs = $conn->query("SELECT id, nombre FROM tb_medios_pago WHERE esBanco=1 ORDER BY nombre");
                            while ($b = $rs->fetch_assoc()) {
                                echo "<option value=\"{$b['id']}\">" . htmlspecialchars($b['nombre']) . "</option>";
                            }
                            ?>
                        </select>
                    </div>
                </div>

                <!-- Tabla de facturas seleccionadas -->
                <div class="table-responsive mb-3">
                    <table class="table table-sm" id="tbl-facturas">
                        <thead>
                            <tr>
                                <th>Fecha</th>
                                <th>Beneficiario</th>
                                <th>Factura</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Se llenará por JS al abrir el modal -->
                        </tbody>
                    </table>
                </div>

                <!-- Detalles de ítems -->
                <div class="table-responsive mb-3">
                    <table class="table table-sm" id="tbl-items">
                        <thead>
                            <tr>
                                <th>Descripción</th>
                                <th class="text-right">Cant.</th>
                                <th class="text-right">Vr Unit.</th>
                                <th class="text-right">SubTotal</th>
                                <th class="text-right">Total</th>
                                <th class="text-right">Abonado</th>
                                <th class="text-right">Saldo</th>
                                <th class="text-right">Vr a Pagar</th>
                            </tr>

                        </thead>
                        <tbody></tbody>
                        <tfoot>
                            <tr>
                                <th colspan="7" class="text-right">Total a Pagar:</th>
                                <th class="text-right"><span id="pay-total">0</span></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="mb-3">
                    <label>Observaciones</label>
                    <textarea name="observaciones" class="form-control" rows="2"></textarea>
                </div>

                <div class="mb-3">
                    <label>Anexar Soporte</label>
                    <div id="soportes-wrapper">
                        <div class="input-group mb-2">
                            <input type="file" name="soportePago[]" class="form-control">
                            <button type="button" class="btn btn-outline-secondary" id="add-file">+</button>
                        </div>
                    </div>
                    <small class="text-muted">También puedes pegar imágenes aquí:</small>
                    <div
                        id="clipboard-paste"
                        contenteditable="true"
                        class="form-control"
                        style="min-height:100px; max-height:150px; overflow-y:auto;"></div>

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-success">Pagar/Abonar</button>
            </div>
        </form>
    </div>
</div>

<!-- Dependencias JS -->

<script>
    $(document).on('click', '.js-open-soportes', function() {
        const idG = $(this).data('id');
        const tab = $(this).data('tab'); // 'pdf' | 'gasto' | 'pago'
        $('#soportesModalTitle').text('#' + idG);

        // Carga toda la vista y, luego, activa sólo la pestaña clicada
        $('#soportesModalBody').load('vistaSoportes.php?idGasto=' + idG, function() {
            $('#soportesModal').modal('show');
            if (tab) {
                // asegurar que existe esa pestaña y activarla
                $('#soportesTab button[data-bs-target="#tab-' + tab + '"]').tab('show');
            }
        });
    });


    $(document).on('change', '.js-origen', function() {
        const idG = $(this).data('id');
        const idOr = $(this).val();
        $.post('update_gasto_general.php', {
            id: idG,
            field: 'idOrigen',
            value: idOr
        });
    });

    $(document).on('click', '.js-view-soportes-gasto', function() {
        const id = $(this).data('id');
        $.getJSON('listado_soportes.php', {
            idGasto: id
        }, files => {
            // muestra un modal con las miniaturas
        });
    });

    $(function() {



        const pastedFiles = [];
        // habilitar/deshabilitar botón bulk
        $(document).on('change', '.select-gasto, #select-all', function() {
            const anyChecked = $('.select-gasto:checked').length > 0;
            $('#bulk-pay').prop('disabled', !anyChecked);
        });

        // select-all
        $('#select-all').on('change', function() {
            $('.select-gasto').prop('checked', this.checked).trigger('change');
        });

        // Bulk pay click
        $('#bulk-pay').on('click', function() {
            const ids = $('.select-gasto:checked').map((_, c) => c.dataset.id).get();
            openBulkPaymentModal(ids);
        });

        // Abrir modal de pago individual
        $('.btn-pay').on('click', function() {
            const id = $(this).data('id');
            const name = $(this).data('name');
            preparePaymentForm([id], name);
        });

        // Abre el modal para uno o varios gastos
        function openBulkPaymentModal(ids) {
            preparePaymentForm(ids);
        }

        // Prepara el formulario y carga tablas
        function preparePaymentForm(ids, name = '') {
            // limpiar inputs anteriores
            $('#form-pago').find('input[name="idGasto"], input[name="idsGasto[]"]').remove();

            // si es único, usamos idGasto; si varios, usamos idsGasto[]
            if (ids.length === 1) {
                $('#form-pago').append(`<input type="hidden" name="idGasto" value="${ids[0]}">`);
            } else {
                ids.forEach(id => {
                    $('#form-pago').append(`<input type="hidden" name="idsGasto[]" value="${id}">`);
                });
            }

            // nombre del beneficiario (solo si es 1)
            if (name) $('#pay-name').text(name);

            // cargar tabla de facturas
            $('#tbl-facturas tbody').empty();
            $.getJSON('get_bulk_gastos.php', {
                ids: ids
            }, facts => {
                facts.forEach(f => {
                    $('#tbl-facturas tbody').append(`
<tr>
    <td>${f.fecha}</td>
    <td>${f.beneficiario}</td>
    <td>${f.factura}</td>
</tr>
`);
                });
            });

            // cargar detalles de ítems
            $('#tbl-items tbody').empty();
            ids.forEach(id => {
                $.getJSON('get_gasto_items.php', {
                    id
                }, items => {

                    items.forEach(it => {
                        const subtotal = it.subtotalItem;
                        const total = it.totalItem;
                        const abonado = it.abonadoItem;
                        const saldo = parseFloat(it.totalItem) - parseFloat(it.abonadoItem);

                        $('#tbl-items tbody').append(`
<tr>
    <td>${it.description}</td>
    <td class="text-right">${it.cantidad}</td>
    <td class="text-right">${parseFloat(it.valorUnitarioGasto).toLocaleString('es-CO',{minimumFractionDigits:0})}</td>
    <td class="text-right">${parseFloat(subtotal).toLocaleString('es-CO',{minimumFractionDigits:0})}</td>
    <td class="text-right">${parseFloat(total).toLocaleString('es-CO',{minimumFractionDigits:0})}</td>
    <td class="text-right">${parseFloat(abonado).toLocaleString('es-CO',{minimumFractionDigits:0})}</td>
    <td class="text-right">${parseFloat(saldo).toLocaleString('es-CO',{minimumFractionDigits:0})}</td>
    <td class="text-right">
        <input type="hidden" name="itemId[]" value="${it.id}">
        <input type="hidden" name="totalItem[]" value="${parseFloat(total).toFixed(0)}">

        ${saldo > 0
        ? `<input
            type="number"
            step="1"
            name="valorPagado[]"
            class="form-control form-control-sm pay-val text-right"
            value="${saldo.toFixed(0)}"
            min="0"
            max="${saldo.toFixed(0)}" />`
        : '-'
        }
    </td>
</tr>
`);
                    });


                    recalc();
                });
            });

            $('#paymentModal').modal('show');
        }

        // Recalcular total
        $('#tbl-items').on('input', '.pay-val', recalc);

        function recalc() {
            let sum = 0;
            $('.pay-val').each((_, el) => sum += parseFloat($(el).val().replace(/\./g, '')) || 0);
            $('#pay-total').text(sum.toLocaleString('es-CO', {
                minimumFractionDigits: 0
            }));
        }

        // Añadir/quitar soporte manual
        $('#add-file').on('click', () => {
            $('#soportes-wrapper').append(`
<div class="input-group mb-2">
    <input type="file" name="soportePago[]" class="form-control">
    <button type="button" class="btn btn-outline-danger remove-file">×</button>
</div>
`);
        });
        $('#soportes-wrapper').on('click', '.remove-file', function() {
            $(this).closest('.input-group').remove();
        });


        // 1) Pegar imágenes desde portapapeles
        $('#clipboard-paste').on('paste', function(e) {
            // Evitamos que el navegador inserte la imagen como <img …>
            e.preventDefault();

            // e.originalEvent para eventos de jQuery
            const files = (e.originalEvent || e).clipboardData.files;
            if (!files.length) return; // Nada que procesar

            for (const file of files) {
                pastedFiles.push(file); // 1) guardamos para el submit

                // 2) mini-preview
                const url = URL.createObjectURL(file);
                $('#clipboard-paste').append(
                    $('<img>', {
                        src: url
                    })
                    .css({
                        maxWidth: 100,
                        maxHeight: 100,
                        margin: 4,
                        objectFit: 'contain'
                    })
                );
            }
        });


        // 2) Enviar pago por AJAX
        $('#form-pago').on('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);

            pastedFiles.forEach((file, idx) => {
                // Si file.name está vacío → inventamos uno con hora y extensión
                let fname = (file.name && file.name.trim() !== '') ?
                    file.name :
                    `clipboard_${Date.now()}_${idx}.${(file.type.split('/').pop() || 'png')}`;

                formData.append('soportePago[]', file, fname);
            });



            $.ajax({
                url: '../pagos/procesar_pago.php',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                dataType: 'json',
                success(res) {
                    if (res.success) {
                        $('#paymentModal').modal('hide');
                        location.reload();
                    }
                }

            });
        });
    });
    $('#newGastoModal').on('shown.bs.modal', function() {

        const $sel = $('#select-tercero');

        /*  ¿Ya existe Select2? -> solo abrirlo   */
        if ($sel.hasClass('select2-hidden-accessible')) {
            $sel.select2('open');
            return;
        }

        $sel.select2({
            ajax: {
                url: 'terceros_search.php',
                dataType: 'json',
                delay: 250,
                data: p => ({
                    q: p.term
                }),
                processResults: d => ({
                    results: d.results
                })
            },
            placeholder: 'Buscar beneficiario…',
            minimumInputLength: 1,

            /*  ⬇⬇  Cambiado: ahora está dentro de .modal-content  */
            dropdownParent: $(this).find('.modal-content'),
            width: '100%'
        }).one('select2:opening', () => {
            /*  Esperamos al 1er apertura para pasar foco al input  */
            setTimeout(() =>
                $('.select2-container--open .select2-search__field').focus(), 0);
        }).select2('open');
    });
</script>