<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-pencil-square me-2"></i> Editar Compra</h2>
        <p class="text-muted">Atualize os dados da compra #<?= htmlspecialchars($compra['numero'] ?? $compra['id']) ?></p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/compras') ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i> Voltar
        </a>
    </div>
</div>

<form id="form-compra" method="POST" action="<?= url('/compras/editar') ?>">
    <input type="hidden" name="id" value="<?= $compra['id'] ?>">
    <?php include \ROOT_PATH . '/views/compras/form.php'; ?>

    <div class="row mt-4">
        <div class="col-12">
            <div class="d-grid gap-2 d-md-flex">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="bi bi-check-circle me-2"></i> Atualizar Compra
                </button>
                <a href="<?= url('/compras') ?>" class="btn btn-outline-secondary btn-lg">
                    <i class="bi bi-x-circle me-2"></i> Cancelar
                </a>
            </div>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    $('#form-compra').on('submit', function(e) {
        e.preventDefault();

        // Validar se há itens
        if (itensCompra.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Atenção',
                text: 'Adicione pelo menos um item à compra!'
            });
            $('#itens-tab').tab('show');
            return false;
        }

        // Validar fornecedor
        if (!$('#fornecedor_id').val()) {
            Swal.fire({
                icon: 'warning',
                title: 'Atenção',
                text: 'Selecione um fornecedor!'
            });
            $('#dados-tab').tab('show');
            return false;
        }

        const formData = $(this).serialize();
        const $btn = $(this).find('button[type="submit"]');
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Salvando...');

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Sucesso!',
                        text: response.message,
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        const redirectUrl = response.data?.redirect || response.redirect || '/compras';
                        window.location.href = appUrl(redirectUrl);
                    });
                } else {
                    $btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> Atualizar Compra');
                    Swal.fire({
                        icon: 'error',
                        title: 'Erro',
                        text: response.message
                    });
                }
            },
            error: function(xhr) {
                $btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> Atualizar Compra');
                const response = xhr.responseJSON || {};
                Swal.fire({
                    icon: 'error',
                    title: 'Erro',
                    text: response.message || 'Erro ao atualizar compra'
                });
            }
        });
    });
});
</script>

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

