<?php
session_start();
include '../includes/session_control.php';
include '../db/db.php';

// 1) Validar y obtener idTercero
$idTercero = intval($_GET['id'] ?? 0);
if (!$idTercero) {
    die('ID de tercero inválido.');
}

// 2) Traer datos del tercero
$stmt = $conn->prepare("
    SELECT nombre, apellido, razonSocial, saldoInicial
    FROM tb_terceros
    WHERE id = ?
");
$stmt->bind_param('i', $idTercero);
$stmt->execute();
$stmt->bind_result($nombre, $apellido, $razonSocial, $saldoInicial);
$stmt->fetch();
$stmt->close();

// 3) Preparar consulta de movimientos (gastos y pagos)
// movimiento_tercero.php, reemplaza la parte del $sql por:
$sql = "
SELECT mov.fecha,
 mov.idRef,     
       mov.doc,
       mov.concepto,
       mov.fact,
       mov.pago,
       mov.orden
FROM (
    /* 1) Gastos (uno por cada gasto) */
    SELECT 
        g.id               AS idRef,
        g.fecha            AS fecha,
        CONCAT(g.prefijoFactura, g.noFactura) AS doc,
        GROUP_CONCAT(gi.description ORDER BY gi.id SEPARATOR ', ') AS concepto,
        ROUND(g.total,0)   AS fact,
        0                  AS pago,
        1                  AS orden
    FROM tb_contabilidad_gastos       g
    LEFT JOIN tb_contabilidad_gastos_items gi ON gi.idGasto = g.id
    WHERE g.idTercero = ?
    GROUP BY g.id

   UNION ALL

/* 2) Pagos */
SELECT 
    p.id               AS idRef,
    p.fecha            AS fecha,
    p.noComprobante    AS doc,
    mp.nombre          AS concepto,            -- ← medio de pago
    0                  AS fact,
    ROUND(p.totalPago,0) AS pago,
    2                  AS orden
FROM tb_contabilidad_pagos p
JOIN tb_medios_pago mp
  ON mp.id = p.idMedio                      -- ← join a medios de pago
JOIN tb_contabilidad_pagos_facturas pf
  ON pf.idPago = p.id
JOIN tb_contabilidad_gastos g
  ON g.id        = pf.noDocumento
 AND pf.idOrigen = g.idOrigen
WHERE g.idTercero = ?
GROUP BY p.id                                  -- ← un pago = una sola fila
) AS mov
ORDER BY mov.fecha, mov.orden, mov.idRef
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ii', $idTercero, $idTercero);
$stmt->execute();
$result = $stmt->get_result();

?>

<?php include '../templates/header.php'; ?>

<h1 class="h4 mb-4">
    Movimiento de: <?= htmlspecialchars("$nombre $apellido") ?>
    <?php if ($razonSocial): ?> (<?= htmlspecialchars($razonSocial) ?>)<?php endif; ?>
</h1>

<table class="table table-sm table-bordered">
    <thead class="table-light">
        <tr>
            <th>Fecha</th>
            <th>Doc</th>
            <th>Concepto</th>
            <th class="text-right">Fact</th>
            <th class="text-right">Pago</th>
            <th class="text-right">Saldo</th>
            <th>Soporte</th> <!-- ← nueva cabecera -->
        </tr>
    </thead>
    <tbody>
        <?php
        // 4) Mostrar saldo inicial
        $balance   = $saldoInicial;
        echo '<tr class="fw-bold">'
            . '<td colspan="5">Saldo Inicial</td>'
            . '<td class="text-right">' . number_format($balance, 0, ',', '.') . '</td>'
            . '<td></td>'
            . '</tr>';

        $currentMonth = null;
        $subFact = $subPago = 0;

        while ($row = $result->fetch_assoc()) {
            $fecha = $row['fecha'];
            $mes   = date('Y-m', strtotime($fecha));

            // 5) Al cambiar de mes, imprimir subtotal del mes anterior
            if ($currentMonth !== null && $mes !== $currentMonth) {
                echo '<tr class="table-secondary fw-bold">'
                    . '<td colspan="3">Subtotal ' . date('M Y', strtotime($currentMonth . '-01')) . '</td>'
                    . '<td class="text-right">' . number_format($subFact, 0, ',', '.') . '</td>'
                    . '<td class="text-right">' . number_format($subPago, 0, ',', '.') . '</td>'
                    . '<td></td>'
                    . '</tr>';
                $subFact = $subPago = 0;
            }
            $currentMonth = $mes;

            // 6) Calcular nuevo balance
            $fact = (float)$row['fact'];
            $pago = (float)$row['pago'];
            $balance += $fact - $pago;
            $subFact += $fact;
            $subPago += $pago;

            // 7) Renderizar fila de movimiento
            echo '<tr>'
                . '<td>' . date('d-M-Y', strtotime($fecha)) . '</td>'
                . '<td>' . htmlspecialchars($row['doc']) . '</td>'
                . '<td>' . htmlspecialchars($row['concepto']) . '</td>'
                . '<td class="text-right">' . ($fact ? number_format($fact, 0, ',', '.') : '') . '</td>'
                . '<td class="text-right">' . ($pago ? number_format($pago, 0, ',', '.') : '') . '</td>'
                . '<td class="text-right">' . number_format($balance, 0, ',', '.') . '</td>'
                // ← Nueva columna Soporte:
                . '<td class="text-center">
       <button
         class="btn btn-sm btn-outline-secondary js-open-soportes"
         data-id="' . $row['idRef'] . '"
         data-tab="' . ($row['orden'] === 1 ? 'gasto' : 'pago') . '">
         <i class="fas fa-image"></i>
       </button>
     </td>'
                . '</tr>';
        }

        // 8) Subtotal del último mes
        if ($currentMonth !== null) {
            echo '<tr class="table-secondary fw-bold">'
                . '<td colspan="3">Subtotal ' . date('M Y', strtotime($currentMonth . '-01')) . '</td>'
                . '<td class="text-right">' . number_format($subFact, 0, ',', '.') . '</td>'
                . '<td class="text-right">' . number_format($subPago, 0, ',', '.') . '</td>'
                . '<td></td>'
                . '<td></td>'  // <-- Soporte vacío
                . '</tr>';
        }
        ?>
    </tbody>
</table>

<!-- MODAL: 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 Movimiento <span id="soportesModalTitle"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="soportesModalBody">
                <div class="text-center py-5">
                    <i class="fas fa-spinner fa-spin"></i> Cargando…
                </div>
            </div>
        </div>
    </div>
</div>
<?php include '../templates/footer.php'; ?>
<script>
    $(document).on('click', '.js-open-soportes', function() {
        const id = $(this).data('id');
        const tab = $(this).data('tab'); // 'gasto' | 'pago'
        $('#soportesModalTitle').text('#' + id);
        // incluimos el parámetro tab para que vistaSoportes lo reciba
        $('#soportesModalBody')
            .load('vistaSoportes.php?idGasto=' + id + '&tab=' + tab, function() {
                $('#soportesModal').modal('show');
                if (tab) {
                    // activa la pestaña correcta
                    $('#soportesTab button[data-bs-target="#tab-' + tab + '"]').tab('show');
                }
            });
    });
</script>