<!-- ============================================================ -->
<!-- LETRAS - Checklist Pendientes -->
<!-- ============================================================ -->

<!-- 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">Checklist de Letras Pendientes</h3>
        <p class="text-xs text-gray-500 mt-1">Selecciona las letras para marcarlas como pagadas masivamente</p>
    </div>
    <div class="flex items-center gap-3">
        <a href="<?= BASE_URL ?>?c=dashboard" class="px-5 py-2.5 rounded-xl text-sm font-medium text-gray-400 hover:text-white transition-colors border border-white/10 hover:border-white/20">
            Volver al Dashboard
        </a>
        <button onclick="procesarPagoMasivo()" class="btn-primary px-5 py-2.5 rounded-xl text-sm font-semibold inline-flex items-center gap-2">
            <i class="fas fa-check-double"></i>
            Marcar Pagadas (<span id="count-selected">0</span>)
        </button>
    </div>
</div>

<!-- Filters -->
<div class="glass-card rounded-2xl p-5 mb-6 relative z-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">
        <input type="hidden" name="a" value="checklist">
        
        <div class="flex-1 w-full sm:w-1/3">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Razón Social (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/4">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Nº Letra</label>
            <input type="text" name="numero_letra" value="<?= htmlspecialchars($numeroLetra ?? '') ?>" class="input-glass w-full" placeholder="Buscar Nº Letra">
        </div>

        <div class="w-full sm:w-1/4">
            <label class="block text-xs text-gray-400 mb-1.5 font-medium">Fecha Emisión de Factura</label>
            <input type="date" name="fecha_emision_factura" value="<?= htmlspecialchars($fechaEmisionFactura ?? '') ?>" class="input-glass w-full">
        </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&a=checklist" 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">
    <form id="formChecklist">
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-white/5">
                        <th class="px-4 py-3.5 text-center w-12">
                            <div class="flex items-center justify-center">
                                <input type="checkbox" id="checkAll" class="w-4 h-4 rounded bg-white/5 border-white/10 text-primary-500 focus:ring-primary-500/50 cursor-pointer">
                            </div>
                        </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">Empresa</th>
                        <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">F. Emi Factura</th>
                        <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider">F. Vencimiento</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 Restantes</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="8" 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-check text-emerald-500 text-2xl"></i>
                            </div>
                            <p class="text-gray-400 font-medium text-base mb-1">No hay letras pendientes</p>
                            <p class="text-gray-500 text-xs">Ajuste los filtros o celebre que no hay deudas</p>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($letras as $letra):
                        $diasPagar = (int)$letra['dias_para_pagar'];
                        $urgenciaClass = '';
                        if ($diasPagar < 0) $urgenciaClass = 'bg-red-500/10 border-l-2 border-red-500';
                        elseif ($diasPagar <= 3) $urgenciaClass = 'bg-amber-500/10 border-l-2 border-amber-500';
                    ?>
                    <tr class="hover:bg-white/5 transition-colors <?= $urgenciaClass ?>">
                        <td class="px-4 py-3 text-center">
                            <div class="flex items-center justify-center">
                                <input type="checkbox" name="letras_ids[]" value="<?= $letra['id'] ?>" class="letra-check w-4 h-4 rounded bg-white/5 border-white/10 text-primary-500 focus:ring-primary-500/50 cursor-pointer">
                            </div>
                        </td>
                        <td class="px-4 py-3 text-white font-mono text-xs font-medium"><?= htmlspecialchars($letra['numero_letra']) ?></td>
                        <td class="px-4 py-3">
                            <p class="text-white font-medium text-xs truncate max-w-[200px]"><?= htmlspecialchars($letra['razon_social']) ?></p>
                        </td>
                        <td class="px-4 py-3 text-gray-400 text-xs"><?= empty($letra['fecha_emision_factura']) ? '-' : date('d/m/Y', strtotime($letra['fecha_emision_factura'])) ?></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-right text-white font-bold text-xs">
                            <?= $letra['moneda'] === 'USD' ? '$' : 'S/' ?><?= number_format((float)$letra['importe'], 2) ?>
                        </td>
                        <td class="px-4 py-3 text-center">
                            <?php if ($diasPagar < 0): ?>
                                <span class="text-xs font-bold text-red-400">Vencida (<?= abs($diasPagar) ?>d)</span>
                            <?php elseif ($diasPagar === 0): ?>
                                <span class="text-xs font-bold text-amber-400">0d</span>
                            <?php elseif ($diasPagar <= 3): ?>
                                <span class="text-xs font-bold text-amber-400"><?= $diasPagar ?>d</span>
                            <?php else: ?>
                                <span class="text-xs text-gray-400"><?= $diasPagar ?>d</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 text-center">
                            <div class="flex items-center justify-center gap-1">
                                <a href="<?= BASE_URL ?>?c=letras&a=editar&id=<?= $letra['id'] ?>" 
                                   class="w-7 h-7 rounded-lg bg-primary-500/10 text-primary-400 flex items-center justify-center hover:bg-primary-500 hover:text-white transition-colors"
                                   title="Editar Letra">
                                    <i class="fas fa-edit text-xs"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const checkAll = document.getElementById('checkAll');
    const checkboxes = document.querySelectorAll('.letra-check');
    const countSelected = document.getElementById('count-selected');

    function updateCount() {
        const selected = document.querySelectorAll('.letra-check:checked').length;
        countSelected.textContent = selected;
    }

    if(checkAll) {
        checkAll.addEventListener('change', function() {
            checkboxes.forEach(cb => {
                cb.checked = this.checked;
            });
            updateCount();
        });
    }

    checkboxes.forEach(cb => {
        cb.addEventListener('change', function() {
            if (!this.checked) {
                checkAll.checked = false;
            } else if (document.querySelectorAll('.letra-check:checked').length === checkboxes.length) {
                checkAll.checked = true;
            }
            updateCount();
        });
    });
});

function procesarPagoMasivo() {
    const selected = document.querySelectorAll('.letra-check:checked');
    if (selected.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'Sin selección',
            text: 'Por favor, selecciona al menos una letra para marcar como pagada.',
            background: '#1e2a3a',
            color: '#fff',
        });
        return;
    }

    Swal.fire({
        title: '¿Confirmar Pago?',
        text: `Se marcarán ${selected.length} letras como pagadas. Esta acción no se puede deshacer masivamente.`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Sí, marcar pagadas',
        cancelButtonText: 'Cancelar',
        background: '#1e2a3a',
        color: '#fff',
        confirmButtonColor: '#10b981',
        cancelButtonColor: '#475569'
    }).then((result) => {
        if (result.isConfirmed) {
            const form = document.getElementById('formChecklist');
            const formData = new FormData(form);
            
            fetch('<?= BASE_URL ?>?c=letras&a=marcarPagadasMasivo', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.error) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.mensaje,
                        background: '#1e2a3a',
                        color: '#fff',
                    });
                } else {
                    Swal.fire({
                        icon: 'success',
                        title: '¡Éxito!',
                        text: data.mensaje,
                        background: '#1e2a3a',
                        color: '#fff',
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.reload();
                    });
                }
            })
            .catch(error => {
                console.error(error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error de conexión',
                    text: 'No se pudo completar la operación.',
                    background: '#1e2a3a',
                    color: '#fff',
                });
            });
        }
    });
}
</script>
