// source --> https://www.bbies.fr/wp-content/plugins/woo-discount-rules-pro/assets/Store/Js/wdr-store.js?ver=3.0.0-RC1 
jQuery(function ($) {

    // assign get price html method
    wdr_store.get_price_html = function (product_id, quantity = 1, custom_price = null) {
        let html = false;
        $.ajax({
            url: wdr_store.ajax_url,
            type: 'POST',
            async: false,
            data: {
                action: 'wdr_get_price_html',
                product_id: product_id,
                quantity: quantity,
                custom_price: custom_price,
                nonce: wdr_store.nonce,
            },
            success: function (response) {
                if (response.success && response.data.html) {
                    html = response.data.html;
                }
            },
        });
        return html;
    };

    // trigger checkout refresh order review
    if (wdr_store.trigger_refresh_order_review) {
        // trigger when payment method, billing email or billing postcode changed
        $(document).on('change', 'input[name="payment_method"], input[name="billing_city"], input[name="billing_postcode"]', function () {
            $('body').trigger('update_checkout');
        });

        // trigger when billing email or billing state blurred
        $(document).on('blur', 'input[name="billing_email"], select#billing_state', function () {
            $('body').trigger('update_checkout');
        });
    }

    // dynamic price html (based on quantity)
    if (wdr_store.dynamic_price_html_enabled) {
        $(document).on('change', '[name="quantity"]', function () {
            let form = $(this).closest('form');
            let quantity = $(this).val();
            if (form.length > 0) {
                if (form.find(wdr_store.variable_product_id_selector).length > 0) {
                    let target = $(wdr_store.variable_product_price_target).first();
                    let product_id = form.find(wdr_store.variable_product_id_selector).first().val();
                    if (target.length > 0 && product_id) {
                        let price_html = wdr_store.get_price_html(product_id, quantity);
                        if (price_html) target.html(price_html);
                    }
                } else if (form.find(wdr_store.simple_product_id_selector).length > 0) {
                    let target = $(wdr_store.simple_product_price_target).first();
                    let product_id = form.find(wdr_store.simple_product_id_selector).first().val();
                    if (target.length > 0 && product_id) {
                        let price_html = wdr_store.get_price_html(product_id, quantity);
                        if (price_html) target.html(price_html);
                    }
                }
            }
        });
    }

    if (wdr_store.awdr_dynamic_bulk_table_status == "1" && wdr_store.awdr_dynamic_bulk_table_off == "on") {

        jQuery(".single_variation_wrap").on("hide_variation", function (event) {
            let variation_id = jQuery(this).closest('form').find('input[name="product_id"]').val();
            awdr_load_variation_table(variation_id);
        });

        jQuery(".single_variation_wrap").on("show_variation", function (event, variation, purchasable) {
            let variation_id = variation.variation_id;
            if (variation.is_bundled != undefined) {
                if (variation.is_bundled == true) {
                    return;
                }
            }
            awdr_load_variation_table(variation_id);
        });
    }

    jQuery(document).on('blur', '#billing_email', "", function ($) {
        refreshCart();
    });

    function refreshCart() {
        jQuery('#billing_country').trigger('change');
    }

    $(document).on("click", '.wdr-cart-item-variant-select-toggle', function () {
        $(this).toggleClass('wdr-cart-item-variant-select-toggle-active');
        if ($(this).hasClass('wdr-cart-item-variant-select-toggle-active')) {
            $(this).next().slideDown(1000);
        } else {
            $(this).next().slideUp(1000);
        }
    });

    $(document).on("click", ".wdr-cart-item-variant-select .wdr-cart-item-variant", function () {
        let variation_id = $(this).data('variation_id');
        let cart_item_key = $(this).closest('.wdr-cart-item-variant-select').data('cart_item_key');
        $.ajax({
            url: wdr_store.ajax_url,
            data: {
                action: 'wdr_ajax_change_cart_item_variant',
                cart_item_key: cart_item_key,
                variation_id: variation_id,
                awdr_nonce: wdr_store.nonce,
            },
            type: 'POST',
            success: function (response) {
                if (response.success && response.data) {
                    jQuery("[name='update_cart']").removeAttr('disabled');
                    jQuery("[name='update_cart']").trigger("click");
                }
            },
            error: function (response) {
            }
        });
    });

    if ($(".wdr-gifts-notice-container").length > 0) {
        updateGiftSection();
    }

    $(document.body).on('click', '#wdr-load-more-gift', function () {
        let products = $(this).closest('.wdr-modal').find('.wdr-products');
        let page_no =  parseInt(products.data('page_no')) + 1;
        products.data('page_no', page_no);
        updateGiftSection();
    });

    let enable_fragments_refreshed = true;
    jQuery(document.body).on('updated_cart_totals', function () {
        updateGiftSection();
        enable_fragments_refreshed = false;
    });

    $(document.body).on('updated_checkout', function () {
        updateGiftSection();
        enable_fragments_refreshed = false;
    });

    jQuery(document.body).on('wc_fragments_refreshed', function () {
        if (enable_fragments_refreshed) {
            updateGiftSection();
        }
    });

    jQuery(document.body).on('wc_fragment_refreshed', function () {
        updateGiftSection();
    });

    $(document.body).on('click', '.wdr-choose-gift', function () {
        $('.wdr-gifts-modal-container .wdr-modal').show();
    });

    $(document.body).on('click', '.wdr-modal-close', function () {
        $(this).closest('.wdr-modal').hide();
    });

    $(document.body).on('click', '.wdr-products .wdr-atc-button', function () {
        let modal = $(this).closest('.wdr-modal');
        let products = $(this).closest('.wdr-products');
        let button = $(this);
        let model_title = $(this).closest('.wdr-modal').find('.wdr-choose-products-title');
        let page_no = $(this).closest('.wdr-products').data('page_no');
        $.ajax({
            url: wdr_store.ajax_url,
            data: {
                action: 'wdr_ajax_add_gift_product',
                product_id: button.val(),
                uid: button.data('uid'),
                rule_id: button.data('rule_id'),
                gift_type: button.data('gift_type'),
                page_no: page_no,
                ref_item_key: button.data('ref_item_key') || '',
                nonce: wdr_store.nonce,
            },
            type: 'POST',
            beforeSend: function () {
                if (jQuery(".wdr-gifts-modal-container .wdr-modal-content").block) {
                    jQuery(".wdr-gifts-modal-container .wdr-modal-content").block({
                        message: null,
                        overlayCSS: {background: '#fff', opacity: 0.6}
                    });
                }
            },
            success: function (response) {
                if (response.data && response.data.item_added) {
                    jQuery(".wdr-gifts-notice-container").html(response.data.notice);
                    jQuery(".wdr-gifts-modal-container .wdr-modal-body").html(response.data.product_html);
                    let qty = response.data.remaining_quantity;
                    if (qty <= 0 || qty === undefined) {
                        modal.hide();
                    } else {
                        products.data('choose_products_quantity', qty);
                        model_title.html(response.data.modal_header);
                    }
                    jQuery(document.body).trigger('wc_fragment_refresh');
                    jQuery(document.body).trigger('wc_update_cart');
                    jQuery(document.body).trigger('update_checkout');
                }
            },
            complete: function () {
                if (jQuery(".wdr-gifts-modal-container .wdr-modal-content").block) {
                    jQuery(".wdr-gifts-modal-container .wdr-modal-content").unblock();
                }
            },
        });
    });

});

function updateGiftSection() {
    jQuery.ajax({
        url: wdr_store.ajax_url,
        data: {
            action: 'wdr_ajax_gift_details',
            page_no: jQuery(document.body).find('.wdr-products').first().data('page_no'),
            nonce: wdr_store.nonce,
        },
        type: 'POST',
        success: function (response) {
            if (response.data && response.data.notice) {
                let qty = response.data.remaining_quantity;
                jQuery(".wdr-gifts-notice-container").html(response.data.notice);
                if (jQuery(".wdr-gifts-modal-container").children().length === 0) {
                    jQuery(".wdr-gifts-modal-container").html(response.data.modal);
                } else {
                    jQuery('.wdr-products').data('choose_products_quantity', qty);
                    jQuery('.wdr-choose-products-title').html(response.data.modal_header);
                    jQuery(".wdr-gifts-modal-container .wdr-modal-body").html(response.data.product_html);
                }
            } else {
                jQuery(".wdr-gifts-notice-container, .wdr-gifts-modal-container").html('');
            }
        },
    });
}

function awdr_load_variation_table(variation_id) {
    setTimeout(function () {
        if (variation_id == '' || variation_id == '0') {
            return;
        }

        var data = {
            action: 'wdr_ajax_get_variable_product_discount_table',
            product_id: variation_id,
            awdr_nonce: wdr_store.nonce,
        };

        let awdr_opacity = 'div.awdr-bulk-customizable-table';

        if (wdr_store.awdr_opacity_to_bulk_table != undefined) {
            if (wdr_store.awdr_opacity_to_bulk_table != "") {
                awdr_opacity = wdr_store.awdr_opacity_to_bulk_table;
            }
        }


        jQuery.ajax({
            url: wdr_store.ajax_url,
            data: data,
            type: 'POST',
            beforeSend: function () {
                jQuery(awdr_opacity).css('opacity', '0.5');
            },
            complete: function () {
                jQuery(awdr_opacity).css('opacity', '1');
            },
            success: function (response) {
                if (response.discount_table) {
                    jQuery('.awdr-bulk-customizable-table').html(response.discount_table);
                }
            },
            error: function (response) {
                jQuery('.awdr-bulk-customizable-table').html("")
            }
        });

    }, 100);
};