<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-pencil-square me-2"></i> Editar DAV</h2>
        <p class="text-muted">DAV #<?= htmlspecialchars($venda['sale_number'] ?? '') ?></p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/pre-vendas') ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i> Voltar
        </a>
    </div>
</div>

<form id="form-dav" method="POST" action="<?= url('/pre-vendas/editar') ?>">
    <?php
    $formPath = ROOT_PATH . '/views/pre-vendas/form.php';
    if (!file_exists($formPath)) {
        error_log("Arquivo form.php não encontrado: {$formPath}");
        echo "<div class='alert alert-danger'>Erro: Arquivo de formulário da DAV não encontrado.</div>";
    } else {
        include $formPath;
    }
    ?>

    <div class="row mt-4">
        <div class="col-12">
            <div class="d-grid gap-2 d-md-flex">
                <button type="submit" class="btn btn-success btn-lg">
                    <i class="bi bi-check-circle me-2"></i> Atualizar DAV
                </button>
                <a href="<?= url('/pre-vendas') ?>" 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-dav').on('submit', function(e) {
        e.preventDefault();

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

        let formData = $(this).serialize();

        const readonlyFields = ['sale_number'];
        readonlyFields.forEach(function(fieldName) {
            const $field = $(`#${fieldName}, [name="${fieldName}"]`);
            if ($field.length && $field.val()) {
                if (formData.indexOf(fieldName + '=') === -1) {
                    formData += (formData ? '&' : '') + encodeURIComponent(fieldName) + '=' + encodeURIComponent($field.val());
                }
            }
        });

        const $idField = $('input[name="id"]');
        if ($idField.length && $idField.val()) {
            if (formData.indexOf('id=') === -1) {
                formData += (formData ? '&' : '') + 'id=' + encodeURIComponent($idField.val());
            }
        }

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

        $.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(() => {
                        window.location.href = response.redirect || appUrl('/pre-vendas');
                    });
                } else {
                    $btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> Atualizar DAV');
                    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 DAV');
                const response = xhr.responseJSON || {};
                let errorMsg = response.message || 'Erro ao atualizar DAV';

                if (xhr.status === 400 && response.errors) {
                    errorMsg += '\n\nDetalhes:\n' + JSON.stringify(response.errors, null, 2);
                }

                console.error('Erro ao atualizar DAV:', xhr);
                console.error('Dados enviados:', formData);
                console.error('Resposta do servidor:', response);

                Swal.fire({
                    icon: 'error',
                    title: 'Erro ' + (xhr.status || ''),
                    text: errorMsg,
                    width: '600px'
                });
            }
        });
    });
});
</script>

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

