<?php
ob_start();

$module = $module ?? [];
$routeBase = $module['routeBase'] ?? '/vendas';
$singular = $module['singular'] ?? 'Venda';
$plural = $module['plural'] ?? 'Vendas';
$icon = $module['createIcon'] ?? 'bi bi-cart-plus';
$subtitle = $module['createSubtitle'] ?? 'Preencha os dados da venda e adicione os itens';
$formId = $module['formId'] ?? 'form-venda';
$emptyItemsMessage = $module['emptyItemsMessage'] ?? 'Adicione pelo menos um item à venda!';
$saveLabel = $module['saveLabel'] ?? ('Salvar ' . $singular);
$cancelLabel = $module['cancelLabel'] ?? 'Cancelar';
$successRedirect = $module['successRedirect'] ?? $routeBase;
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="<?= htmlspecialchars($icon) ?> me-2"></i> Nova <?= htmlspecialchars($singular) ?></h2>
        <p class="text-muted"><?= htmlspecialchars($subtitle) ?></p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url($routeBase) ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i> Voltar
        </a>
    </div>
</div>

<form id="<?= htmlspecialchars($formId) ?>" method="POST" action="<?= url($routeBase . '/criar') ?>">
    <?php include ROOT_PATH . '/views/vendas/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-success btn-lg">
                    <i class="bi bi-check-circle me-2"></i> <?= htmlspecialchars($saveLabel) ?>
                </button>
                <a href="<?= url($routeBase) ?>" class="btn btn-outline-secondary btn-lg">
                    <i class="bi bi-x-circle me-2"></i> <?= htmlspecialchars($cancelLabel) ?>
                </a>
            </div>
        </div>
    </div>
</form>

<script>
const FORM_ID = '<?= addslashes($formId) ?>';
const SUCCESS_REDIRECT = '<?= addslashes($successRedirect) ?>';
const EMPTY_ITEMS_MESSAGE = '<?= addslashes($emptyItemsMessage) ?>';

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

        // Remover required de campos desabilitados antes da validação
        $('#empresa_id, #customer_search, #vendor_id, #auxiliary_vendor_id').each(function() {
            if ($(this).prop('disabled')) {
                $(this).removeAttr('required');
            }
        });

        // Validar se há itens
        if (itensTabela.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Atenção',
                text: EMPTY_ITEMS_MESSAGE
            });
            $('#itens-tab').tab('show');
            return false;
        }

        // Não precisa validar cliente - pode ser Consumidor Final (vazio)

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

        // Adicionar campos desabilitados (disabled) que não são incluídos no serialize()
        const disabledFields = ['vendor_id', 'auxiliary_vendor_id', 'empresa_id', 'customer_search', 'customer_id'];
        disabledFields.forEach(function(fieldName) {
            const $field = $(`#${fieldName}, [name="${fieldName}"]`);
            if ($field.length && $field.val()) {
                // Se o campo não foi incluído no serialize, adicionar manualmente
                if (formData.indexOf(fieldName + '=') === -1) {
                    formData += (formData ? '&' : '') + encodeURIComponent(fieldName) + '=' + encodeURIComponent($field.val());
                }
            }
        });
        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(() => {
                        window.location.href = response.redirect || appUrl(SUCCESS_REDIRECT);
                    });
                } else {
                    $btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i> ' + <?= json_encode($saveLabel) ?>);
                    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> ' + <?= json_encode($saveLabel) ?>);
                const response = xhr.responseJSON || {};
                Swal.fire({
                    icon: 'error',
                    title: 'Erro',
                    text: response.message || 'Erro ao salvar ' + <?= json_encode(mb_strtolower($singular)) ?>
                });
            }
        });
    });
});
</script>

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