<?php
ob_start();
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="<?= url('/dashboard') ?>">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="<?= url('/entradas') ?>">Entradas</a></li>
                        <li class="breadcrumb-item active">Editar Entrada</li>
                    </ol>
                </div>
                <h4 class="page-title">
                    <i class="bi bi-pencil me-2"></i> Editar Entrada #<?= $conta['id'] ?? '' ?>
                </h4>
            </div>
        </div>
    </div>

    <form id="entradaForm" method="POST" action="<?= url('/entradas/editar') ?>">
        <input type="hidden" name="id" value="<?= $conta['id'] ?? '' ?>">

        <?php include ROOT_PATH . '/views/entradas/form.php'; ?>

        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-footer">
                        <button type="button" class="btn btn-primary" onclick="atualizarEntrada()">
                            <i class="bi bi-check-lg me-2"></i> Atualizar Entrada
                        </button>
                        <a href="<?= url('/entradas') ?>" class="btn btn-secondary">
                            <i class="bi bi-arrow-left me-2"></i> Voltar
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
function atualizarEntrada() {
    const form = document.getElementById('entradaForm');
    if (!form) {
        alert('Formulário não encontrado');
        return;
    }

    const formData = new FormData(form);
    const btn = event.target;
    const btnOriginalText = btn.innerHTML;

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Atualizando...';

    fetch('<?= url('/entradas/editar') ?>', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            window.location.href = data.data?.redirect || '<?= url('/entradas') ?>';
        } else {
            btn.disabled = false;
            btn.innerHTML = btnOriginalText;
            alert(data?.message || 'Erro ao atualizar');
        }
    })
    .catch(error => {
        btn.disabled = false;
        btn.innerHTML = btnOriginalText;
        console.error('Erro:', error);
        alert('Erro ao atualizar entrada');
    });
}
</script>

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