<?php

/**
 *  gastos_generales.php  –  Único archivo para ORÍGENES 1-7
 *  Ramiro Zapata · Sistema Compranet · 2025-05-28
 *
 *  Orígenes (tb_contabilidad_origen_pago):
 *    1  Proveedores          -> tb_proveedores
 *    2  Envíos               -> tb_proveedor_envio
 *    3  Impresores           -> tb_impresores
 *    4  Gastos generales     -> —
 *    5  Créditos             -> tb_medios_pago  (esTC=1)
 *    6  Comisión de Ventas   -> tb_medios_pago  (esTC=0 AND esRecaudador=1)
 *    7  Gastos bancarios     -> tb_medios_pago  (esTC=0 AND esRecaudador=0)
 *
 *  Cada origen:
 *    – muestra cartera (aging) por tercero + SaldoInicial
 *    – botones Importar / Ir a trabajos → usa Procedimiento / Ruta de la tabla origenes
 *    – filtros:  select (listas) o input libre (origen 4)
 */

/*───────────────────  CONFIG  ───────────────────*/
session_start();
include '../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

// Origen recibido
$idOrigen = intval($_GET['or'] ?? 1);

/*───────────────────  AUX  ───────────────────*/
function fmt($v)
{
    return $v == 0 ? '-' : '$ ' . number_format(abs($v), 0, '', '.');
}
function txt($s)
{
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
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';
}

$token = cpn_node_token_or_fail();
$nodeBase = cpn_node_api_base();

$fi = $_GET['filter_id'] ?? '';
$ff = $_GET['filter_factura'] ?? '';
$fb = $_GET['filter_beneficiario'] ?? '';
$fe = $_GET['filter_estado'] ?? '';
$ft = $_GET['idTercero'] ?? '';

$hasActiveFilters = trim((string)$fi) !== ''
    || trim((string)$ff) !== ''
    || trim((string)$fb) !== ''
    || trim((string)$fe) !== ''
    || trim((string)$ft) !== '';

$showAllRequested = isset($_GET['show_all']) && in_array(strtolower((string)$_GET['show_all']), ['1', 'true', 'si', 'yes'], true);
$showAllMode = $showAllRequested && $hasActiveFilters;
$qsShowAll = array_merge($_GET, ['show_all' => 1, 'page' => 1]);
$qsPaged = $_GET;
unset($qsPaged['show_all']);
$qsPaged['page'] = 1;

// 1) Manejar creación de gasto mínimo (DB sólo en Node)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $idEmpresa = intval($_POST['idEmpresa'] ?? 0);
    $idTercero = intval($_POST['idTercero'] ?? 0);

    $respCreate = cpn_node_request('POST', $nodeBase . '/api/gastos/generales/create', $token, [
        'idOrigen' => $idOrigen,
        'idEmpresa' => $idEmpresa,
        'idTercero' => $idTercero,
    ]);

    if (!($respCreate['ok'] ?? false)) {
        $msg = $respCreate['error']['message'] ?? 'Error creando gasto';
        die($msg);
    }

    $newId = intval($respCreate['data']['id'] ?? 0);
    if ($newId <= 0) {
        die('Respuesta inválida al crear gasto');
    }

    header("Location: detalle_gasto.php?id={$newId}");
    exit;
}

// 2) Cargar datos de la vista desde Node (DB sólo en Node)
$params = $_GET;
$params['or'] = $idOrigen;

$resp = cpn_node_request(
    'GET',
    $nodeBase . '/api/gastos/generales/view?' . http_build_query($params),
    $token,
    null
);

if (!($resp['ok'] ?? false)) {
    $msg = $resp['error']['message'] ?? 'Error cargando datos';
    die($msg);
}

$view = $resp['data'] ?? [];

if ($showAllMode) {
    $allRows = $view['rows'] ?? [];
    $apiTotalPages = intval($view['totalPages'] ?? 1);

    for ($p = 2; $p <= $apiTotalPages; $p++) {
        $paramsPage = $params;
        $paramsPage['page'] = $p;

        $respPage = cpn_node_request(
            'GET',
            $nodeBase . '/api/gastos/generales/view?' . http_build_query($paramsPage),
            $token,
            null
        );

        if (!($respPage['ok'] ?? false)) {
            break;
        }

        $rowsPage = $respPage['data']['rows'] ?? [];
        if ($rowsPage) {
            $allRows = array_merge($allRows, $rowsPage);
        }
    }

    $view['rows'] = $allRows;
    $view['page'] = 1;
    $view['totalPages'] = 1;
}

$config = $view['config'] ?? [];
$agSel = $config;

$meta = $view['meta'] ?? [];
$OR_NAME  = $meta['nombre'] ?? '';
$OR_COLOR = $meta['colorHexa'] ?? '#000000';
$OR_PROC  = $meta['procedimiento'] ?? '';
$OR_RUTA  = $meta['ruta'] ?? '';

$origenes = $view['origenes'] ?? [];
$empresas = $view['empresas'] ?? [];
$bancos = $view['bancos'] ?? [];

$origines = [];
foreach ($origenes as $o) {
    if (isset($o['id'])) $origines[$o['id']] = $o;
}

// Paginación
$page = intval($view['page'] ?? 1);
$totalPages = intval($view['totalPages'] ?? 1);
$sort = $view['sort'] ?? 'fecha';
$dir = $view['dir'] ?? 'DESC';

$rows = $view['rows'] ?? [];
$aging = $view['aging'] ?? null;
$filterOptions = $view['filterOptions'] ?? [];
$pendRows = $view['pendRows'] ?? [];
$pendCount = intval($view['pendCount'] ?? 0);
/*───────────────────  HTML  ───────────────────*/
?>
<?php include '../templates/header.php'; ?>

<style>
    /* Compacto (solo esta pantalla) */
    #content .container-fluid .table {
        font-size: 12px;
    }

    #content .container-fluid .table th,
    #content .container-fluid .table td {
        padding: .25rem .35rem;
        line-height: 1.15;
    }

    #content .container-fluid .form-control,
    #content .container-fluid .custom-select,
    #content .container-fluid .form-select {
        font-size: 12px !important;
        padding: .2rem .4rem;
        height: calc(1.2em + .5rem + 2px);
    }

    #content .container-fluid .btn {
        font-size: 12px;
        padding: .25rem .5rem;
    }

    #content .container-fluid h1.h3,
    #content .container-fluid .h3 {
        font-size: 1.1rem;
    }

    #content .container-fluid .pagination .page-link {
        font-size: 12px;
        padding: .25rem .5rem;
    }
</style>

<!-- Botonera cambio de origen -->
<div class="mb-3">
    <?php
    foreach (($origenes ?? []) as $o) {
        $cls = $o['id'] == $idOrigen ? 'btn-primary' : 'btn-outline-primary';
        echo "<a class='btn $cls me-1 mb-1' href='?or={$o['id']}'>" . txt($o['nombre']) . "</a>";
    }
    ?>
</div>

<h1 class="h3 mb-4" style="color:<?= getTextColor($OR_COLOR) ?>;background:<?= $OR_COLOR ?>;padding:.4rem .8rem">
    <?= txt($OR_NAME) ?>
</h1>

<?php /*──────────  Aging (si aplica)  ──────────*/ ?>
<?php if ($aging): ?>
    <?php
    $t_total = $t_pagado = $t_saldo = $t_pv60 = $t_pv30 = $t_pv8 = $t_pvTot = $t_v7 = $t_v29 = $t_v59 = $t_v60 = $t_vTot = 0;
    ?>
    <div class="table-responsive mb-4">
        <table class="table table-sm table-bordered text-center">
            <thead class="table-light">
                <tr>
                    <th rowspan="2"><?= txt($agSel['etq']) ?></th>
                    <th colspan="3">Estado</th>
                    <th style="width:8px;background:#ccc" rowspan="2"></th>
                    <th colspan="4">Por vencer</th>
                    <th style="width:8px;background:#ccc" rowspan="2"></th>
                    <th colspan="5">Vencidos</th>
                </tr>
                <tr>
                    <th>Total</th>
                    <th>Pagado</th>
                    <th>Saldo</th>
                    <th>>60d</th>
                    <th>30-59d</th>
                    <th>8-29d</th>
                    <th>Total</th>
                    <th>≤7d</th>
                    <th>8-29d</th>
                    <th>30-59d</th>
                    <th>≥60d</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach (($aging ?? []) as $a): ?>
                    <tr>
                        <td class="text-start">
                            <a href="movimiento_tercero.php?id=<?= $a['idTercero'] ?>"
                                target="_blank"
                                style="text-decoration:none;color:inherit">
                                <?= txt($a['nombre']) ?>
                                <i class="fas fa-arrow-right ms-1"></i>
                            </a>
                        </td>
                        <td><?= fmt($a['total_fact']) ?></td>
                        <td><?= fmt($a['pagado']) ?></td>
                        <td><?= fmt($a['saldo']) ?></td>
                        <td style="background:#ccc"></td>
                        <td><?= fmt($a['pv_60']) ?></td>
                        <td><?= fmt($a['pv_30']) ?></td>
                        <td><?= fmt($a['pv_8']) ?></td>
                        <td><?= fmt($a['por_vencer_total']) ?></td>
                        <td style="background:#ccc"></td>
                        <td><?= fmt($a['v_7']) ?></td>
                        <td><?= fmt($a['v_29']) ?></td>
                        <td><?= fmt($a['v_59']) ?></td>
                        <td><?= fmt($a['v_60']) ?></td>
                        <td><?= fmt($a['vencida_total']) ?></td>
                    </tr>
                <?php
                    $t_total += $a['total_fact'];
                    $t_pagado += $a['pagado'];
                    $t_saldo += $a['saldo'];
                    $t_pv60 += $a['pv_60'];
                    $t_pv30 += $a['pv_30'];
                    $t_pv8 += $a['pv_8'];
                    $t_pvTot += $a['por_vencer_total'];
                    $t_v7 += $a['v_7'];
                    $t_v29 += $a['v_29'];
                    $t_v59 += $a['v_59'];
                    $t_v60 += $a['v_60'];
                    $t_vTot += $a['vencida_total'];
                endforeach; ?>
            </tbody>
            <tfoot class="table-light fw-bold">
                <tr>
                    <td class="text-right">Totales ▶</td>
                    <td><?= fmt($t_total) ?></td>
                    <td><?= fmt($t_pagado) ?></td>
                    <td><?= fmt($t_saldo) ?></td>
                    <td style="background:#ccc"></td>
                    <td><?= fmt($t_pv60) ?></td>
                    <td><?= fmt($t_pv30) ?></td>
                    <td><?= fmt($t_pv8) ?></td>
                    <td><?= fmt($t_pvTot) ?></td>
                    <td style="background:#ccc"></td>
                    <td><?= fmt($t_v7) ?></td>
                    <td><?= fmt($t_v29) ?></td>
                    <td><?= fmt($t_v59) ?></td>
                    <td><?= fmt($t_v60) ?></td>
                    <td><?= fmt($t_vTot) ?></td>
                </tr>
            </tfoot>
        </table>
    </div>
<?php endif; ?>

<!-- Botones especiales -->
<div class="mb-3">
    <?php if ($idOrigen !== 4): ?>
        <button id="import-marcados" class="btn btn-secondary me-2">
            Importar Gastos <?= txt($OR_NAME) ?>
        </button>
    <?php endif; ?>

    <?php if ($OR_RUTA): ?>
        <a href="<?= $OR_RUTA ?>" class="btn btn-primary me-2">Ir al listado</a>
    <?php endif; ?>
    <button class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#newGastoModal">Ingresar nuevo gasto</button>
    <button id="bulk-pay" class="btn btn-warning me-2" disabled>Pagar/Abonar facturas seleccionadas</button>
    <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#pendFactModal">
        Facturas pendientes
        <?php if ($pendCount > 0): ?>
            <span class="badge bg-danger"><?= $pendCount ?></span>
        <?php endif; ?>
    </button>

</div>

<!-- Filtros -->
<form class="row g-2 mb-4">
    <input type="hidden" name="or" value="<?= $idOrigen ?>">
    <div class="col-auto"><input name="filter_id" class="form-control" placeholder="No." value="<?= txt($fi) ?>"></div>
    <div class="col-auto"><input name="filter_factura" class="form-control" placeholder="Factura" value="<?= txt($ff) ?>"></div>

    <?php if ($agSel['filter'] === 'select'): ?>
        <div class="col-auto">
            <select name="idTercero" class="form-control">
                <option value="">Todos los <?= txt($agSel['etq']) ?></option>
                <?php foreach ($filterOptions as $opt): ?>
                    <option value="<?= $opt['id'] ?>" <?= $ft == $opt['id'] ? 'selected' : '' ?>><?= txt($opt['etiqueta']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    <?php else: /* origen 4 */ ?>
        <div class="col-auto">
            <input name="filter_beneficiario" class="form-control" placeholder="Beneficiario" value="<?= txt($fb) ?>">
        </div>
    <?php endif; ?>

    <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></div>
    <?php if ($hasActiveFilters && !$showAllMode): ?>
        <div class="col-auto">
            <a class="btn btn-outline-secondary" href="?<?= http_build_query($qsShowAll) ?>">
                Mostrar todo
            </a>
        </div>
    <?php endif; ?>
    <?php if ($showAllMode): ?>
        <div class="col-auto">
            <a class="btn btn-outline-secondary" href="?<?= http_build_query($qsPaged) ?>">
                Volver a paginar
            </a>
        </div>
    <?php endif; ?>
</form>

<!-- LISTADO PRINCIPAL -->
<div class="table-responsive mb-4">
    <table class="table table-bordered table-sm align-middle">
        <thead class="table-light">
            <tr>
                <th><input type="checkbox" id="select-all"></th>
                <th>No.</th>
                <th>Emp</th>
                <th>Or</th>
                <th class="text-center">
                    <?php
                    $nextDir = ($sort === 'fecha' && $dir === 'ASC') ? 'desc' : 'asc';
                    $arrow   = ($sort === 'fecha') ? ($dir === 'ASC' ? ' ▲' : ' ▼') : '';
                    ?>
                    <a href="?<?= http_build_query(array_merge($_GET, [
                                    'sort' => 'fecha',
                                    'dir' => $nextDir
                                ])) ?>">Fecha<?= $arrow ?></a>
                </th>
                <th>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 foreach (($rows ?? []) as $r):
                $selOr        = $r['idOrigen'];
                $orColor      = $origines[$selOr]['colorHexa'];
                $orTxt        = getTextColor($orColor);
                $bg           = $r['empColor'];
                $nombreCompleto = trim($r['nombre'] . ' ' . $r['apellido']);
                $ben          = $r['razonSocial'] && $r['razonSocial'] != $nombreCompleto
                    ? "$nombreCompleto ({$r['razonSocial']})"
                    : $nombreCompleto;

                // cálculo de saldo y estado con umbral de 5 pesos
                $diff         = $r['total'] - $r['sumaPagos'];
                $saldoDisplay = abs($diff) < 5 ? '-' : fmt($diff);
                if ($r['sumaPagos'] == 0) {
                    $estTxt = 'No pagado';
                } elseif (abs($diff) < 5 || $r['sumaPagos'] == $r['total']) {
                    $estTxt = 'Pagado';
                } else {
                    $estTxt = 'Abonado';
                }
                $estBg = $estTxt === 'No pagado'
                    ? '#ff6666'
                    : ($estTxt === 'Pagado' ? '#00cc66' : '#ffcc00');

                // resto de íconos y comprobaciones
                $iconConc = '&ndash;';
                if ($r['ad_total'] !== null) {
                    $diffConc = abs($r['ad_total'] - $r['total']);
                    $iconConc = $diffConc > 10
                        ? '<i class="fas fa-times text-danger"></i>'
                        : '<i class="fas fa-check text-success"></i>';
                } elseif ($r['archivos'] > 0) {
                    $iconConc = '<i class="fas fa-file-image"></i>';
                }
                $iconS   = $r['siigo_id'] ? '<strong>S</strong>' : '';
                $iconAnx = $r['anexos'] > 0
                    ? '<i class="fas fa-check text-purple" title="Tiene anexos"></i>'
                    : '';
            ?>
                <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: <?= htmlspecialchars($bg) ?>; color: <?= getTextColor($bg) ?>;">
                        <strong><?= txt($r['sigla']) ?></strong>
                    </td>
                    <td class="text-center">
                        <select class="form-select form-select-sm js-origen" data-id="<?= $r['id'] ?>"
                            style="background:<?= $orColor ?>;color:<?= getTextColor($orColor) ?>;
                       text-align:center;text-align-last:center">
                            <?php foreach ($origines as $o): ?>
                                <option value="<?= $o['id'] ?>"
                                    <?= $o['id'] == $selOr ? 'selected' : '' ?>
                                    style="background:<?= $o['colorHexa'] ?>;
                               color:<?= getTextColor($o['colorHexa']) ?>">
                                    <?= txt($o['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td class="text-center">
                        <?= date('d-M-y', strtotime($r['fecha'])) ?>
                    </td>
                    <td class="text-center">
                        <strong><?= txt($r['factura'] ?: '-') ?></strong>
                    </td>
                    <td><?= txt($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']) ?></td>
                    <td class="text-right"><?= fmt($r['sumaPagos']) ?></td>
                    <!-- SALDO con umbral de 5 pesos -->
                    <td class="text-right"><?= $saldoDisplay ?></td>
                    <!-- ESTADO con color según No pagado / Pagado / Abonado -->
                    <td class="text-center"
                        style="background:<?= $estBg ?>;color:<?= getTextColor($estBg) ?>">
                        <?= $estTxt ?>
                    </td>
                    <td class="text-center">
                        <div class="btn-group btn-group-sm">
                            <?php if ($r['ad_total'] !== null): ?>
                                <button class="btn btn-outline-secondary js-open-soportes"
                                    data-id="<?= $r['id'] ?>" data-tab="pdf">
                                    <i class="fas fa-file-pdf"></i>
                                </button>
                            <?php endif; ?>
                            <?php if ($r['archivos'] > 0): ?>
                                <button class="btn btn-outline-secondary js-open-soportes"
                                    data-id="<?= $r['id'] ?>" data-tab="gasto">
                                    <i class="fas fa-image"></i>
                                </button>
                            <?php endif; ?>
                            <?php if (($r['pagosConArchivos'] ?? 0) > 0): ?>
                                <button class="btn btn-outline-secondary js-open-soportes"
                                    data-id="<?= $r['id'] ?>" data-tab="pago">
                                    <i class="fas fa-money-check-alt"></i>
                                </button>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td class="text-center"><?= $iconConc . ' ' . $iconAnx ?></td>
                    <td class="text-center"><?= $iconS ?></td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-warning btn-pay"
                            data-id="<?= $r['id'] ?>"
                            data-name="<?= txt($ben) ?>"
                            data-tercero="<?= $r['idTercero'] ?>"
                            <?= $estTxt === 'Pagado' ? 'disabled' : '' ?>>
                            Pagar/Abonar
                        </button>

                        <a href="detalle_gasto.php?id=<?= $r['id'] ?>"
                            class="btn btn-sm btn-primary">Ver Detalle</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>

    </table>
</div>

<!-- Paginación -->
<?php if (!$showAllMode): ?>
    <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 for ($p = max(1, $page - 2); $p <= min($totalPages, $page + 2); $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 endif; ?>


<?php include '../templates/footer.php'; ?>
<script src="/js/pago_modal.js"></script>

<!-- MODALES reutilizados (Nuevo Gasto, Soportes, Pago, Pendientes) -->
<?php include 'modals_gastos_reusable.php'; ?>

<!-- JS específico -->
<!-- JS específico del listado -->
<script>
    /* Soportes modal */
    $(document).on('click', '.js-open-soportes', function() {
        const idG = $(this).data('id');
        const tab = $(this).data('tab');
        $('#soportesModalTitle').text('#' + idG);
        $('#soportesModalBody').load('vistaSoportes.php?idGasto=' + idG, () => {
            $('#soportesModal').modal('show');
            if (tab) $('#soportesTab button[data-bs-target="#tab-' + tab + '"]').tab('show');
        });
    });

    /* Cambio de origen inline */
    $(document).on('change', '.js-origen', function() {
        $.post('update_gasto_general.php', {
            id: $(this).data('id'),
            field: 'idOrigen',
            value: $(this).val()
        });
    });

    /* Select-all y habilitar pago masivo */
    $(function() {
        $('#select-all').on('change', function() {
            $('.select-gasto').prop('checked', this.checked).trigger('change');
        });

        $(document).on('change', '.select-gasto', function() {
            const marked = $('.select-gasto:checked').length;
            $('#bulk-pay').prop('disabled', marked === 0);
        });
    });

    /* Botón de pago masivo */
    $('#bulk-pay').on('click', () => {
        const ids = $('.select-gasto:checked').map((_, c) => c.dataset.id).get();
        openPaymentModal(ids); // <- función global del js compartido
    });

    /* Botón de pago individual */
    $(document).on('click', '.btn-pay', function() {
        const idGasto = $(this).data('id');
        const nombre = $(this).data('name');
        const idTercero = $(this).data('tercero');
        openPaymentModal([idGasto], nombre, idTercero);
    });


    <?php if ($idOrigen !== 4): ?>
        $('#import-marcados').on('click', function() {
            $.post(
                'importar_gastos.php?id=<?= $idOrigen ?>', {},
                res => {
                    if (res.success) location.reload();
                    else alert('Error');
                },
                'json'
            );
        });
    <?php endif; ?>

    /* Select2 en modal "Nuevo gasto" */
    $('#newGastoModal').on('shown.bs.modal', function() {
        const $sel = $('#select-tercero');
        if (!$sel.hasClass('select2-hidden-accessible')) {
            $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,
                dropdownParent: $(this).find('.modal-content'),
                width: '100%'
            });
        }
        $sel.select2('open');
    });
</script>
