<?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;
//  ← después de calcular $offset
$sort = ($_GET['sort'] ?? 'fecha') === 'fecha' ? 'fecha' : 'g.fecha';
$dir  = (strtolower($_GET['dir'] ?? 'asc') === 'desc') ? 'DESC' : 'ASC';


// → 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
// → FILTROS
$filterImpresor = isset($_GET['idTercero']) && $_GET['idTercero'] !== ''
    ? intval($_GET['idTercero'])
    : '';
$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 = 3';
if ($fi !== '') $where[] = "g.id = $fi";
if ($ff !== '') $where[] = "CONCAT(g.prefijoFactura,g.noFactura) LIKE '%{$ff}%'";
if ($filterImpresor !== '') {
    $where[] = "g.idTercero = $filterImpresor";
}
$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 = 3
    $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,
  COALESCE(a.anexos,0) AS anexos,

  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      = 3 
LEFT JOIN tb_archivo_digital            ad ON ad.noFactura     = CONCAT(g.prefijoFactura,g.noFactura)
                                           AND ad.nit          = t.noDocumento
LEFT JOIN (
    SELECT gi.idGasto, COUNT(ax.id) AS anexos
    FROM   tb_contabilidad_gastos_items gi
    JOIN   tb_contabilidad_gastos_item_anexos ax
           ON ax.idGastoItem = gi.id
    GROUP  BY gi.idGasto
) a ON a.idGasto = g.id

$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.$sort $dir
          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;
}

// --- AGING POR IMPRESOR --------------------------------------------------
$sqlAging = "
SELECT  i.id,
        i.nombre,

        /* ─── Estado ─── */
        SUM(x.total)  AS total_fact,
        SUM(x.pagado) AS pagado,
        SUM(x.saldo)  AS saldo,

        /* ─── Por vencer ─── */
        SUM(CASE WHEN x.dias <= -60                  THEN x.saldo END) AS pv_60,
        SUM(CASE WHEN x.dias BETWEEN -59 AND -30     THEN x.saldo END) AS pv_30,
        SUM(CASE WHEN x.dias BETWEEN -29 AND  -8     THEN x.saldo END) AS pv_8,
        SUM(CASE WHEN x.dias < 0                     THEN x.saldo END) AS por_vencer_total,

        /* ─── Vencidos ─── */
        SUM(CASE WHEN x.dias BETWEEN  0 AND   7      THEN x.saldo END) AS v_7,
        SUM(CASE WHEN x.dias BETWEEN  8 AND  29      THEN x.saldo END) AS v_29,
        SUM(CASE WHEN x.dias BETWEEN 30 AND  59      THEN x.saldo END) AS v_59,
        SUM(CASE WHEN x.dias >=  60                  THEN x.saldo END) AS v_60,
        SUM(CASE WHEN x.dias >=  0                   THEN x.saldo END) AS vencida_total

FROM (
    SELECT  g.idTercero,
            g.total,
            COALESCE(p.sumaPagos,0)           AS pagado,
            g.total - COALESCE(p.sumaPagos,0) AS saldo,
            DATEDIFF(CURDATE(),
                     COALESCE(g.fechaVencimiento,g.fecha)) AS dias
    FROM  tb_contabilidad_gastos g
    LEFT JOIN (
        SELECT gi.idGasto,
               SUM(dt.valorPagado) AS sumaPagos
        FROM   tb_contabilidad_gastos_items gi
        JOIN   tb_contabilidad_pagos_detalle dt
               ON dt.idDocumento = gi.id
        GROUP  BY gi.idGasto
    ) p ON p.idGasto = g.id
    WHERE g.idOrigen = 3          -- sólo impresores
) x
JOIN tb_impresores i ON i.idTercero = x.idTercero
GROUP BY i.id, i.nombre
ORDER BY i.nombre";


$aging = $conn->query($sqlAging);

// --- FACTURAS DIGITAL ≠ GASTO -----------------------------
$sqlPend = "
SELECT  i.nombre            AS impresor,
        ad.fechaFactura,
        ad.noFactura,
        ad.nit
FROM    tb_archivo_digital ad
JOIN    tb_terceros        t  ON t.noDocumento = ad.nit
JOIN    tb_impresores      i  ON i.idTercero   = t.id
LEFT JOIN tb_contabilidad_gastos g
       ON g.idTercero = t.id
      AND CONCAT(g.prefijoFactura,g.noFactura) = ad.noFactura
      AND YEAR(g.fecha) = YEAR(CURDATE())
WHERE YEAR(ad.fechaFactura) = YEAR(CURDATE())
  AND g.id IS NULL           -- ← todavía no existe
ORDER BY ad.fechaFactura DESC";

$pendFact = $conn->query($sqlPend);
$pendCount  = $pendFact->num_rows;          // ← total para el badge
$pendRows   = $pendFact->fetch_all(MYSQLI_ASSOC); // ← datos para el modal

?>
<?php include '../templates/header.php'; ?>


<h1 class="h3 mb-4 text-gray-800">Pagos a Impresores</h1>
<!-- Aging cartera impresores -->
<?php
/*── acumuladores ──*/
$t_total = $t_pagado = $t_saldo = 0;
$t_pv60 = $t_pv30 = $t_pv8 = $t_pvTot = 0;
$t_v7 = $t_v29 = $t_v59 = $t_v60 = $t_vTot = 0;
?>

<div class="table-responsive mb-3">
    <table class="table table-sm table-bordered text-center">
        <thead>
            <tr>
                <th rowspan="2">Impresor</th>

                <th colspan="3">Estado</th>
                <th style="width:8px;background:#ccc" rowspan="2"></th>

                <th colspan="4" class="bg-opacity-25">Por vencer</th>
                <th style="width:8px;background:#ccc" rowspan="2"></th>

                <th colspan="5">Vencidos</th>
            </tr>
            <tr>
                <!-- Estado -->
                <th>Total</th>
                <th>Pagado</th>
                <th>Saldo</th>

                <!-- Por vencer -->
                <th>&gt; 60 d</th>
                <th>30-59 d</th>
                <th>8-29 d</th>
                <th>Total</th>

                <!-- Vencidos -->
                <th>&le; 7 d</th>
                <th>8-29 d</th>
                <th>30-59 d</th>
                <th>&ge; 60 d</th>
                <th>Total</th>
            </tr>
        </thead>

        <tbody>
            <?php while ($a = $aging->fetch_assoc()): ?>
                <tr>
                    <td class="text-start"><?= htmlspecialchars($a['nombre']) ?></td>

                    <td><?= fmt($a['total_fact']) ?></td>
                    <td><?= fmt($a['pagado']) ?></td>
                    <td><?= fmt($a['saldo']) ?></td>

                    <td class="bg-secondary" style="width:8px"></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 class="bg-secondary" style="width:8px"></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
                /*── sumar totales ──*/
                $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'];
                ?>
            <?php endwhile; ?>
        </tbody>

        <tfoot class="table-light fw-bold">
            <tr>
                <td class="text-end">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>


<button type="button" id="bulk-pay" class="btn btn-warning mb-3" disabled>
    Pagar/Abonar facturas seleccionadas
</button>
<button type="button" id="import-marcados" class="btn btn-secondary mb-3 ms-2">
    Importar Trabajos Marcados
</button>
<a href="/marcacion/trabajos.php"
    class="btn btn-primary mb-3 ms-2">
    Ir a Trabajos
</a>

<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">

        <select name="idTercero" class="form-control">
            <option value="" <?= $filterImpresor === '' ? 'selected' : '' ?>>Todos</option>
            <?php
            $rs = $conn->query("
      SELECT t.id,
             i.nombre AS etiqueta
        FROM tb_impresores i
        JOIN tb_terceros t ON i.idTercero=t.id
       ORDER BY t.nombre
    ");
            while ($imp = $rs->fetch_assoc()):
            ?>
                <option
                    value="<?= $imp['id'] ?>"
                    <?= $filterImpresor == $imp['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($imp['etiqueta']) ?>
                </option>
            <?php endwhile; ?>
        </select>

    </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>
        <button type="button"
            class="btn btn-info ms-2"
            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>
</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">
                    <?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 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';
                }

                $iconAnx = $r['anexos'] > 0 ? '<i class="fas fa-check text-purple" title="Tiene anexos"></i>' : '';

                // 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 . ' ' . $iconAnx ?></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="3">
            <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>

<!-- MODAL: Facturas digitales pendientes -->
<div class="modal fade" id="pendFactModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Facturas digitales sin gasto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-sm table-bordered align-middle">
                        <thead class="table-light text-center">
                            <tr>
                                <th>Impresor</th>
                                <th>Fecha</th>
                                <th>No. Factura</th>
                                <th>NIT</th>
                                <th>PDF</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pendRows as $p): ?>
                                <tr>
                                    <td><?= htmlspecialchars($p['impresor']) ?></td>
                                    <td class="text-center"><?= date('d-M-Y', strtotime($p['fechaFactura'])) ?></td>
                                    <td class="text-center"><strong><?= htmlspecialchars($p['noFactura']) ?></strong></td>
                                    <td class="text-center"><?= htmlspecialchars($p['nit']) ?></td>
                                    <td class="text-center">
                                        <a href="https://sistema.compranet.com.co/archivoDigital/<?= $p['nit'] ?>/<?= $p['noFactura'] ?>.pdf"
                                            target="_blank"
                                            class="btn btn-outline-secondary btn-sm">
                                            <i class="fas fa-file-pdf"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if ($pendCount === 0): ?>
                                <tr>
                                    <td colspan="5" class="text-center">Sin pendientes 🎉</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </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);
        });

        $(document).on('click', '#import-marcados', function() {
            $.post('importar_trabajos_marcados.php', {}, res => {
                if (res.success) location.reload();
                else alert('Error al importar');
            }, 'json');
        });


        // 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="soportes[]" 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>