<?php
// vistaSoportes.php
session_start();
include '../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$idG = intval($_GET['idGasto'] ?? 0);
if (!$idG) {
    echo "ID inválido";
    exit;
}

// ¿PDF?
// 1) factura electrónica
$factura = '';
$nit = '';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$resp = cpn_node_request('GET', $base . '/api/gastos/soportes/meta?idGasto=' . urlencode((string)$idG), $token, null);
if (!($resp['ok'] ?? false)) {
    echo '<p class="text-center text-danger">Error cargando soportes.</p>';
    exit;
}

$meta = $resp['data'] ?? [];
$r = $meta['factura'] ?? null;
if (is_array($r) && !empty($r['prefijoFactura'])) {
    $nit = $r['nit'] ?? '';
    $factura = "/archivoDigital/{$nit}/{$r['prefijoFactura']}{$r['noFactura']}.pdf";
}

// 2) soportes gasto
$gDir = __DIR__ . "/../archivoDigital/soporteGastos/$idG";
$gFiles = is_dir($gDir)
    ? array_values(array_filter(scandir($gDir), fn($f) => !in_array($f, ['.', '..', 'Thumbs.db'])))
    : [];

// 3) pagos + tabla y soportes pago
$pagos = [];
foreach (($meta['pagos'] ?? []) as $p) {
    if (!is_array($p) || empty($p['id'])) continue;
    $pid = (int)$p['id'];

    // galería
    $pd = [];
    $pDir = __DIR__ . "/../archivoDigital/soportePagos/{$pid}";
    if (is_dir($pDir)) {
        foreach (scandir($pDir) as $f) {
            if (in_array($f, ['.', '..', 'Thumbs.db'])) continue;
            $pd[] = "/archivoDigital/soportePagos/{$pid}/{$f}";
        }
    }
    $p['files'] = $pd;
    $pagos[] = $p;
}

$tabs = [];
if ($factura)   $tabs['pdf']   = 'Factura PDF';
if ($gFiles)    $tabs['gasto'] = 'Soporte Gasto';
if ($pagos)     $tabs['pago']  = 'Soporte Pago';
if (empty($tabs)) {
    echo '<p class="text-center text-muted">No hay soportes disponibles.</p>';
    return;
}
?>
<!-- pestañas -->
<ul class="nav nav-tabs" id="soportesTab" role="tablist">
    <?php $i = 0;
    foreach ($tabs as $key => $label): ?>
        <li class="nav-item" role="presentation">
            <button
                class="nav-link <?= $i === 0 ? 'active' : '' ?>"
                data-bs-toggle="tab"
                data-bs-target="#tab-<?= $key ?>"
                type="button"
                role="tab"
                aria-selected="<?= $i === 0 ? 'true' : 'false' ?>">
                <?= $label ?>
            </button>
        </li>
    <?php $i++;
    endforeach; ?>
</ul>
<div class="tab-content border-top-0 p-3">
    <?php foreach ($tabs as $key => $label): ?>
        <div
            class="tab-pane fade <?= $key === array_key_first($tabs) ? 'show active' : '' ?>"
            id="tab-<?= $key ?>"
            role="tabpanel">
            <?php if ($key === 'pdf'): ?>
                <iframe src="<?= $factura ?>" style="width:100%; height:600px;" frameborder="0"></iframe>
            <?php elseif ($key === 'gasto'): ?>
                <div class="row g-2">
                    <?php foreach ($gFiles as $f): ?>
                        <div class="col-3">
                            <a href="/archivoDigital/soporteGastos/<?= $idG ?>/<?= $f ?>" target="_blank">
                                <img src="/archivoDigital/soporteGastos/<?= $idG ?>/<?= $f ?>" class="img-fluid border">
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php elseif ($key === 'pago'): ?>
                <table class="table table-sm mb-3">
                    <thead>
                        <tr>
                            <th>Comp.</th>
                            <th>Total</th>
                            <th>Banco</th>
                            <th>Obs.</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pagos as $p): ?>
                            <tr>
                                <td><?= htmlspecialchars($p['noComprobante']) ?></td>
                                <td class="text-end"><?= number_format($p['totalPago'], 0, ',', '.') ?></td>
                                <td><?= htmlspecialchars($p['banco']) ?></td>
                                <td><?= htmlspecialchars($p['observaciones']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php foreach ($pagos as $p): if ($p['files']): ?>
                        <h6>Pago #<?= $p['id'] ?></h6>
                        <div class="row g-2 mb-4">
                            <?php foreach ($p['files'] as $url): ?>
                                <div class="col-3">
                                    <a href="<?= $url ?>" target="_blank">
                                        <img src="<?= $url ?>" class="img-fluid border">
                                    </a>
                                </div>
                            <?php endforeach; ?>
                        </div>
                <?php endif;
                endforeach; ?>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
</div>