$(document).ready(function () {
    var currentSection = 0;
    var sections = $('.form-section');
    var progressBar = $('.progress-bar');

    // Inicializar todos los tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Restricción para campos numéricos
    $('.numeric-only').on('input', function () {
        this.value = this.value.replace(/[^0-9.]/g, '');
        // Permitir solo un punto decimal
        if ((this.value.match(/\./g) || []).length > 1) {
            this.value = this.value.slice(0, -1);
        }
    });

    // Validación adicional para email
    $('#email').on('blur', function () {
        var email = $(this).val();
        var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

        if (email && !emailPattern.test(email)) {
            $(this).addClass('is-invalid');
        } else {
            $(this).removeClass('is-invalid');
        }
    });

    function showSection(index) {
        sections.hide();
        $(sections[index]).show();
        updateProgressBar(index);
    }

    function updateProgressBar(index) {
        var progress = ((index + 1) / sections.length) * 100;
        progressBar.css('width', progress + '%');
        progressBar.text('Paso ' + (index + 1) + ' de ' + sections.length);
    }

    $('.next').click(function () {
        var currentFormSection = $(sections[currentSection]);
        var isValid = true;

        currentFormSection.find('input, select, textarea').each(function () {
            if (!this.checkValidity()) {
                $(this).addClass('is-invalid');
                isValid = false;
            } else {
                $(this).removeClass('is-invalid');
            }
        });

        if (isValid && currentSection < sections.length - 1) {
            currentSection++;
            showSection(currentSection);
        }
    });

    $('.prev').click(function () {
        if (currentSection > 0) {
            currentSection--;
            showSection(currentSection);
        }
    });

    showSection(currentSection);

    // Prevenir el envío del formulario al presionar Enter
    $('#quotationForm').on('keypress', function (e) {
        if (e.which === 13) {
            e.preventDefault();
        }
    });

    $('#quotationForm').submit(function (e) {
        e.preventDefault();
        var form = $(this);

        // Establecer valores de checkboxes no seleccionados a "no"
        form.find('input[type="checkbox"]').each(function () {
            if (!this.checked) {
                $(this).prop('checked', true).val('no');
            }
        });

        // Validar el formulario
        var isValid = true;
        form.find('input, select, textarea').each(function () {
            if (!this.checkValidity()) {
                $(this).addClass('is-invalid');
                isValid = false;
            } else {
                $(this).removeClass('is-invalid');
            }
        });

        if (!isValid) {
            return;
        }

        // Primera solicitud AJAX para enviar el formulario por correo
        var ajax1 = $.ajax({
            type: 'POST',
            url: 'php/quoteEmail.php',
            data: form.serialize()
        });

        // Segunda solicitud AJAX para guardar los datos en la base de datos
        var formData = new FormData(form[0]);
        formData.append('action', 'addPotentialCustomer');
        var ajax2 = $.ajax({
            url: '../login/database/model/potentialcostumer.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false
        });

        // Manejar ambas respuestas
        $.when(ajax1, ajax2).done(function (response1, response2) {
            var data1 = JSON.parse(response1[0]);
            var data2 = JSON.parse(response2[0]);

            if (data1.success) {
                showalert('success', data1.message);
            } else {
                showalert('danger', data1.message);
            }

            form[0].reset();
            setTimeout(function () {
                location.reload();
            }, 2000);
        }).fail(function (response) {
            console.log('Error en alguna de las solicitudes:', response.responseText);
        });

        function showalert(type, message) {
            var notyf = new Notyf({
                duration: 3000,
                position: { x: 'center', y: 'top' }
            });

            if (type === 'success') {
                notyf.success(message);
            } else if (type === 'danger') {
                notyf.error(message);
            }
        }
    });
});