<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-file-earmark-text me-2"></i> Borderô de Pagamentos</h2>
        <p class="text-muted">Selecione as contas para gerar o borderô de pagamentos</p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/saidas') ?>" class="btn btn-secondary me-2">
            <i class="bi bi-arrow-left me-2"></i> Voltar
        </a>
        <button type="button" class="btn btn-primary" onclick="gerarBordero()">
            <i class="bi bi-file-earmark-pdf me-2"></i> Gerar Borderô
        </button>
    </div>
</div>

<!-- Filtros -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Buscar</label>
                <input type="text" class="form-control" name="search" placeholder="Descrição, fornecedor..."
                    value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Data Vencimento Início</label>
                <input type="date" class="form-control" name="data_inicio"
                    value="<?= htmlspecialchars($_GET['data_inicio'] ?? '') ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Data Vencimento Fim</label>
                <input type="date" class="form-control" name="data_fim"
                    value="<?= htmlspecialchars($_GET['data_fim'] ?? '') ?>">
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-secondary w-100">
                    <i class="bi bi-search"></i> Buscar
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Lista de Contas -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-ul me-2"></i> Contas Disponíveis para Borderô</span>
        <div>
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="selecionarTodas()">
                <i class="bi bi-check-all me-1"></i> Selecionar Todas
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="desmarcarTodas()">
                <i class="bi bi-x-circle me-1"></i> Desmarcar Todas
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($contas)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th width="50">
                                <input type="checkbox" id="select-all" onchange="toggleAll(this)">
                            </th>
                            <th>ID</th>
                            <th>Fornecedor</th>
                            <th>Descrição</th>
                            <th>Valor</th>
                            <th>Vencimento</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $totalSelecionado = 0;
                        foreach ($contas as $conta):
                            ?>
                            <tr>
                                <td>
                                    <input type="checkbox" class="conta-checkbox" value="<?= $conta['id'] ?>"
                                        data-valor="<?= $conta['amount'] ?>" onchange="calcularTotal()">
                                </td>
                                <td><?= $conta['id'] ?></td>
                                <td><?= htmlspecialchars($conta['supplier_name'] ?? 'Fornecedor não informado') ?></td>
                                <td><strong><?= htmlspecialchars($conta['description']) ?></strong></td>
                                <td>R$ <?= number_format($conta['amount'] ?? 0, 2, ',', '.') ?></td>
                                <td><?= date('d/m/Y', strtotime($conta['due_date'])) ?></td>
                                <td>
                                    <?php
                                    $statusBadges = [
                                        'pendente' => '<span class="badge bg-warning">Pendente</span>',
                                        'pago_parcial' => '<span class="badge bg-info">Pago Parcial</span>',
                                        'vencido' => '<span class="badge bg-danger">Vencido</span>'
                                    ];
                                    echo $statusBadges[$conta['status']] ?? '<span class="badge bg-secondary">-</span>';
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-info">
                            <td colspan="4" class="text-end"><strong>Total Selecionado:</strong></td>
                            <td><strong id="total-selecionado">R$ 0,00</strong></td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="bi bi-file-earmark-text" style="font-size: 4rem; color: var(--text-secondary);"></i>
                <p class="text-muted mt-3">Nenhuma conta disponível para borderô</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    function toggleAll(checkbox) {
        const checkboxes = document.querySelectorAll('.conta-checkbox');
        checkboxes.forEach(cb => cb.checked = checkbox.checked);
        calcularTotal();
    }

    function selecionarTodas() {
        document.querySelectorAll('.conta-checkbox').forEach(cb => cb.checked = true);
        document.getElementById('select-all').checked = true;
        calcularTotal();
    }

    function desmarcarTodas() {
        document.querySelectorAll('.conta-checkbox').forEach(cb => cb.checked = false);
        document.getElementById('select-all').checked = false;
        calcularTotal();
    }

    function calcularTotal() {
        let total = 0;
        document.querySelectorAll('.conta-checkbox:checked').forEach(checkbox => {
            total += parseFloat(checkbox.getAttribute('data-valor')) || 0;
        });
        document.getElementById('total-selecionado').textContent =
            'R$ ' + total.toFixed(2).replace('.', ',').replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    }

    function gerarBordero() {
        const selecionadas = Array.from(document.querySelectorAll('.conta-checkbox:checked'))
            .map(cb => cb.value);

        if (selecionadas.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Atenção',
                text: 'Selecione pelo menos uma conta para gerar o borderô'
            });
            return;
        }

        // Redirecionar para a página de impressão
        const ids = selecionadas.join(',');
        const url = appUrl('/saidas/bordero/print?ids=' + encodeURIComponent(ids));
        window.open(url, '_blank');
    }

    // Inicializar total
    calcularTotal();
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'saidas';
include ROOT_PATH . '/views/layouts/app.php';
?>