<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-pencil me-2"></i> Editar Conta</h2>
        <p class="text-muted"><?= htmlspecialchars($conta['name'] ?? '') ?></p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/plano-contas') ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i> Voltar
        </a>
    </div>
</div>

<form id="formConta" method="POST" action="<?= url('/plano-contas/editar') ?>">
    <?php include __DIR__ . '/form.php'; ?>

    <div class="row mt-4">
        <div class="col-12">
            <button type="submit" class="btn btn-primary btn-lg">
                <i class="bi bi-check-circle me-2"></i> Atualizar Conta
            </button>
            <a href="<?= url('/plano-contas') ?>" class="btn btn-outline-secondary btn-lg ms-2">
                <i class="bi bi-x-circle me-2"></i> Cancelar
            </a>
        </div>
    </div>
</form>

<script>
(function aguardarjQuery() {
    if (typeof jQuery === 'undefined') {
        setTimeout(aguardarjQuery, 100);
        return;
    }

    $(document).ready(function() {
        $('#formConta').on('submit', function(e) {
            e.preventDefault();

            const formData = $(this).serializeArray();
            const data = {};
            formData.forEach(item => {
                data[item.name] = item.value;
            });

            $('input[type="checkbox"]').each(function() {
                if (!$(this).is(':checked')) {
                    data[$(this).attr('name')] = '0';
                }
            });

            $.ajax({
                url: appUrl('/plano-contas/editar'),
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Toast.success(response.message);
                        setTimeout(() => {
                            window.location.href = response.redirect || appUrl('/plano-contas');
                        }, 1500);
                    } else {
                        Toast.error(response.message);
                    }
                },
                error: function(xhr) {
                    console.error('Erro:', xhr);
                    Toast.error('Erro ao atualizar conta. Verifique os dados.');
                }
            });
        });
    });
})();
</script>

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

