$(document).ready(function () {
    $(document).on('change', 'input[name="billingcycle"]', function (event) {
        var package = $(this).val();
        $('label').removeClass('bgcactive');
        $(this).closest('label').addClass('bgcactive');
        var off_price = $(this).closest('label').find('.off_price').text().trim(); // Use singular class name
        var price = $(this).closest('label').find('.price').text().trim(); // Use singular class name
        $("#inputBillingcycle").html(`<h3><i class='fa fa-inr'></i> ${off_price} <del> <i class='fa fa-inr'></i> ${price}</del></h3>`);
        $('.slected_package').val(package);
        $('select[id="slected_package_option"] option[value="' + package.replace("'", "\\'") + '"]').prop('selected', true);
    });
    $(document).on('change', '#slected_package_option', function (event) {
        var package = $(this).val();
        $('.slected_package').val(package);
        $('input[name="billingcycle"][value="' + package + '"]').prop('checked', true);
    });
    let time = 5 * 60;
    function startCountdown() {
        let $timerElement = $('#tmr');
        let countdownInterval = setInterval(function () {
            let minutes = Math.floor(time / 60);
            let seconds = time % 60;
            seconds = seconds < 10 ? '0' + seconds : seconds;
            $timerElement.text(minutes + ":" + seconds);
            time--;
            if (time < 0) {
                clearInterval(countdownInterval);
                $timerElement.text("Expired");
            }
        }, 1000);
    }
    startCountdown();
    $(document).on('click', '.btn-apply-promo', function (event) {
        event.preventDefault();
        $(this).closest('.vouchertoggle').addClass('bgcactive');
        $('.product_discount_promo').val(100);
        $('.product_discount_promo_text').text(100);
        $('.btn-apply-promo-tr').removeClass('d-none');
        $('.product_name').val('BEST SELLER');
        $('.product_name_text').text('BEST SELLER');
        $('.product_price').val(2950);
        $('.product_price_text').text(2950);
        $('#package_1').attr('src', 'checkout/pack1.jpg');
        $('#package_2').attr('src', 'checkout/pack2.jpg');
        $('#package_3').attr('src', 'checkout/pack1-3.jpg');
        Gettotal_amount();

    });

    $(document).on('click', '#package_1', function (event) {
        event.preventDefault();
        let item_name = $(this).attr('data-item_name');
        $('.product_name').val(item_name);
        $('.product_name_text').text(item_name);
        let item_price = $(this).attr('data-item_price');
        $('.product_price').val(item_price);
        $('.product_price_text').text(item_price);
        $('#package_1').attr('src', 'checkout/pack1-s.jpg');
        $('#package_2').attr('src', 'checkout/pack2.jpg');
        $('#package_3').attr('src', 'checkout/pack3.jpg');
        $('.vouchertoggle').removeClass('bgcactive');
        $('.product_discount_promo').val(0);
        $('.product_discount_promo_text').text(0);
        $('.btn-apply-promo-tr').addClass('d-none');
        Gettotal_amount();
    });


    $(document).on('click', '#package_2', function (event) {
        event.preventDefault();
        let item_name = $(this).attr('data-item_name');
        $('.product_name').val(item_name);
        $('.product_name_text').text(item_name);
        //item_price
        let item_price = $(this).attr('data-item_price');
        $('.product_price').val(item_price);
        $('.product_price_text').text(item_price);
        $('#package_1').attr('src', 'checkout/pack1.jpg');
        $('#package_2').attr('src', 'checkout/pack1-2.jpg');
        $('#package_3').attr('src', 'checkout/pack3.jpg');
        $('.vouchertoggle').removeClass('bgcactive');
        $('.product_discount_promo').val(0);
        $('.product_discount_promo_text').text(0);
        $('.btn-apply-promo-tr').addClass('d-none');
        Gettotal_amount();

    });

    $(document).on('click', '#package_3', function (event) {
        event.preventDefault();
        let item_name = $(this).attr('data-item_name');
        $('.product_name').val(item_name);
        $('.product_name_text').text(item_name);
        //item_price
        let item_price = $(this).attr('data-item_price');
        $('.product_price').val(item_price);
        $('.product_price_text').text(item_price);
        $('#package_1').attr('src', 'checkout/pack1.jpg');
        $('#package_2').attr('src', 'checkout/pack2.jpg');
        $('#package_3').attr('src', 'checkout/pack1-3.jpg');
        Gettotal_amount();
    });

    $(document).on('click', 'input[name="payment_method"]', function () {
        let payment_method = $(this).val();
        if (payment_method == 'cod') {
            $('.payment_discount_tr').addClass('d-none');
            $('.payment_discount').val(0);
            $('.payment_discount_text').text(0);
            // let product_price = parseFloat($('.product_price').val());
            // let discount = 0;
            // let total_amount = product_price - discount;
            // $('.total_amount').val(total_amount);
            // $('.total_amount_text').text(total_amount);
            Gettotal_amount();
        }
        if (payment_method == 'online') {

            $('.payment_discount_tr').removeClass('d-none');
            // $('.payment_discount').val(discount);
            // $('.payment_discount_text').text(discount);
            // let product_price = parseFloat($('.product_price').val());
            // let discount = 199;
            // let total_amount = product_price - discount;
            // $('.total_amount').val(total_amount);
            // $('.total_amount_text').text(total_amount);

            Gettotal_amount();
        }
    });

    function Gettotal_amount() {
        let product_price = parseFloat($('.product_price').val());
        let product_discount_promo = parseFloat($('.product_discount_promo').val());
        let payment_discount = parseFloat($('.payment_discount').val());
        let total_amount = product_price - product_discount_promo - payment_discount;
        $('.total_amount').val(total_amount);
        $('.total_amount_text').text(total_amount);
        // Payment Discount 
        let discount_percentage = parseInt($('.offer_payment_discount').data('offerdiscount'), 10);
        let discount = (product_price * discount_percentage) / 100;
        $('.payment_discount').val(discount);
        $('.payment_discount_text').text(discount);
    }
});

$(document).ready(function () {
    let on_keyup_response = null;
    // Keyup event handler for phone number input field
    $('input[name="user_phone"]').on('keyup', function () {
        var user_phone = $(this).val();
        var user_name = $(this).closest('form').find('input[name="user_name"]').val() || '';
        if (user_phone.length === 10 && user_name !== '') {
            var form = $(this).closest('form');
            var form_data = new FormData(form[0]);
            form_data.append('fontEnd_userDataSave', true);
            $.ajax({
                url: 'admin/controllers-abhay.php',
                method: 'POST',
                data: form_data,
                processData: false,
                contentType: false,
                beforeSend: function () {
                    // Optional: You can show a loading spinner here if needed
                },
                success: function (response) {
                    if (response.status !== undefined && response.message !== undefined) {
                        on_keyup_response = response;
                        console.log("AJAX Response: ", on_keyup_response);
                    } else {
                        console.error("Invalid response format:", response);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('Error occurred:', error);  // Improved error handling
                }
            });
        }
    });

    $(document).on('submit', '.pop_modal_enquery', function (event) {
        event.preventDefault();
        var self = $(this); // Save the form context
        var submitButton = self.find('button[type="submit"]');
        var submitText = submitButton.html();
        var userPhone = self.find('input[name="user_phone"]').val().trim() || '';
        var userName = self.find('input[name="user_name"]').val().trim() || '';
        self.find('input').removeClass('invalid valid');
        self.find('#error-message').addClass('d-none').html('');
        let valid = true;
        if (userName === '') {
            self.find('input[name="user_name"]').addClass('invalid');
            self.find('#error-message').removeClass('d-none').html('Please enter a valid Name');
            valid = false;
        } else {
            self.find('input[name="user_name"]').addClass('valid');
        }
        if (userPhone.length !== 10 || !/^\d{10}$/.test(userPhone)) {
            self.find('input[name="user_phone"]').addClass('invalid');
            self.find('#error-message').removeClass('d-none').html('Please enter a valid 10-digit phone number');
            valid = false;
        } else {
            self.find('input[name="user_phone"]').addClass('valid');
        }
        if (!valid) return;
        var form = self.closest('form');
        var formData = new FormData(form[0]);
        formData.append('submit_enquery', true);
        $.ajax({
            url: 'admin/controllers-abhay.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function () {
                submitButton.html('<i class="fa fa-spinner fa-spin"></i> Loading...');
                submitButton.prop('disabled', true); // Disable the button while processing
            },
            success: function (response) {
                console.log(response); 
                if (response.status) {
                    submitButton.remove();
                    self.find('#success-message').removeClass('d-none').html(response.message);
                    setTimeout(function () {
                        window.location.replace("checkout.php");
                    }, 1000);
                } else {
                    submitButton.html(submitText).prop('disabled', false);
                    self.find('#error-message').removeClass('d-none').html(response.message);
                }
            },
            error: function (xhr, status, error) {
                submitButton.html(submitText).prop('disabled', false);
                console.error('Error occurred:', error);
                self.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
            }
        });
    });

});

// get city by pin

$(document).on('change', 'input[name="zip_code"]', function () {
    var pincode = $(this).val();
    // console.log(pincode);

    // Validate pincode: non-empty, 6 digits, and numeric
    if (pincode === '' || pincode.length !== 6 || isNaN(pincode)) {
        alert('Enter a valid 6-digit pincode');
        $(this).val(''); // Clear the pincode field
        $('input[name="city"]').val(''); // Clear city field
        $('input[name="state"]').val(''); // Clear state field
    } else {
        $.ajax({
            url: 'admin/controllers-abhay.php',
            method: 'POST',
            data: {
                GetAddressbypin: true, // Match with the PHP parameter name
                pincode: pincode
            },
            beforeSend: function () {
                // Optional: show loading spinner if needed
            },
            success: function (response) {
                var getData = $.parseJSON(response); // Parse the JSON response
                if (getData.status) {
                    // Fill the city and state fields with response data
                    $('input[name="state"]').val(getData.data.state);
                    $('input[name="city"]').val(getData.data.city);
                } else {
                    // If response indicates failure, clear the fields
                    $('input[name="zip_code"]').val('');
                    $('input[name="city"]').val('');
                    $('input[name="state"]').val('');
                    alert(getData.message); // Display error message
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred:', error); // Improved error handling
            }
        });
    }
});

$(document).on('click', '#submitType', function (event) {
    event.preventDefault();

    let form = $('#checkoutform');
    form.find('.error_form').remove(); // Clear previous error messages

    // Get form input values
    let first_name = form.find('input[name="first_name"]').val();
    let zip_code = form.find('input[name="zip_code"]').val();
    let address1 = form.find('input[name="address1"]').val();
    let city = form.find('input[name="city"]').val();
    let state = form.find('input[name="state"]').val();
    let email = form.find('input[name="email"]').val();
    let phone = form.find('input[name="phone"]').val();
    let payment_method = form.find('input[name="payment_method"]').val();
    let product_name = form.find('input[name="product_name"]').val();
    let product_price = form.find('input[name="product_price"]').val();
    let isValid = true;
    if (first_name === '') {
        form.find('input[name="first_name"]').addClass('invalid');
        form.find('input[name="first_name"]').parent().append('<p class="error_form">Please enter a valid Name</p>');
        isValid = false;
    }
    let zipCodePattern = /^\d{6}$/;
    if (zip_code === '' || !zipCodePattern.test(zip_code)) {
        form.find('input[name="zip_code"]').addClass('invalid');
        form.find('input[name="zip_code"]').parent().append('<p class="error_form">Please enter a valid Zip Code</p>');
        isValid = false;
    }
    if (address1 === '') {
        form.find('input[name="address1"]').addClass('invalid');
        form.find('input[name="address1"]').parent().append('<p class="error_form">Please enter your address</p>');
        isValid = false;
    }
    if (city === '') {
        form.find('input[name="city"]').addClass('invalid');
        form.find('input[name="city"]').parent().append('<p class="error_form">Please enter a valid City</p>');
        isValid = false;
    }
    if (state === '') {
        form.find('input[name="state"]').addClass('invalid');
        form.find('input[name="state"]').parent().append('<p class="error_form">Please enter a valid State</p>');
        isValid = false;
    }
    let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    // if (email === '' || !emailPattern.test(email)) {
    //     form.find('input[name="email"]').addClass('invalid');
    //     form.find('input[name="email"]').parent().append('<p class="error_form">Please enter a valid Email Address</p>');
    //     isValid = false;
    // }
    let phonePattern = /^\d{10}$/; // Change this pattern based on country if needed
    if (phone === '' || !phonePattern.test(phone)) {
        form.find('input[name="phone"]').addClass('invalid');
        form.find('input[name="phone"]').parent().append('<p class="error_form">Please enter a valid 10-digit Phone Number</p>');
        isValid = false;
    }
    if (payment_method === '') {
        form.find('input[name="payment_method"]').addClass('invalid');
        form.find('input[name="payment_method"]').parent().append('<p class="error_form">Please select a Payment Method</p>');
        isValid = false;
    }
    if (product_name === '') {
        form.find('input[name="product_name"]').addClass('invalid');
        form.find('input[name="product_name"]').parent().append('<p class="error_form">Product Name is required</p>');
        isValid = false;
    }
    if (product_price === '' || isNaN(product_price)) {
        form.find('input[name="product_price"]').addClass('invalid');
        form.find('input[name="product_price"]').parent().append('<p class="error_form">Please select at least one valid product.</p>');
        isValid = false;
    }
    if (isValid == false) {
        console.log('not isValid');
        return false;
    }
    let formData = new FormData(form[0]);
    formData.append('order_now', true);
    let submitButton = form.find('button[type="submit"]');
    let submitText = submitButton.html();
    submitButton.prop('disabled', true);
    // Perform AJAX request
    $.ajax({
        url: 'admin/controllers-abhay.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function () {
            $('#progress_bar').removeClass('d-none');
            $('#checkout_success_res').addClass('d-none').html();
            $('#checkout_error_res').addClass('d-none').html()
        },
        success: function (response) {
            $('#progress_bar').addClass('d-none');
            if (response.status) {
                submitButton.remove();
                // alert(response.message);
                $('#checkout_success_res').removeClass('d-none').html(response.message);
                console.log(response);
                $('#otp_Verify_html').removeClass('d-none');
                // window.location.replace(response.url);
            } else {
                $('#checkout_error_res').removeClass('d-none').html(response.message);

                submitButton.html(submitText).prop('disabled', false);
                form.find('#error-message').removeClass('d-none').html(response.message);
            }
        },
        error: function (xhr, status, error) {
            submitButton.html(submitText).prop('disabled', false);
            console.error('Error occurred:', error);
            form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
        }

    });
});

//OTP Files
const inputs = document.querySelectorAll('.otp-input input');
const timerDisplay = document.getElementById('timer');
const resendButton = document.getElementById('resendButton');
let timeLeft = 180; // 3 minutes in seconds
let timerId;

function startTimer() {
    timerId = setInterval(() => {
        if (timeLeft <= 0) {
            clearInterval(timerId);
            timerDisplay.textContent = "Code expired";
            resendButton.disabled = false;
            inputs.forEach(input => input.disabled = true);
        } else {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timerDisplay.textContent = `Time remaining: ${minutes}:${seconds.toString().padStart(2, '0')}`;
            timeLeft--;
        }
    }, 1000);
}

function resendOTP() {
    // Here you would typically call your backend to resend the OTP
    // alert("New OTP sent!");
    timeLeft = 180;
    inputs.forEach(input => {
        input.value = '';
        input.disabled = false;
    });
    resendButton.disabled = true;
    inputs[0].focus();
    clearInterval(timerId);
    startTimer();

    $.ajax({
        url: 'admin/controllers-abhay.php',
        method: 'POST',
        data: { resendOtpBtn: true },
        beforeSend: function () {
            $('#progress_bar').removeClass('d-none');
            $('#checkout_success_res').addClass('d-none').html();
            $('#checkout_error_res').addClass('d-none').html()
        },
        success: function (response) {
            $('#progress_bar').addClass('d-none');
            if (response.status === true) {
                $('#checkout_success_res').removeClass('d-none').html(response.message);
            } else {
                $('#checkout_error_res').removeClass('d-none').html(response.message);
            }
        },
        error: function (xhr, status, error) {
            submitButton.html(submitText).prop('disabled', false);
            console.error('Error occurred:', error);
            form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
        }

    });
}

inputs.forEach((input, index) => {
    input.addEventListener('input', (e) => {
        if (e.target.value.length > 1) {
            e.target.value = e.target.value.slice(0, 1);
        }
        if (e.target.value.length === 1) {
            if (index < inputs.length - 1) {
                inputs[index + 1].focus();
            }
        }
    });

    input.addEventListener('keydown', (e) => {
        if (e.key === 'Backspace' && !e.target.value) {
            if (index > 0) {
                inputs[index - 1].focus();
            }
        }
        if (e.key === 'e') {
            e.preventDefault();
        }
    });
});

function verifyOTP() {
    const otp = Array.from(inputs).map(input => input.value).join('');
    if (otp.length === 4) {
        if (timeLeft > 0) {
            $.ajax({
                url: 'admin/controllers-abhay.php',
                method: 'POST',
                data: { submit_otp: true, otp: otp },
                beforeSend: function () {
                    $('#progress_bar').removeClass('d-none');
                    $('#checkout_success_res').addClass('d-none').html();
                    $('#checkout_error_res').addClass('d-none').html()
                },
                success: function (response) {
                    $('#progress_bar').addClass('d-none');
                    console.log(response);
                    if (response.status === true) {
                        $('#otp_Verify_html').addClass('d-none');
                        // $('#buy_now_btn').removeClass('d-none');
                        $('#checkout_success_res').removeClass('d-none').html(response.message);
                        $('#buynowbtn').click();
                    } else {
                        $('#checkout_error_res').removeClass('d-none').html(response.message);
                    }
                },
                error: function (xhr, status, error) {
                    submitButton.html(submitText).prop('disabled', false);
                    console.error('Error occurred:', error);
                    form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
                }

            });
        } else {
            $('#checkout_error_res').removeClass('d-none').html('OTP has expired. Please request a new one.');
        }
    } else {
        $('#checkout_error_res').removeClass('d-none').html('Please enter a 4-digit OTP.');
    }
}
startTimer();

// function resendOTP() {
//     // Backend call to resend OTP would go here
//     $.ajax({
//         url: 'admin/controllers-abhay.php',
//         method: 'POST',
//         data: { resendOtpBtn: true },
//         beforeSend: function () {
//             $('#progress_bar').removeClass('d-none');
//             $('#checkout_success_res').addClass('d-none').html();
//             $('#checkout_error_res').addClass('d-none').html()
//         },
//         success: function (response) {
//             $('#progress_bar').addClass('d-none');
//             if (response.status === true) {
//                 $('#checkout_success_res').removeClass('d-none').html(response.message);
//             } else {
//                 $('#checkout_error_res').removeClass('d-none').html(response.message);
//             }
//         },
//         error: function (xhr, status, error) {
//             submitButton.html(submitText).prop('disabled', false);
//             console.error('Error occurred:', error);
//             form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
//         }

//     });
//     timeLeft = 180;
//     inputs.forEach(input => {
//         input.value = '';
//         input.disabled = false;
//     });
//     resendButton.disabled = true;
//     inputs[0].focus();
//     clearInterval(timerId);
//     startTimer();
// }


// // const inputs = document.querySelectorAll('.otp-input');
// inputs.forEach((input, index) => {
//     // Event listener for the 'input' event
//     input.addEventListener('input', (e) => {
//         const { value } = e.target;
//         if (value.length > 1) {
//             e.target.value = value.slice(0, 1); // Limit input to one character
//         }
//         if (value.length === 1) {
//             if (index < inputs.length - 1) {
//                 inputs[index + 1].focus(); // Automatically move to the next input
//             }
//         }
//     });

//     // Event listener for the 'keydown' event to handle backspace and prevent invalid input
//     input.addEventListener('keydown', (e) => {
//         if (e.key === 'Backspace' && !e.target.value) {
//             if (index > 0) {
//                 inputs[index - 1].focus(); // Move to the previous input if backspace is pressed
//             }
//         }
//         if (e.key === 'e' || e.key === '+' || e.key === '-') {
//             e.preventDefault(); // Prevent unwanted characters
//         }
//     });
// });


// function verifyOTP() {
//     const otp = Array.from(inputs).map(input => input.value).join('');
//     // console.log(otp);
//     if (otp.length === 4) {
//         if (timeLeft > 0) {
// $.ajax({
//     url: 'admin/controllers-abhay.php',
//     method: 'POST',
//     data: { submit_otp: true, otp: otp },
//     beforeSend: function () {
//         $('#progress_bar').removeClass('d-none');
//         $('#checkout_success_res').addClass('d-none').html();
//         $('#checkout_error_res').addClass('d-none').html()
//     },
//     success: function (response) {
//         $('#progress_bar').addClass('d-none');
//         console.log(response);
//         if (response.status === true) {
//             $('#otp_Verify_html').addClass('d-none');
//             $('#buy_now_btn').removeClass('d-none');
//             $('#checkout_success_res').removeClass('d-none').html(response.message);
//             $('#buynowbtn').click();
//         } else {
//             $('#checkout_error_res').removeClass('d-none').html(response.message);
//         }
//     },
//     error: function (xhr, status, error) {
//         submitButton.html(submitText).prop('disabled', false);
//         console.error('Error occurred:', error);
//         form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
//     }

// });
//             // Send OTP to server for verification
//         } else {
//             $('#checkout_error_res').removeClass('d-none').html('OTP has expired. Please request a new one.');
//         }
//     } else {
//         $('#checkout_error_res').removeClass('d-none').html('Please enter a 4-digit OTP.');
//     }
// }


// $(document).on('click', '#Verifyotp', function (event) {
//     event.preventDefault();
//     let otp1 = $('#otp1').val();
//     let otp2 = $('#otp2').val();
//     let otp3 = $('#otp3').val();
//     let otp4 = $('#otp4').val();
//     if (otp1 == '' || otp2 == '' || otp3 == '' || otp4 == '') {
//         alert('Enter the OTP')
//     }
//     else {
//         let otp = otp1 + otp2 + otp3 + otp4;
//         $.ajax({
//             url: 'admin/controllers-abhay.php',
//             method: 'POST',
//             data: { submit_otp: true, otp: otp },
//             beforeSend: function () {
//                 $('#progress_bar').removeClass('d-none');
//                 $('#checkout_success_res').addClass('d-none').html();
//                 $('#checkout_error_res').addClass('d-none').html()
//             },
//             success: function (response) {
//                 $('#progress_bar').addClass('d-none');
//                 console.log(response);
//                 if (response.status === true) {
//                     $('#otp_Verify_html').addClass('d-none');
//                     $('#buy_now_btn').removeClass('d-none');
//                     $('#checkout_success_res').removeClass('d-none').html(response.message);
//                     $('#buynowbtn').click();
//                 } else {
//                     $('#checkout_error_res').removeClass('d-none').html(response.message);
//                 }
//             },
//             error: function (xhr, status, error) {
//                 submitButton.html(submitText).prop('disabled', false);
//                 console.error('Error occurred:', error);
//                 form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
//             }

//         });
//     }
// });

// resendOtpBtn
// $(document).on('click', '#resendOtpBtn', function (event) {
//     event.preventDefault();

//     $.ajax({
//         url: 'admin/controllers-abhay.php',
//         method: 'POST',
//         data: { resendOtpBtn: true },
//         beforeSend: function () {
//             $('#progress_bar').removeClass('d-none');
//             $('#checkout_success_res').addClass('d-none').html();
//             $('#checkout_error_res').addClass('d-none').html()
//         },
//         success: function (response) {
//             $('#progress_bar').addClass('d-none');
//             if (response.status === true) {
//                 $('#checkout_success_res').removeClass('d-none').html(response.message);
//             } else {
//                 $('#checkout_error_res').removeClass('d-none').html(response.message);
//             }
//         },
//         error: function (xhr, status, error) {
//             submitButton.html(submitText).prop('disabled', false);
//             console.error('Error occurred:', error);
//             form.find('#error-message').removeClass('d-none').html('An error occurred. Please try again.');
//         }

//     });
// });
//buynowbtn

// $(document).on('click', '#buynowbtn', function (event) {
//     event.preventDefault();
//     let form = $('#checkoutform');
//     form.find('.error_form').remove();
//     let first_name = form.find('input[name="first_name"]').val();
//     let zip_code = form.find('input[name="zip_code"]').val();
//     let address1 = form.find('input[name="address1"]').val();
//     let city = form.find('input[name="city"]').val();
//     let state = form.find('input[name="state"]').val();
//     let email = form.find('input[name="email"]').val();
//     let phone = form.find('input[name="phone"]').val();
//     let payment_method = form.find('input[name="payment_method"]').val();
//     let product_name = form.find('input[name="product_name"]').val();
//     let product_price = form.find('input[name="product_price"]').val();
//     let isValid = true;
//     if (first_name === '') {
//         form.find('input[name="first_name"]').addClass('invalid');
//         form.find('input[name="first_name"]').parent().append('<p class="error_form">Please enter a valid Name</p>');
//         isValid = false;
//     }
//     let zipCodePattern = /^\d{6}$/;
//     if (zip_code === '' || !zipCodePattern.test(zip_code)) {
//         form.find('input[name="zip_code"]').addClass('invalid');
//         form.find('input[name="zip_code"]').parent().append('<p class="error_form">Please enter a valid Zip Code</p>');
//         isValid = false;
//     }
//     if (address1 === '') {
//         form.find('input[name="address1"]').addClass('invalid');
//         form.find('input[name="address1"]').parent().append('<p class="error_form">Please enter your address</p>');
//         isValid = false;
//     }
//     if (city === '') {
//         form.find('input[name="city"]').addClass('invalid');
//         form.find('input[name="city"]').parent().append('<p class="error_form">Please enter a valid City</p>');
//         isValid = false;
//     }
//     if (state === '') {
//         form.find('input[name="state"]').addClass('invalid');
//         form.find('input[name="state"]').parent().append('<p class="error_form">Please enter a valid State</p>');
//         isValid = false;
//     }
//     let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
//     let phonePattern = /^\d{10}$/; // Change this pattern based on country if needed
//     if (phone === '' || !phonePattern.test(phone)) {
//         form.find('input[name="phone"]').addClass('invalid');
//         form.find('input[name="phone"]').parent().append('<p class="error_form">Please enter a valid 10-digit Phone Number</p>');
//         isValid = false;
//     }
//     if (payment_method === '') {
//         form.find('input[name="payment_method"]').addClass('invalid');
//         form.find('input[name="payment_method"]').parent().append('<p class="error_form">Please select a Payment Method</p>');
//         isValid = false;
//     }
//     if (product_name === '') {
//         form.find('input[name="product_name"]').addClass('invalid');
//         form.find('input[name="product_name"]').parent().append('<p class="error_form">Product Name is required</p>');
//         isValid = false;
//     }
//     if (product_price === '' || isNaN(product_price)) {
//         form.find('input[name="product_price"]').addClass('invalid');
//         form.find('input[name="product_price"]').parent().append('<p class="error_form">Please select at least one valid product.</p>');
//         isValid = false;
//     }
//     if (isValid == false) {
//         console.log('not isValid');
//         return false;
//     }
//     let formData = new FormData(form[0]);
//     formData.append('buynowbtn', true);
//     $.ajax({
//         url: 'admin/controllers-abhay.php',
//         method: 'POST',
//         data: formData,
//         processData: false,
//         contentType: false,
//         beforeSend: function () {
//             $('#progress_bar').removeClass('d-none');
//         },
//         success: function (response) {
//             $('#progress_bar').addClass('d-none');
//             if (response.status) {
//                 window.location.replace(response.url);
//                 console.log(response);
//             } else {
//                 alert(response.message);
//             }
//         },
//         error: function (xhr, status, error) {
//             console.error('Error occurred:', error);
//         }

//     });
// });