<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-arrow-up-circle me-2"></i> Contas a Pagar</h2>
        <p class="text-muted">Gerencie suas contas a pagar</p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/saidas/bordero') ?>" class="btn btn-outline-primary me-2">
            <i class="bi bi-file-earmark-text me-2"></i>
        </a>
        <a href="<?= url('/saidas/provisionamento') ?>" class="btn btn-outline-primary me-2">
            <i class="bi bi-calendar-check me-2"></i>
        </a>
        <a href="<?= url('/saidas/folha-pagamento') ?>" class="btn btn-outline-primary">
            <i class="bi bi-cash-stack me-2"></i>
        </a>
        <a href="<?= url('/saidas/criar') ?>" class="btn btn-primary me-2">
            <i class="bi bi-plus-circle me-2"></i> Nova Conta
        </a>
    </div>
</div>

<!-- Filtros -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-6">
                <input type="text" class="form-control" name="fornecedor"
                    placeholder="Buscar por descrição, fornecedor..."
                    value="<?= htmlspecialchars($filtros['fornecedor'] ?? '') ?>">
            </div>
            <div class="col-md-3">
                <select class="form-select" name="status">
                    <option value="">Todos os Status</option>
                    <option value="pendente" <?= ($filtros['status'] ?? '') === 'pendente' ? 'selected' : '' ?>>Pendente
                    </option>
                    <option value="pago_parcial" <?= ($filtros['status'] ?? '') === 'pago_parcial' ? 'selected' : '' ?>>
                        Pago Parcial</option>
                    <option value="pago" <?= ($filtros['status'] ?? '') === 'pago' ? 'selected' : '' ?>>Pago</option>
                    <option value="vencido" <?= ($filtros['status'] ?? '') === 'vencido' ? 'selected' : '' ?>>Vencido
                    </option>
                    <option value="cancelado" <?= ($filtros['status'] ?? '') === 'cancelado' ? 'selected' : '' ?>>Cancelado
                    </option>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-secondary w-100">
                    <i class="bi bi-search"></i> Buscar
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Listagem -->
<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> Lista de Contas a Pagar</span>
        <span class="badge bg-primary"><?= count($contas ?? []) ?> registro(s)</span>
    </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="60">ID</th>
                            <th>Descrição</th>
                            <th>Fornecedor</th>
                            <th>Valor</th>
                            <th>Pago</th>
                            <th>Restante</th>
                            <th>Vencimento</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($contas as $conta): ?>
                            <tr class="conta-row" data-id="<?= $conta['id'] ?>" style="cursor: pointer;">
                                <td><?= $conta['id'] ?></td>
                                <td><strong><?= htmlspecialchars($conta['description']) ?></strong></td>
                                <td><?= htmlspecialchars($conta['supplier_name'] ?? 'Fornecedor não informado') ?></td>
                                <td>R$ <?= formatCurrency($conta['amount'] ?? 0) ?></td>
                                <td>R$ <?= formatCurrency($conta['amount_paid'] ?? $conta['amount_received'] ?? 0) ?></td>
                                <td>R$ <?= formatCurrency($conta['amount_remaining'] ?? 0) ?></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>',
                                        'pago' => '<span class="badge bg-success">Pago</span>',
                                        'vencido' => '<span class="badge bg-danger">Vencido</span>',
                                        'cancelado' => '<span class="badge bg-secondary">Cancelado</span>'
                                    ];
                                    echo $statusBadges[$conta['status']] ?? '<span class="badge bg-secondary">-</span>';
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="bi bi-arrow-up-circle" style="font-size: 4rem; color: var(--text-secondary);"></i>
                <p class="text-muted mt-3">Nenhuma conta a pagar encontrada</p>
                <a href="<?= url('/saidas/criar') ?>" class="btn btn-primary mt-2">
                    <i class="bi bi-plus-circle me-2"></i> Cadastrar Primeira Conta
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
    .conta-row {
        transition: all 0.2s ease;
    }

    .conta-row:hover {
        background-color: rgba(220, 53, 69, 0.05) !important;
        transform: scale(1.01);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    /* SweetAlert2 - Botões QUADRADOS Profissionais */
    .swal-html-container {
        margin: 0 !important;
        padding: 0 !important;
        overflow: hidden !important;
    }

    .acoes-grid {
        display: grid;
        grid-template-columns: repeat(4, 110px);
        gap: 8px;
        padding: 0;
        margin: 0;
        justify-content: center;
    }

    .btn-acao {
        width: 110px;
        height: 110px;
        border: 2px solid #e0e0e0;
        border-radius: 0;
        background-color: #ffffff;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s ease;
        font-weight: 600;
        font-size: 10px;
        color: #2c3e50;
    }

    .btn-acao:hover {
        border-color: #2c3e50;
        background-color: #2c3e50;
        color: #ffffff;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }

    .btn-acao i {
        font-size: 28px;
        margin-bottom: 6px;
    }

    .btn-acao span {
        display: block;
        margin-top: 3px;
        font-size: 9px;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    .btn-acao-delete {
        border-color: #dc3545;
        color: #dc3545;
    }

    .btn-acao-delete:hover {
        background-color: #dc3545;
        color: #ffffff;
        border-color: #dc3545;
    }

    .swal2-popup.swal-acoes-conta {
        border-radius: 0 !important;
        padding: 20px 15px !important;
        width: 500px !important;
        max-width: 500px !important;
    }

    .swal2-title {
        font-size: 16px !important;
        font-weight: 600 !important;
        margin-bottom: 20px !important;
        color: #2c3e50 !important;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .swal2-close {
        border-radius: 0 !important;
        font-size: 28px !important;
        color: #999 !important;
    }

    .swal2-close:hover {
        color: #000 !important;
    }
</style>

<script>
    // Evento de click na linha da tabela
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.conta-row').forEach(row => {
            row.addEventListener('click', function (e) {
                // Prevenir se clicar em um link ou botão dentro da linha
                if (e.target.closest('a, button')) return;

                const contaId = this.dataset.id;
                mostrarAcoesConta(contaId);
            });
        });
    });

    function mostrarAcoesConta(id) {
        Swal.fire({
            title: 'Ações',
            html: `
            <div class="acoes-grid">
                <button type="button" class="btn-acao" onclick="editarConta(${id})" title="Editar Conta">
                    <i class="bi bi-pencil"></i>
                    <span>Editar</span>
                </button>
                <button type="button" class="btn-acao" onclick="visualizarConta(${id})" title="Visualizar Detalhes">
                    <i class="bi bi-eye"></i>
                    <span>Ver</span>
                </button>
                <button type="button" class="btn-acao" onclick="pagarConta(${id})" title="Marcar como Pago">
                    <i class="bi bi-check-circle"></i>
                    <span>Pagar</span>
                </button>
                <button type="button" class="btn-acao" onclick="gerenciarAnexos(${id})" title="Gerenciar Anexos">
                    <i class="bi bi-paperclip"></i>
                    <span>Anexos</span>
                </button>
                <button type="button" class="btn-acao btn-acao-delete" onclick="deletarConta(${id})" title="Excluir Conta">
                    <i class="bi bi-trash"></i>
                    <span>Excluir</span>
                </button>
            </div>
        `,
            showConfirmButton: false,
            showCloseButton: true,
            width: '500px',
            padding: '20px',
            customClass: {
                popup: 'swal-acoes-conta',
                htmlContainer: 'swal-html-container'
            }
        });
    }

    function editarConta(id) {
        Swal.close();
        window.location.href = appUrl('/saidas/editar?id=' + id);
    }

    function visualizarConta(id) {
        Swal.close();
        window.location.href = appUrl('/saidas/visualizar?id=' + id);
    }

    function gerenciarAnexos(id) {
        Swal.close();

        // Carregar anexos primeiro
        $.ajax({
            url: appUrl('/saidas/anexos/listar'),
            type: 'GET',
            data: { conta_id: id },
            success: function (response) {
                const anexos = response.success ? (response.data?.anexos || []) : [];
                exibirModalAnexos(id, anexos);
            },
            error: function () {
                exibirModalAnexos(id, []);
            }
        });
    }

    function exibirModalAnexos(contaId, anexos) {
        let listaHtml = '';
        if (anexos.length === 0) {
            listaHtml = '<div class="text-center text-muted py-3"><i class="bi bi-inbox"></i> Nenhum anexo cadastrado</div>';
        } else {
            listaHtml = '<div class="table-responsive" style="max-height: 300px; overflow-y: auto;"><table class="table table-sm table-hover">';
            listaHtml += '<thead><tr><th>Arquivo</th><th>Tamanho</th><th width="100">Ações</th></tr></thead><tbody>';
            anexos.forEach(function (anexo) {
                const tamanho = formatarTamanhoAnexo(anexo.tamanho);
                const icone = obterIconeArquivoAnexo(anexo.nome_original);
                listaHtml += '<tr>';
                listaHtml += '<td><i class="bi ' + icone + ' me-2"></i>' + anexo.nome_original + '</td>';
                listaHtml += '<td>' + tamanho + '</td>';
                listaHtml += '<td>';
                listaHtml += '<a href="' + appUrl('/saidas/anexos/download?id=' + anexo.id) + '" class="btn btn-sm btn-outline-primary me-1" title="Download"><i class="bi bi-download"></i></a>';
                listaHtml += '<button onclick="deletarAnexoModal(' + anexo.id + ', ' + contaId + ')" class="btn btn-sm btn-outline-danger" title="Excluir"><i class="bi bi-trash"></i></button>';
                listaHtml += '</td>';
                listaHtml += '</tr>';
            });
            listaHtml += '</tbody></table></div>';
        }

        Swal.fire({
            title: 'Gerenciar Anexos',
            html: `
            <div class="text-start">
                <form id="formUploadAnexoModal" enctype="multipart/form-data" class="mb-3">
                    <input type="hidden" name="conta_id" value="${contaId}">
                    <div class="mb-2">
                        <label class="form-label small">Selecionar Arquivo</label>
                        <input type="file" class="form-control form-control-sm" name="arquivo"
                            accept=".jpg,.jpeg,.png,.pdf" required>
                        <small class="text-muted">JPG, JPEG, PNG ou PDF (máx. 10MB)</small>
                    </div>
                    <div class="mb-2">
                        <label class="form-label small">Descrição (opcional)</label>
                        <input type="text" class="form-control form-control-sm" name="descricao"
                            placeholder="Ex: Nota fiscal, comprovante...">
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm w-100">
                        <i class="bi bi-upload me-1"></i> Enviar Anexo
                    </button>
                </form>
                <hr>
                <h6 class="small">Anexos Cadastrados</h6>
                <div id="listaAnexosModal">${listaHtml}</div>
            </div>
        `,
            width: 600,
            showConfirmButton: false,
            showCloseButton: true,
            didOpen: () => {
                $('#formUploadAnexoModal').on('submit', function (e) {
                    e.preventDefault();
                    const formData = new FormData(this);
                    $.ajax({
                        url: appUrl('/saidas/anexos/upload'),
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Sucesso!',
                                    text: response.message,
                                    timer: 1500,
                                    showConfirmButton: false
                                });
                                gerenciarAnexos(contaId); // Recarregar
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Erro',
                                    text: response.message
                                });
                            }
                        },
                        error: function () {
                            Swal.fire({
                                icon: 'error',
                                title: 'Erro',
                                text: 'Erro ao fazer upload do anexo'
                            });
                        }
                    });
                });
            }
        });
    }

    function deletarAnexoModal(anexoId, contaId) {
        Swal.fire({
            title: 'Confirmar Exclusão',
            text: 'Tem certeza que deseja excluir este anexo?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sim, excluir',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: appUrl('/saidas/anexos/deletar'),
                    type: 'POST',
                    data: { anexo_id: anexoId },
                    success: function (response) {
                        if (response.success) {
                            gerenciarAnexos(contaId); // Recarregar
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Erro',
                                text: response.message
                            });
                        }
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: 'Erro',
                            text: 'Erro ao excluir anexo'
                        });
                    }
                });
            }
        });
    }

    function formatarTamanhoAnexo(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    }

    function obterIconeArquivoAnexo(nomeArquivo) {
        const extensao = nomeArquivo.split('.').pop().toLowerCase();
        const icones = {
            'pdf': 'bi-file-pdf',
            'jpg': 'bi-file-image',
            'jpeg': 'bi-file-image',
            'png': 'bi-file-image'
        };
        return icones[extensao] || 'bi-file';
    }

    function pagarConta(id) {
        Swal.close();
        Swal.fire({
            title: 'Marcar como Pago?',
            text: 'Esta conta será marcada como totalmente paga.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Sim, marcar como pago',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: appUrl('/saidas/pagar'),
                    type: 'POST',
                    data: { id: id },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            Swal.fire({
                                title: 'Sucesso!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonText: 'OK'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Erro!',
                                text: response.message,
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                        }
                    },
                    error: function () {
                        Swal.fire({
                            title: 'Erro!',
                            text: 'Erro ao marcar conta como paga',
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                });
            }
        });
    }

    function deletarConta(id) {
        Swal.close();
        Swal.fire({
            title: 'Tem certeza?',
            text: 'Esta ação não poderá ser desfeita!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sim, excluir',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: appUrl('/saidas/deletar'),
                    type: 'POST',
                    data: { id: id },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            Swal.fire({
                                title: 'Excluído!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonText: 'OK'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Erro!',
                                text: response.message,
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                        }
                    },
                    error: function () {
                        Swal.fire({
                            title: 'Erro!',
                            text: 'Erro ao excluir conta a pagar',
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                });
            }
        });
    }
</script>

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