<!-- ============================================================ -->
<!-- LETRAS - Listado con filtros -->
<!-- ============================================================ -->

<!-- Header Actions -->
<div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
    <div>
        <h3 class="font-sora font-bold text-white text-lg">Listado de Letras</h3>
        <p class="text-xs text-gray-500 mt-1">Gestiona todas las letras registradas</p>
    </div>
    <a href="<?= BASE_URL ?>?c=letras&a=crear" class="btn-primary px-5 py-2.5 rounded-xl text-sm font-semibold inline-flex items-center gap-2">
        <i class="fas fa-plus"></i>
        Registrar Letras
    </a>
</div>

<!-- Filters -->
<div class="glass-card rounded-2xl p-5 mb-6" style="position: relative; z-index: 50;">
    <form method="GET" action="<?= BASE_URL ?>" class="flex flex-col sm:flex-row items-end gap-4">
        <input type="hidden" name="c" value="letras">
        
        <div class="flex-1 w-full sm:w-1/4">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Empresa</label>
            <select name="empresa_id" class="input-glass w-full tom-select">
                <option value="0">-- Buscar por RUC o Razón Social --</option>
                <?php foreach ($empresas as $emp): ?>
                <option value="<?= $emp['id'] ?>" <?= $empresaId == $emp['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($emp['razon_social']) ?> <?= !empty($emp['ruc']) ? ' - RUC: ' . htmlspecialchars($emp['ruc']) : '' ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="w-full sm:w-1/6">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">F. Emisión Factura</label>
            <input type="date" name="fecha_emision_factura" value="<?= htmlspecialchars($fechaEmisionFactura ?? '') ?>" class="input-glass w-full">
        </div>

        <div class="w-full sm:w-1/6">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Desde</label>
            <input type="date" name="fecha_desde" value="<?= htmlspecialchars($fechaDesde ?? '') ?>" class="input-glass w-full">
        </div>
        <div class="w-full sm:w-1/6">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Hasta</label>
            <input type="date" name="fecha_hasta" value="<?= htmlspecialchars($fechaHasta ?? '') ?>" 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">Estado</label>
            <select name="estado" class="input-glass w-full">
                <option value="">-- Todos --</option>
                <option value="pendiente" <?= $filtroEstado === 'pendiente' ? 'selected' : '' ?>>Pendiente</option>
                <option value="pagada" <?= $filtroEstado === 'pagada' ? 'selected' : '' ?>>Pagada</option>
                <option value="vencida" <?= $filtroEstado === 'vencida' ? 'selected' : '' ?>>Vencida</option>
                <option value="renovada" <?= $filtroEstado === 'renovada' ? 'selected' : '' ?>>Renovada</option>
                <option value="protestada" <?= $filtroEstado === 'protestada' ? 'selected' : '' ?>>Protestada</option>
            </select>
        </div>

        <button type="submit" class="btn-primary px-5 py-2.5 rounded-xl text-sm font-semibold inline-flex items-center gap-2 whitespace-nowrap">
            <i class="fas fa-search"></i> Filtrar
        </button>
        <a href="<?= BASE_URL ?>?c=letras" class="px-5 py-2.5 rounded-xl text-sm font-medium text-gray-400 hover:text-white border border-white/10 hover:border-white/20 transition-colors inline-flex items-center gap-2 whitespace-nowrap">
            <i class="fas fa-times"></i> Limpiar
        </a>
    </form>
</div>

<!-- Table -->
<div class="glass-card rounded-2xl overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full min-w-max text-sm" id="tabla-letras">
            <thead>
                <tr class="border-b border-white/5">
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">ID</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">Empresa</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">Nº Letra</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">Tipo</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">Moneda</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">Emisión</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">Vencimiento</th>
                    <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">F. Pago (+8d)</th>
                    <th class="px-4 py-3.5 text-right text-xs font-semibold text-gray-400 uppercase tracking-wider">Importe</th>
                    <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-400 uppercase tracking-wider">Días</th>
                    <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-400 uppercase tracking-wider">Estado</th>
                    <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-400 uppercase tracking-wider">Acciones</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-white/5">
                <?php if (empty($letras)): ?>
                <tr>
                    <td colspan="12" class="px-4 py-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-400 font-medium text-base mb-1">Utilice los filtros para buscar letras</p>
                        <p class="text-gray-500 text-xs">Seleccione una empresa o un rango de fechas para visualizar los resultados</p>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($letras as $letra):
                    $diasVencer = (int)$letra['dias_para_vencer'];
                    $diasPagar  = (int)$letra['dias_para_pagar'];
                    
                    // Color de fila según urgencia
                    if ($letra['estado'] === 'pagada') {
                        $rowClass = '';
                    } elseif ($diasPagar < 0) {
                        $rowClass = 'bg-red-500/5';
                    } elseif ($diasVencer < 0) {
                        $rowClass = 'bg-red-500/3';
                    } elseif ($diasVencer <= 3) {
                        $rowClass = 'bg-amber-500/3';
                    } else {
                        $rowClass = '';
                    }
                    
                    // Badge de estado
                    $estadoBadge = match($letra['estado']) {
                        'pendiente'  => 'bg-amber-500/15 text-amber-400',
                        'pagada'     => 'bg-emerald-500/15 text-emerald-400',
                        'vencida'    => 'bg-red-500/15 text-red-400',
                        'renovada'   => 'bg-primary-500/15 text-primary-400',
                        'protestada' => 'bg-gray-500/15 text-gray-400',
                        default      => 'bg-gray-500/15 text-gray-400',
                    };
                ?>
                <tr class="hover:bg-white/3 transition-colors <?= $rowClass ?>">
                    <td class="px-4 py-3 text-gray-400 font-mono text-xs"><?= $letra['id'] ?></td>
                    <td class="px-4 py-3">
                        <p class="text-white font-medium text-xs truncate max-w-[150px]"><?= htmlspecialchars($letra['razon_social']) ?></p>
                        <p class="text-gray-600 text-[10px]">Doc: <?= htmlspecialchars($letra['documento_sunat'] ?? '-') ?></p>
                    </td>
                    <td class="px-4 py-3 text-white font-mono text-xs"><?= htmlspecialchars($letra['numero_letra']) ?></td>
                    <td class="px-4 py-3">
                        <?php if ($letra['tipo_letra'] === 'REN'): ?>
                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-500/15 text-emerald-400 border border-emerald-500/20">
                                <i class="fas fa-sync-alt text-[8px]"></i> REN-<?= $letra['renovacion'] ?>
                            </span>
                        <?php elseif ($letra['estado'] === 'renovada'): ?>
                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-violet-500/15 text-violet-400 border border-violet-500/20">
                                <i class="fas fa-history text-[8px]"></i> Renovada
                            </span>
                        <?php else: ?>
                            <span class="text-gray-400 text-xs"><?= $letra['tipo_letra'] ?></span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3 text-gray-400 text-xs"><?= $letra['moneda'] ?></td>
                    <td class="px-4 py-3 text-gray-400 text-xs"><?= date('d/m/Y', strtotime($letra['fecha_emision'])) ?></td>
                    <td class="px-4 py-3 text-white text-xs font-medium"><?= date('d/m/Y', strtotime($letra['fecha_vencimiento'])) ?></td>
                    <td class="px-4 py-3 text-white text-xs font-bold"><?= date('d/m/Y', strtotime($letra['fecha_pago'])) ?></td>
                    <td class="px-4 py-3 text-right text-white font-semibold text-xs">
                        <?= $letra['moneda'] === 'USD' ? '$' : 'S/' ?><?= number_format((float)$letra['importe'], 2) ?>
                    </td>
                    <td class="px-4 py-3 text-center">
                        <?php if ($letra['estado'] === 'pendiente'): ?>
                            <?php if ($diasPagar < 0): ?>
                                <span class="text-xs font-bold text-red-400 animate-pulse"><?= $diasPagar ?></span>
                            <?php elseif ($diasVencer < 0): ?>
                                <span class="text-xs font-bold text-red-400"><?= $diasVencer ?></span>
                            <?php elseif ($diasVencer <= 3): ?>
                                <span class="text-xs font-bold text-amber-400"><?= $diasVencer ?></span>
                            <?php else: ?>
                                <span class="text-xs text-gray-400"><?= $diasVencer ?></span>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="text-xs text-gray-600">-</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3 text-center">
                        <select onchange="cambiarEstado(<?= $letra['id'] ?>, this.value)" 
                                class="text-[10px] font-semibold px-2 py-1 rounded-full border-0 cursor-pointer <?= $estadoBadge ?> bg-opacity-100 appearance-none text-center">
                            <option value="pendiente" <?= $letra['estado'] === 'pendiente' ? 'selected' : '' ?>>Pendiente</option>
                            <option value="pagada" <?= $letra['estado'] === 'pagada' ? 'selected' : '' ?>>Pagada</option>
                            <option value="vencida" <?= $letra['estado'] === 'vencida' ? 'selected' : '' ?>>Vencida</option>
                            <option value="renovada" <?= $letra['estado'] === 'renovada' ? 'selected' : '' ?>>Renovada</option>
                            <option value="protestada" <?= $letra['estado'] === 'protestada' ? 'selected' : '' ?>>Protestada</option>
                        </select>
                    </td>
                    <td class="px-4 py-3 text-center">
                        <div class="flex items-center justify-center gap-1">
                            <?php if (in_array($letra['estado'], ['pendiente', 'vencida'])): ?>
                            <a href="<?= BASE_URL ?>?c=letras&a=renovar&id=<?= $letra['id'] ?>" 
                               class="p-1.5 rounded-lg hover:bg-emerald-500/10 text-gray-400 hover:text-emerald-400 transition-colors" title="Renovar">
                                <i class="fas fa-sync-alt text-xs"></i>
                            </a>
                            <?php endif; ?>
                            <a href="<?= BASE_URL ?>?c=letras&a=editar&id=<?= $letra['id'] ?>" 
                               class="p-1.5 rounded-lg hover:bg-primary-500/10 text-gray-400 hover:text-primary-400 transition-colors" title="Editar">
                                <i class="fas fa-edit text-xs"></i>
                            </a>
                            <button onclick="confirmarEliminar(<?= $letra['id'] ?>, '<?= htmlspecialchars($letra['numero_letra']) ?>')" 
                                    class="p-1.5 rounded-lg hover:bg-red-500/10 text-gray-400 hover:text-red-400 transition-colors" title="Eliminar">
                                <i class="fas fa-trash text-xs"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if (!empty($letras)): ?>
    <div class="px-4 py-3 border-t border-white/5 flex items-center justify-between">
        <p class="text-xs text-gray-500"><?= count($letras) ?> letra(s) encontrada(s)</p>
    </div>
    <?php endif; ?>
</div>

<!-- Hidden form for delete -->
<form id="form-eliminar" method="POST" action="<?= BASE_URL ?>?c=letras&a=eliminar" class="hidden">
    <input type="hidden" name="id" id="delete-id">
</form>

<!-- Hidden form for renewal -->
<form id="form-renovar" method="POST" action="<?= BASE_URL ?>?c=letras&a=guardarrenovacion" class="hidden">
    <input type="hidden" name="id" id="renovar-id">
    <input type="hidden" name="porcentaje_abono" id="renovar-porcentaje">
    <input type="hidden" name="nuevo_plazo" id="renovar-plazo">
</form>
