<?php
ob_start();

$module = $module ?? [];
$routeBase = $module['routeBase'] ?? '/pre-vendas';
$singular = $module['singular'] ?? 'DAV';
$plural = $module['plural'] ?? 'DAVs';
$icon = $module['createIcon'] ?? 'bi bi-clipboard-plus';
$subtitle = $module['createSubtitle'] ?? 'Preencha a DAV com os itens e condições acordadas';
$formId = $module['formId'] ?? 'form-dav';
$emptyItemsMessage = $module['emptyItemsMessage'] ?? 'Adicione pelo menos um item à DAV!';
$saveLabel = $module['saveLabel'] ?? ('Salvar ' . $singular);
$cancelLabel = $module['cancelLabel'] ?? 'Cancelar';
$successRedirect = $module['successRedirect'] ?? $routeBase;
$slug = $module['slug'] ?? 'pre-vendas';
?>

<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/pre-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();

        if (itensTabela.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Atenção',
                text: EMPTY_ITEMS_MESSAGE
            });
            $('#itens-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(() => {
                        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;
include ROOT_PATH . '/views/layouts/app.php';
?>

