<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-building me-2"></i> Editar Centro de Custo</h2>
        <p class="text-muted">Altere os dados do centro de custo</p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/centro-custos') ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i> Voltar
        </a>
    </div>
</div>

<form id="formCentro" method="POST" action="<?= url('/centro-custos/editar') ?>">
    <input type="hidden" name="id" value="<?= $centro['id'] ?>">

    <?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 Centro de Custo
            </button>
            <a href="<?= url('/centro-custos') ?>" 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() {
        $('#formCentro').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() {
                data[$(this).attr('name')] = $(this).is(':checked') ? '1' : '0';
            });

            $.ajax({
                url: appUrl('/centro-custos/editar'),
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Toast.success(response.message);
                        setTimeout(() => {
                            window.location.href = response.data.redirect || '/centro-custos';
                        }, 1500);
                    } else {
                        Toast.error(response.message);
                    }
                },
                error: function(xhr) {
                    console.error('Erro:', xhr.responseText);
                    let mensagemErro = 'Erro ao atualizar centro de custo';
                    try {
                        const erro = JSON.parse(xhr.responseText);
                        mensagemErro = erro.message || mensagemErro;
                    } catch(e) {}
                    Toast.error(mensagemErro);
                }
            });
        });
    });
})();
</script>

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

