/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Other/javascript.js to edit this template
 */


$ = jQuery;
$(document).ready(function () {
    $('#forgot-password-form').submit(function (e) {
        e.preventDefault();
        var userLogin = $('#user_login').val();
        var nonce = dspp_nonces.custom_forgot_password;
        var ajaxUrl = dspp_nonces.ajax_url;
        $.ajax({
            type: 'post',
            url: ajaxUrl,
            data: {
                action: 'dspp_custom_forgot_password',
                nonce: nonce,
                user_login: userLogin
            },
            success: function (response) {
                $('#reset-message').html(response);
            }
        });
    });
    $(document).on('click', '.btncart', function () {
        var site = $(this).data("site"); // Change 1 to the index of the column you want to copy
        var price = parseFloat($(this).data("price")); // Change 1 to the index of the column you want to copy
        var user_id = parseInt($(this).data("user-id")); // Change 1 to the index of the column you want to copy
        var service_id = parseInt($(this).data("post-id")); // Change 1 to the index of the column you want to copy
        var variation_id = parseInt($(this).data("variation-id"));        
        var $clickedButton = $(this);
        var nonce = dspp_nonces.add_to_session_nonce;
        var ajaxUrl = dspp_nonces.ajax_url;

        var website_data = {
            site: site,
            price: price,
            user_id: user_id,
            post_id: service_id,
            variation_id: variation_id
        };
        console.log(website_data);
        // 👇 Disable all buttons
        $('.btncart').prop('disabled', true);
        $('.view_cart_button').addClass('disabled').css('pointer-events', 'none');

        // 👇 Replace icon with spinner
        $clickedButton.find('.fa-cart-plus').addClass('d-none');
        $clickedButton.find('.spinner-border').removeClass('d-none');

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_add_to_session',
                nonce: nonce,
                site: site,
                price: price,
                user_id: user_id,
                post_id: service_id,
                data: website_data
            },
            success: function (response) {
                var responseObj = JSON.parse(response);

                if (responseObj.status === true) {
                    var cartCountElement = $('#cartCount');
                    var currentCount = parseInt(cartCountElement.text(), 10);
                    cartCountElement.text(currentCount + 1);

                    $('.view-cart').fadeIn().delay(2000).fadeOut();
                } else {
                    alert(responseObj.message);
                }

                // 👇 Revert spinner and re-enable buttons
                $('.btncart').prop('disabled', false);
                $('.view_cart_button').removeClass('disabled').css('pointer-events', 'auto');
                $clickedButton.find('.fa-cart-plus').removeClass('d-none');
                $clickedButton.find('.spinner-border').addClass('d-none');
            },
            error: function (errorThrown) {
                console.log('Error:', errorThrown);
                $('.btncart').prop('disabled', false);
                $('.view_cart_button').removeClass('disabled').css('pointer-events', 'auto');
                $clickedButton.find('.fa-cart-plus').removeClass('d-none');
                $clickedButton.find('.spinner-border').addClass('d-none');
            }
        });
    });

    $('#user-profile-form').on('submit', function (e) {
        e.preventDefault();

        var formData = $(this).serialize();
        var nonce = dspp_nonces.update_user_profile;
        var ajaxUrl = dspp_nonces.ajax_url;

        // Show spinner and disable button
        $('#saveProfileBtn').prop('disabled', true);
        $('#profileSpinner').removeClass('d-none');

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_update_user_profile',
                nonce: nonce,
                data: formData
            },
            success: function (response) {
                var responseObj = JSON.parse(response);
                var message = '';

                if (responseObj.status === 'success') {
                    message = '<p class="sucess-message alert alert-success">' + responseObj.message + '</p>';
                } else {
                    message = '<p class="error-message alert alert-danger">' + responseObj.message + '</p>';
                }

                $("#message-box").html(message).fadeIn(2000).delay(2000).fadeOut(2000);
            },
            error: function (errorThrown) {
                console.log('Error:', errorThrown);
            },
            complete: function () {
                // Hide spinner and enable button again
                $('#profileSpinner').addClass('d-none');
                $('#saveProfileBtn').prop('disabled', false);
            }
        });
    });
    $('#registration-form').on('submit', function (e) {
        e.preventDefault();
        var username = $('#username').val();
        var email = $('#email').val();
        var password = $('#psw').val();
        var confirmPassword = $('#psw-repeat').val();
        var usernameRegex = /^[a-zA-Z0-9_]+$/;
        var nonce = dspp_nonces.register_user;
        var ajaxUrl = dspp_nonces.ajax_url;
        if (!usernameRegex.test(username)) {
            $(".register-message").html("<span class='error'>Invalid username format. Use only letters, numbers, and underscores!</span>");
            $('#username').focus();
            return false;
        } else {
            $(".register-message").html();
        }
        if (password !== confirmPassword) {
            $(".register-message").html("<span class='error'>Password and Confirm Must be same!</span>");
            $('#psw-repeat').focus();
            return false; // Prevent form submission
        } else {
            $(".register-message").html();
        }
        var registrationData = {
            'action': 'dspp_register_user',
            'nonce': nonce,
            'username': username,
            'email': email,
            'password': password
        };
        $.ajax({
            type: 'POST',
            url: ajaxUrl,
            data: registrationData,
            success: function (response) {
                var parsed = JSON.parse(response);
                if (parsed.status == "error") {
                    $(".register-message").html("<span class='error'>" + parsed.message + "</span>");
                } else {
                    window.location.href = parsed.redirect;
                }
            }
        });
        return false;
    });
    $('#check_coupon_button').on('click', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var user_id = parseInt($btn.data("user-id"));
        var couponCode = $('#orderCoupon').val();
        var totalInvoiceElement = document.getElementById('total-invoice');
        var currentPriceText = totalInvoiceElement.textContent;
        var currentPriceSplitted = currentPriceText.split('$');
        var currentPrice = parseInt(currentPriceSplitted[1]);
        var nonce = dspp_nonces.check_coupon;
        var ajaxUrl = dspp_nonces.ajax_url;

        if (currentPrice > 0) {
            if (couponCode) {

                // Spinner show + disable all
                $btn.prop('disabled', true);
                $btn.find('.spinner-border').removeClass('d-none');
                jQuery('.btn_remove').prop('disabled', true);
                jQuery('.a_checkout').addClass('disabled');

                // Ajax call
                $.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'dspp_check_coupon',
                        nonce: nonce,
                        coupon_code: couponCode,
                        user_id: user_id
                    },
                    success: function (response) {
                        if (response.success) {
                            alert(response.message);
                            location.reload();
                        } else {
                            alert(response.message);
                        }
                    },
                    complete: function () {
                        $btn.prop('disabled', false);
                        $btn.find('.spinner-border').addClass('d-none');
                        // Enable back (optional)
                        jQuery('.btn_remove').prop('disabled', false);
                        jQuery('.a_checkout').removeClass('disabled');
                    },
                    error: function (errorThrown) {
                        console.log('Error:', errorThrown);
                    }
                });

            } else {
                alert('Error! Please enter coupon code.');
            }
        } else {
            alert('Error! You can not apply coupon to zero cart value.');
        }
    });
    $('.view_cart_button').on('click', function (e) {
        e.preventDefault();

        // Disable "View Cart" button and show spinner
        var $this = $(this);
        $this.addClass('disabled');
        $this.find('.spinner-border').removeClass('d-none');

        // Disable all Add to Cart buttons
        $('.btncart').prop('disabled', true);

        console.log(dspp_nonces);
        var nonce = dspp_nonces.dspp_view_cart_button;
        var ajaxUrl = dspp_nonces.ajax_url;

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_view_cart_button',
                nonce: nonce
            },
            success: function (response) {
                if (response.success) {
                    location.href = dspp_nonces.site_url + "/bits-cart";
                } else {
                    alert(response.message);
                    // Re-enable buttons and hide spinner on failure
                    $this.removeClass('disabled');
                    $this.find('.spinner-border').addClass('d-none');
                    $('.btncart').prop('disabled', false);
                }
            },
            error: function (errorThrown) {
                console.log('Error:', errorThrown);
                // Re-enable buttons and hide spinner on error
                $this.removeClass('disabled');
                $this.find('.spinner-border').addClass('d-none');
                $('.btncart').prop('disabled', false);
            }
        });
    });
    $('input[name="selected_billing_address"]').on('change', function () {
        // Hide all icons
        $('.selected-check-icon').addClass('d-none');

        // Show icon for selected address
        $(this).siblings('.card').find('.selected-check-icon').removeClass('d-none');

        // Enable continue button
        $('.continue_to_payment_old_address').removeClass('disabled');
    });

    $(".continue_to_payment_old_address").click(function (e) {
        e.preventDefault();
        var $btn = $(this);
        var invoiceId = new URL(window.location.href).searchParams.get("invoice_id");
        var billing_id = $("input[name='selected_billing_address']:checked").val();
        if (typeof billing_id === 'undefined') {
            alert('Select address or add new');
            return;
        }
        // Show spinner
        $btn.addClass('disabled');
        $btn.find('.spinner-border').removeClass('d-none');
        // Redirect
        var url = dspp_nonces.site_url + "/bits-payment?invoice_id=" + invoiceId + "&billing_id=" + billing_id;
        window.location.href = url;
    });

    var formSubmitted = false;

    $('#billing-form').on('submit', function (e) {
        e.preventDefault();

        var $form = $(this);
        var $submitBtn = $('#submit_billing_form');
        var $spinner = $submitBtn.siblings('.spinner-border');
        var url = window.location.href;
        var urlObj = new URL(url);
        var invoiceId = urlObj.searchParams.get("invoice_id");
        var nonce = dspp_nonces.save_billing_details_ajax;
        var ajaxUrl = dspp_nonces.ajax_url;

        if (!formSubmitted) {
            formSubmitted = true; // Set the flag
            $submitBtn.prop('disabled', true);
            $spinner.removeClass('d-none');

            var form_data = $form.serialize();

            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'dspp_save_billing_details_ajax',
                    nonce: nonce,
                    data: form_data
                },
                success: function (response) {
                    if (response.status) {
                        var url = dspp_nonces.site_url + "/bits-payment?invoice_id=" + invoiceId + "&billing_id=" + response.billing_id;
                        window.location.href = url;
                    } else {
                        alert(response.message || 'An error occurred');
                        $submitBtn.prop('disabled', false);
                        $spinner.addClass('d-none');
                        formSubmitted = false;
                    }
                },
                error: function (errorThrown) {
                    console.log('Error:', errorThrown);
                    $submitBtn.prop('disabled', false);
                    $spinner.addClass('d-none');
                    formSubmitted = false;
                }
            });
        }
    });
    $('#purchaseButton').on('click', function (e) {
        e.preventDefault();

        var $btn = $(this);
        $btn.addClass('disabled'); // disable button
        $btn.find('.spinner-border').removeClass('d-none'); // show spinner
        jQuery('.btn_remove').prop('disabled', true);
        jQuery('#check_coupon_button').prop('disabled', true);
        var nonce = dspp_nonces.dspp_bits_generate_invoice;
        var ajaxUrl = dspp_nonces.ajax_url;
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_bits_generate_invoice',
                nonce: nonce
            },
            success: function (response) {
                console.log(response);
                if (response.success) {
                    $btn.removeClass('disabled');
                    jQuery('.btn_remove').prop('disabled', false);
                    jQuery('#check_coupon_button').prop('disabled', false);
                    $btn.find('.spinner-border').addClass('d-none');
                    window.location.href = dspp_nonces.site_url + "/bits-checkout?invoice_id=" + response.invoice_id;
                } else {
                    alert(response.message);
                    // revert button state if failed
                    $btn.removeClass('disabled');
                    jQuery('.btn_remove').prop('disabled', false);
                    jQuery('#check_coupon_button').prop('disabled', false);
                    $btn.find('.spinner-border').addClass('d-none');
                }
            },
            error: function (errorThrown) {
                console.log('Error:', errorThrown);
                // revert button state on error
                $btn.removeClass('disabled');
                jQuery('.btn_remove').prop('disabled', false);
                jQuery('.a_checkout').removeClass('disabled');
                $btn.find('.spinner-border').addClass('d-none');
            }
        });
    });
    $('#ajax-login-form').on('submit', function (e) {
        var nonce = dspp_nonces.dspp_ajax_user_login;
        var ajaxUrl = dspp_nonces.ajax_url;
        e.preventDefault();
        var loginData = {
            'action': 'dspp_ajax_user_login',
            'username': $('#username').val(),
            'password': $('#password').val(),
            'nonce': nonce
        };
        $.ajax({
            type: 'POST',
            url: ajaxUrl,
            data: loginData,
            success: function (response) {
                var parsed = JSON.parse(response);
                if (parsed.status == "error") {
                    $(".login-message").html(parsed.message);
                } else {
                    window.location.href = parsed.redirect;
                }
            }
        });
        return false;
    });
    $('#complete_purchase_with_token_email').on('submit', function (e) {
        e.preventDefault(); // Prevent the form from submitting the default way
        var nonce = dspp_nonces.complete_purchase_with_token_email;
        var ajaxUrl = dspp_nonces.ajax_url;
        var form = $(this);
        var formData = form.serialize(); // Serialize the form data to be sent in the AJAX request
        var data = {
            action: 'dspp_complete_purchase_with_token_email',
            nonce: nonce,
            formData: formData
        };
        $.ajax({
            url: ajaxUrl, // Localized AJAX URL
            type: 'POST',
            data: data, // Append the action parameter for WordPress
            success: function (response) {
                console.log(response);
                if (response.success) {
                    location.reload();
                } else {
                    alert('We are unable to complete your purchase right now. Please try again later.');
                }
            },
            error: function () {
                alert('An error occurred. Please try again.');
            }
        });
    });
    $('#complete_purchase_with_token').on('submit', function (e) {
        e.preventDefault(); // Prevent the form from submitting the default way
        var nonce = dspp_nonces.complete_purchase_with_token;
        var ajaxUrl = dspp_nonces.ajax_url;
        // Get the form data
        var form = $(this);
        var formData = form.serialize(); // Serialize the form data to be sent in the AJAX request
        var data = {
            action: 'dspp_complete_purchase_with_token',
            nonce: nonce,
            formData: formData
        };
        // Send AJAX request
        $.ajax({
            url: ajaxUrl, // Localized AJAX URL
            type: 'POST',
            data: data, // Append the action parameter for WordPress
            success: function (response) {
                if (response.success) {
                    window.location.href = response.url; // Redirect to the success page
                } else {
                    alert('We are unable to complete your purchase right now. Please try again later.');
                }
                console.log(response);
            },
            error: function () {
                alert('An error occurred. Please try again.');
            }
        });
    });
    $('.btn_payment_confirmed').on('click', function (e) {
        e.preventDefault();
        var button = $(this);
        var nonce = button.data('nonce'); // Assumed you have already localized a nonce
        var invoice_id = button.data('invoice_id'); // Get the invoice ID from button data attribute
        var user_id = button.data('user_id'); // Get the user ID from button data attribute
        var billing_id = button.data('billing_id'); // Get the user ID from button data attribute
        console.log(nonce);
        // Prepare the data for the AJAX request
        var data = {
            action: 'dspp_payment_confirmed_with_token',
            nonce: nonce,
            invoice_id: invoice_id,
            user_id: user_id,
            billing_id: billing_id
        };
        $.ajax({
            url: dspp_nonces.ajax_url, // Your localized AJAX URL
            type: 'POST',
            data: data,
            success: function (response) {
                if (response.success) {
                    location.href = response.url;
                } else {
                    alert('We are unable to process your order right now! Please try again later.');
                }
                console.log(response);
            },
            error: function () {
                alert('An error occurred. Please try again.');
            }
        });
    });
});

function dspp_updateQuantity(e) {
    var value = e.value;
    if (value <= 0) {
        remove_row(e);
        return;
    }
    var product_id = parseInt(e.getAttribute('data-product-id'));
    var userId = parseInt(e.getAttribute('data-user-id'));
    var site = e.getAttribute('data-site');
    var price = parseFloat(e.getAttribute('data-price'));
    var variation_id = parseInt(e.getAttribute('data-variation_id'));
    var nonce = dspp_nonces.update_quantity_in_session;
    var ajaxUrl = dspp_nonces.ajax_url;
    jQuery.ajax({
        url: ajaxUrl,
        type: 'POST',
        data: {
            action: 'dspp_update_quantity_in_session',
            nonce: nonce,
            site: site,
            price: price,
            user_id: userId,
            post_id: product_id,
            variation_id: variation_id,
            value: value
        },
        success: function (response) {
            var parsed = JSON.parse(response);
            if (parsed.status) {
                location.reload();
            }
        },
        error: function (errorThrown) {
            console.log('Error:', errorThrown);
        }
    });
}
function remove_row(e) {
    var row = e.closest('tr');
    var userId = e.getAttribute('data-user-id');
    var site_url = e.getAttribute('data-site');
    var price = e.getAttribute('data-price');
    var variation_id = parseInt(e.getAttribute('data-variation_id'));
    var totalInvoiceElement = document.getElementById('total-invoice');
    var currentPriceText = totalInvoiceElement.textContent;
    var currentPriceSplitted = currentPriceText.split('$');
    var currentPrice = parseInt(currentPriceSplitted[1]);
    var nonce = dspp_nonces.remove_from_session;
    var ajaxUrl = dspp_nonces.ajax_url;
    var newPrice = currentPrice - price;

    // 👇 Disable all remove buttons
    jQuery('.btn_remove').prop('disabled', true);
    jQuery('#check_coupon_button').prop('disabled', true);
    jQuery('.a_checkout').addClass('disabled');

//    document.querySelectorAll('#check_coupon_button, #purchaseButton').forEach(btn => btn.disabled = true);

    // 👇 Show spinner, hide icon
    var $button = jQuery(e);
    $button.find('.fa-trash').addClass('d-none');
    $button.find('.spinner-border').removeClass('d-none');

    jQuery.ajax({
        url: ajaxUrl,
        type: 'POST',
        data: {
            action: 'dspp_remove_from_session',
            nonce: nonce,
            website_url: site_url,
            variation_id: variation_id,
            user_id: userId
        },
        success: function (response) {
            var parsed = JSON.parse(response);
            if (parsed.status) {
                location.reload();
            }
        },
        error: function (errorThrown) {
            console.log('Error:', errorThrown);

            // 👇 Revert UI on error
            jQuery('.btn_remove').prop('disabled', false);
            jQuery('#check_coupon_button').prop('disabled', false);
            jQuery('.a_checkout').removeClass('disabled');
            $button.find('.fa-trash').removeClass('d-none');
            $button.find('.spinner-border').addClass('d-none');
        }
    });
}