(function ($) {

    var forms = $('.wpcf7-form');
    forms.each(function () {
        var formId = $(this).find('input[name="_wpcf7"]').val();
        var form_div = $(this).find('.uacf7-form-' + formId);
        var uacf7_wa_otp = $('.uacf7-form-' + formId).find('.uacf7_otp_recognation');

        var phone = form_div.find(".wpcf7-tel")[0];
        var phoneError = uacf7_wa_otp.find("#phone-error");
        var sendButton = uacf7_wa_otp.find("#otp_send");
        var sentOtp = uacf7_wa_otp.find("#sent-otp");
        var otpInput = uacf7_wa_otp.find("#otp");
        var resultDiv = uacf7_wa_otp.find("#otp_result");
        var protection_method = $(uacf7_wa_otp).attr('protection-method');

        //Send button action
        sendButton.click(function (e) {
            phoneError.text('');

            var phoneNumber = $(phone).val();
            // console.log(phoneNumber)
            const phonePattern = /^\+?[1-9]\d{10,14}$/;
            
            if (!phonePattern.test(phoneNumber)) {
                phoneError.text('Invalid phone number. Please enter a valid international number.');
            } else {
                var sendData = {
                    action: 'send_otp_ajax_action', // The action to trigger in PHP
                    nonce: uacf7_wa_otp_settings.nonce, 
                    data: {phone: phoneNumber} // Your data to send to PHP
                };

                // console.log(uacf7_wa_otp_settings.ajax_url)
                $.post(uacf7_wa_otp_settings.ajax_url, sendData, function(response) {
                    // console.log(response)
                    if (response.success) {
                        sentOtp.text('Sent OTP successfully. If not received, please resend again.');
                    } else {
                        phoneError.text(response.data);
                    }
                });
            }
            
            resultDiv.text('');
            otpInput.val('');
            e.preventDefault();
        });

        //Conditionally make submission event false
        $(window).on('load', function () {

            var form_submit = uacf7_wa_otp.closest(`.uacf7-form-${formId}`).find('.wpcf7-submit');

            form_submit.on('click', function (e) {
                e.preventDefault(); // Always prevent form submission initially

                var otpValue = otpInput.val();
                var phoneNumber = $(phone).val();

                // Check if otpValue is empty
                if (typeof otpValue !== 'undefined' && otpValue.trim() === '') {
                    // Field is empty, set warning message and prevent form submission
                    resultDiv.text(uacf7_wa_otp_settings.otpRequiredMessage).css("color", "#DC2626");
                    return;
                }

                // If it's not empty, compare it with the expected value
                var compareData = {
                    action: 'compare_otp_ajax_action', // The action to trigger in PHP
                    nonce: uacf7_wa_otp_settings.nonce, 
                    data: {phone: phoneNumber, otp: otpValue} // Your data to send to PHP
                };

                $.post(uacf7_wa_otp_settings.ajax_url, compareData, function(response) {
                    // console.log(response)
                    if (response.success) {
                        // OTP validated, allow form submission
                        resultDiv.text(uacf7_wa_otp_settings.otpValidatedMessage).css("color", "#46b450");

                        // Remove preventDefault and manually submit the form
                        form_submit.off('click').trigger('click');
                        // form_submit.off('click');
                        // uacf7_wa_otp.closest(`.uacf7-form-${formId}`).submit();
                    } else {
                        // If it does not match, set a failure message
                        resultDiv.text(uacf7_wa_otp_settings.otpValidationFailed).css("color", "#DC2626");
                    }
                });
            });
        });
    });

})(jQuery);