<!-- ============================================================ -->
<!-- REPORTES - Filtros y vista previa del reporte -->
<!-- ============================================================ -->

<!-- Filtros -->
<div class="glass-card rounded-2xl p-6 mb-6" style="position: relative; z-index: 50;">
    <h3 class="font-sora font-bold text-white text-lg mb-1">Reporte de Letras Semanal</h3>
    <p class="text-xs text-gray-500 mb-5">Filtre por rango de fechas de vencimiento y empresa. La <strong class="text-white">Fecha de Pago</strong> se calcula como Vencimiento + 8 días.</p>

    <form method="POST" action="<?= BASE_URL ?>?c=reportes&a=generar" class="flex flex-col sm:flex-row items-end gap-4">
        <div class="flex-1 w-full">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Fecha Vencimiento Desde *</label>
            <input type="date" name="fecha_desde" value="<?= htmlspecialchars($fechaDesde) ?>" required class="input-glass w-full">
        </div>
        <div class="flex-1 w-full">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Fecha Vencimiento Hasta *</label>
            <input type="date" name="fecha_hasta" value="<?= htmlspecialchars($fechaHasta) ?>" required class="input-glass w-full">
        </div>
        <div class="flex-1 w-full">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Empresa</label>
            <select name="empresa_id[]" multiple class="input-glass w-full tom-select-multi">
                <?php 
                $selectedIds = !empty($empresaId) ? array_map('intval', explode(',', $empresaId)) : [];
                foreach ($empresas as $emp): ?>
                <option value="<?= $emp['id'] ?>" <?= in_array((int)$emp['id'], $selectedIds) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($emp['razon_social']) ?> <?= !empty($emp['ruc']) ? ' - RUC: ' . htmlspecialchars($emp['ruc']) : '' ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn-primary px-6 py-2.5 rounded-xl text-sm font-semibold inline-flex items-center gap-2 whitespace-nowrap">
            <i class="fas fa-search"></i> Generar Reporte
        </button>
    </form>
</div>

<?php if ($reporte !== null): ?>

<!-- Export Buttons -->
<div class="flex items-center justify-between mb-4">
    <div>
        <p class="text-xs text-gray-500">
            Mostrando resultados del <span class="text-white font-medium"><?= date('d/m/Y', strtotime($fechaDesde)) ?></span>
            al <span class="text-white font-medium"><?= date('d/m/Y', strtotime($fechaHasta)) ?></span>
        </p>
    </div>
    <div class="flex gap-2">
        <button onclick="imprimirReporte()" class="px-4 py-2 rounded-xl text-xs font-semibold bg-red-500/10 text-red-400 hover:bg-red-500/20 border border-red-500/20 transition-colors inline-flex items-center gap-2">
            <i class="fas fa-file-pdf"></i> PDF
        </button>
        <a href="<?= BASE_URL ?>?c=reportes&a=exportarexcel&fecha_desde=<?= $fechaDesde ?>&fecha_hasta=<?= $fechaHasta ?>&empresa_id=<?= $empresaId ?>" 
           class="px-4 py-2 rounded-xl text-xs font-semibold bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20 border border-emerald-500/20 transition-colors inline-flex items-center gap-2">
            <i class="fas fa-file-excel"></i> Excel
        </a>
    </div>
</div>

<!-- Report Table (printable) -->
<div class="glass-card rounded-2xl overflow-hidden" id="reporte-contenido">
    
    <!-- Report Header (visible on print) -->
    <div class="p-6 border-b border-white/5 print-header">
        <div class="flex items-center justify-between">
            <div>
                <h2 class="font-sora font-bold text-white text-xl">JW DIESEL S.A.C.</h2>
                <p class="text-xs text-gray-400">JR. LIBERTAD 489 - CHIMBOTE</p>
                <p class="text-sm text-white font-semibold mt-2">REPORTE DE LETRAS SEMANAL</p>
                <p class="text-[10px] text-gray-500 italic">Ordenado por Fecha de Vencimiento</p>
            </div>
            <div class="text-right">
                <p class="text-xs text-gray-400">(Desde el <span class="text-white"><?= date('d/m/Y', strtotime($fechaDesde)) ?></span> hasta el <span class="text-white"><?= date('d/m/Y', strtotime($fechaHasta)) ?></span>)</p>
                <p class="text-[10px] text-gray-500 mt-1">Día que se imprimió el Reporte</p>
                <p class="text-xs text-white font-medium"><?= date('l d/m/Y, H:i:s') ?></p>
            </div>
        </div>
    </div>

    <?php if (empty($reporte)): ?>
    <div class="p-12 text-center">
        <div class="w-16 h-16 mx-auto mb-3 rounded-full bg-white/5 flex items-center justify-center">
            <i class="fas fa-search text-gray-600 text-2xl"></i>
        </div>
        <p class="text-gray-500">No se encontraron letras en el rango de fechas seleccionado</p>
    </div>
    <?php else: ?>

    <div class="overflow-x-auto">
        <table class="w-full text-xs" id="tabla-reporte">
            <thead>
                <tr class="bg-white/3 border-b border-white/10">
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">Id</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">N</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">G</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">#Documento</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">Fec E.</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">Fec I.</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">Fecha Vec</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">Fecha Pag</th>
                    <th class="px-2 py-2.5 text-right text-[10px] font-bold text-gray-300 uppercase">Total</th>
                    <th class="px-2 py-2.5 text-center text-[10px] font-bold text-gray-300 uppercase">Obs.</th>
                    <th class="px-2 py-2.5 text-center text-[10px] font-bold text-gray-300 uppercase">D</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase">Banco</th>
                    <th class="px-2 py-2.5 text-center text-[10px] font-bold text-gray-300 uppercase">E</th>
                    <th class="px-2 py-2.5 text-left text-[10px] font-bold text-gray-300 uppercase"># Unico Ref</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($reporte as $empresaNombre => $grupo): ?>
                <!-- Empresa Header -->
                <tr class="bg-primary-900/20 border-b border-white/5">
                    <td colspan="14" class="px-3 py-2.5">
                        <span class="font-sora font-bold text-white text-sm uppercase"><?= htmlspecialchars($empresaNombre) ?></span>
                    </td>
                </tr>

                <?php foreach ($grupo['letras'] as $letra): 
                    $diasRest = (int)$letra['dias_restantes'];
                    $rowBg = '';
                    if ($diasRest < 0) $rowBg = 'bg-red-500/3';
                    elseif ($diasRest <= 3) $rowBg = 'bg-amber-500/3';
                ?>
                <tr class="border-b border-white/3 hover:bg-white/3 transition-colors <?= $rowBg ?>">
                    <td class="px-2 py-2 text-gray-400 font-mono"><?= $letra['id'] ?></td>
                    <td class="px-2 py-2 text-gray-400"><?= $letra['n'] ?></td>
                    <td class="px-2 py-2 text-gray-400"><?= $letra['g'] ?></td>
                    <td class="px-2 py-2 text-white font-mono"><?= htmlspecialchars($letra['documento']) ?></td>
                    <td class="px-2 py-2 text-gray-400"><?= $letra['fec_emision'] ?></td>
                    <td class="px-2 py-2 text-gray-400"><?= $letra['fec_ingreso'] ?></td>
                    <td class="px-2 py-2 text-white"><?= $letra['fecha_vec_formato'] ?></td>
                    <td class="px-2 py-2 text-white font-bold text-sm"><?= $letra['fecha_pag_formato'] ?></td>
                    <td class="px-2 py-2 text-right text-white font-medium">US$ <?= number_format((float)$letra['total'], 2) ?></td>
                    <td class="px-2 py-2 text-center">
                        <?php if (!empty($letra['obs'])): ?>
                            <i class="fas fa-check text-primary-400 text-[10px]"></i>
                        <?php endif; ?>
                    </td>
                    <td class="px-2 py-2 text-center">
                        <?php if ($letra['estado'] === 'pendiente'): ?>
                            <span class="<?= $diasRest < 0 ? 'text-red-400 font-bold' : ($diasRest <= 3 ? 'text-amber-400 font-bold' : 'text-gray-400') ?>">
                                <?= $diasRest ?>
                            </span>
                        <?php else: ?>
                            <span class="text-gray-600">-</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-2 py-2 text-gray-400 truncate max-w-[80px]"><?= htmlspecialchars($letra['banco'] ?? '') ?></td>
                    <td class="px-2 py-2 text-center">
                        <?php 
                            $estadoColor = match($letra['estado_letra']) {
                                'R'  => 'text-blue-400',
                                'A'  => 'text-emerald-400',
                                'P'  => 'text-amber-400',
                                'V'  => 'text-red-400',
                                'PR' => 'text-gray-400',
                                default => 'text-gray-400',
                            };
                        ?>
                        <span class="<?= $estadoColor ?> font-bold">
                            <?= $letra['estado_letra'] ?>
                        </span>
                    </td>
                    <td class="px-2 py-2 text-gray-400 font-mono truncate max-w-[80px]"><?= htmlspecialchars($letra['referencia_unica'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>

                <!-- Group Total -->
                <tr class="border-b border-white/10 bg-white/2">
                    <td colspan="7"></td>
                    <td class="px-2 py-2 text-right text-xs text-gray-400 font-semibold">Total de Grupo -----></td>
                    <td class="px-2 py-2 text-right text-white font-bold">US$ <?= number_format($grupo['total_dolares'], 2) ?></td>
                    <td colspan="5"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Report Footer -->
    <div class="p-6 border-t border-white/5">
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="glass-card-inner rounded-xl p-3">
                <p class="text-[10px] text-gray-500 uppercase font-medium">Total Letras Dólares</p>
                <p class="font-sora font-bold text-white text-lg"><?= number_format((float)$totales['total_dolares'], 2) ?></p>
            </div>
            <div class="glass-card-inner rounded-xl p-3">
                <p class="text-[10px] text-gray-500 uppercase font-medium">Total Letras Soles</p>
                <p class="font-sora font-bold text-white text-lg"><?= number_format((float)$totales['total_soles'], 2) ?></p>
            </div>
            <div class="glass-card-inner rounded-xl p-3">
                <p class="text-[10px] text-gray-500 uppercase font-medium">Nº Letras a pagar</p>
                <p class="font-sora font-bold text-amber-400 text-lg"><?= $totales['letras_pendientes'] ?></p>
            </div>
            <div class="glass-card-inner rounded-xl p-3">
                <p class="text-[10px] text-gray-500 uppercase font-medium">Total Letras</p>
                <p class="font-sora font-bold text-white text-lg"><?= $totales['total_letras'] ?></p>
            </div>
        </div>

        <!-- Legend -->
        <div class="mt-4 text-[10px] text-gray-500 grid grid-cols-2 gap-1">
            <p><strong class="text-gray-400">La Letra G:</strong> Hace Referencia al Grupo de Letras ingresado en el día</p>
            <p><strong class="text-gray-400">La Letra E:</strong> Hace Referencia al Estado en el que se encuentra la Letra</p>
            <p><strong class="text-gray-400">Donde P:</strong> Pendiente | <strong class="text-gray-400">Donde A:</strong> Aceptada (Pagada) | <strong class="text-gray-400">Donde R:</strong> Renovada | <strong class="text-gray-400">Donde V:</strong> Vencida</p>
            <p><strong class="text-gray-400">Fecha Pag:</strong> Fecha de vencimiento + 8 días (fecha límite para pagar al banco)</p>
        </div>
    </div>

    <?php endif; ?>
</div>

<?php endif; ?>
