// source --> https://deskartable.cl/wp-content/plugins/addify-product-dynamic-pricing-and-discounts/front/../includes/js/addf-drpc-front.js?ver=1.0.0 
jQuery(document).ready( function($){  
    

	$(document).on('show_variation' , 'form.variations_form' , function(event, data){
		var variation_id = data.variation_id;
		if ( $('.af_drpc_variation_table').is(':visible') ) {
			$('.af_drpc_variable_table').hide();
		} else {
			$('.af_drpc_variable_table').show();
		}
	} );
});



function afpdad_block_message_function(current_quantity,current_id){
    jQuery.ajax({
        url: addf_drpc_php_vars.admin_url,
        type: 'POST',
        data: {
            action: 'addf_drpc_block_quantity',
            nonce :  addf_drpc_php_vars.nonce,
            current_id: current_id,
            quantity: current_quantity
        },
        success: function (response) {  
            
            let block_messages = response.data.block_data;
            let cart_block_messages = response.data.cart_block;
            if(undefined !== block_messages || block_messages.length>=0){
                jQuery('.af-dpad-block-class').remove();
    
                // ---------------------------product rule discount
                for (const key in block_messages) {
                    if (block_messages.hasOwnProperty(key)) {
                        if(jQuery('.block-message-info-'+key).length){
                            jQuery('.block-message-info-'+key).remove();
                        }
                        jQuery('.wc-block-cart').before(
                            '<div class="af-dpad-block-class block-message-info-'+key+' wc-block-components-notice-banner is-info" role="alert"><div class="wc-block-components-notice-banner__content">'+block_messages[key]+'</div></div>');
    
                    }
                }

            }

            // ---------------------------cart rule discount

            if(undefined !== block_messages || block_messages.length>=0){
                jQuery('.af-dpad-cart-block-class').remove();
                for (const key in cart_block_messages) {
                    if (cart_block_messages.hasOwnProperty(key)) {
                        if(jQuery('.af-dpad-cart-block-class').length){
                            jQuery('.af-dpad-cart-block-class').remove();
                        }
                        jQuery('.wc-block-cart').before(
                            '<div class="af-dpad-cart-block-class block-message-info wc-block-components-notice-banner is-info" role="alert"><div class="wc-block-components-notice-banner__content">'+cart_block_messages[key]+'</div></div>');
    
                    }
                }
            }
        }
    })
}
setTimeout(() => {
    if(jQuery('.wc-block-cart').length){

        afpdad_block_message_function();
        wp.hooks.addAction('experimental__woocommerce_blocks-cart-set-item-quantity', 'af_dp_tax_price_cart_update', function(item) {
            // action_type = 'change_qty';
            current_quantity = item.quantity;
            current_id = item.product.id;      
            
            afpdad_block_message_function(current_quantity,current_id);
        
        });    
    }
    
}, 1000);

jQuery(document).ready(function ($) {
    
    //for simple product
    if(!$('.single_variation').length && !$('.product-type-grouped').length){

        if($('.addf_drpc_table_for_dynamic_pricing').length){
            var className = '';
    
            var initialPrice = $('.entry-summary .price ins .woocommerce-Price-amount bdi').text();
            
            if(initialPrice == ''){
                className = '.entry-summary .price .woocommerce-Price-amount bdi';
                initialPrice = $(className).text();
            }
            else{
                className = '.entry-summary .price ins .woocommerce-Price-amount bdi';
            }

            $('.qty').on('input change', function(){
                var newValue = parseInt($(this).val()); 
                
                $('.addf_drpc_table_for_dynamic_pricing tr').each(function() {
                    var minQuantity = parseInt($(this).find('td:nth-child(1)').text());
                    var maxQuantity = isNaN(parseInt($(this).find('td:nth-child(2)').text()))?0:parseInt($(this).find('td:nth-child(2)').text());
                    var priceText = $(this).find('td:nth-child(3)').text(); 
                    var replace_price = $(this).find('td:first').data('replace');

                    

                    if ((newValue >= minQuantity && newValue <= maxQuantity) || (newValue >= minQuantity && 0 == maxQuantity)) {
                        
                        $(className).html('<span class="woocommerce-Price-currencySymbol">' + priceText + '</span>' );
 
                        if('yes' == replace_price){    
                            $('.entry-summary .price del').hide();
                            $('.b2b-role-based-custom-price').remove();

                        }
                        //
                        if(addf_drpc_php_vars.addf_drpc_option_sale_price && addf_drpc_php_vars.addf_drpc_option_sale_price == 'sale'){
                            $('.entry-summary .price del').hide();
                            $('.b2b-role-based-custom-price').remove();
                            var delElement = '<del class="b2b-role-based-custom-price"><span class="woocommerce-Price-amount amount">' + initialPrice + '</span></del>';

                            if('yes' != replace_price){
                                $('.entry-summary .price').prepend(delElement);
                            }
                        }else{
                            if('yes' != replace_price){
                                $('.entry-summary .price del').show();
                            }
                        }
                        
                        $('.elementor-widget-woocommerce-product-price .price del').hide();



                        //



                        // if('yes' == replace_price){
                            
                        //     $('.entry-summary .price del').hide();
                        // }
                        // else{
                        //     $('.entry-summary .price del').hide();
                        //     $('.b2b-role-based-custom-price').remove();
                        //     var delElement = '<del class="b2b-role-based-custom-price"><span class="woocommerce-Price-amount amount">' + initialPrice + '</span></del>';
                        //     $('.entry-summary .price').prepend(delElement);
                        // }
                        // return false; 
                    }
                });

                if (!$('.addf_drpc_table_for_dynamic_pricing tr').is(function() {
                    var replace_price = $(this).find('td:first').data('replace');
                    return (newValue >= parseInt($(this).find('td:nth-child(1)').text()) && newValue <= parseInt($(this).find('td:nth-child(2)').text()) || (newValue >= parseInt($(this).find('td:nth-child(1)').text()) && (0 == parseInt($(this).find('td:nth-child(2)').text()) || isNaN(parseInt($(this).find('td:nth-child(2)').text())))));
                })) {
                    $('.addf_drpc_list_box').each(function(){
                            $(this).removeClass('addf_drpc_selected_list')
                        })
                        $('[name=offer]').each(function(){
                            $(this).prop('checked', false);
                        })
                        $('.addf_drpc_inner_small_box').each(function(){
                            $(this).removeClass('addf_drpc_selected_card');
                        })
                    $('.entry-summary .price del').show();
                    $(className).text(initialPrice);
                    $('.b2b-role-based-custom-price').remove();
                }
            });

            $('.qty').trigger('change');
        }
    }


    $('.variations select').on('change', function() {
   
        setTimeout(function(){
            // $('.addf_drpc_radio_div').append('<input type="radio" name="offer" />');

            // if($('.addf_drpc_table_for_dynamic_pricing').length){

                $('.addf_drpc_radio_div').each(function() {
                    if ($(this).find('input[type="radio"][name="offer"]').length === 0) {
                        $('.addf_drpc_radio_div').append('<input type="radio" name="offer" />');
                    }
                });
    
                var variation_id = $('.variation_id').val();
                if(variation_id != '' && variation_id != '0' ){
    
                    $.ajax({
                        url: addf_drpc_php_vars.admin_url,
                        type: 'POST',
                        data: {
                            action: 'addf_drpc_get_variation_price',
                            nonce :  addf_drpc_php_vars.nonce,
                            variation_id:variation_id
                        },
                        success: function (response) {
                            // var original_price = response.data.price;
                            var original_price_formatted = response.data.price;
                            var regular_price = response.data.regular_price;
                            
                            //changing price on quantity change for variable price
                             if($('.single_variation').length){
                                var className = '';
                            
                                var initialPrice = $('.single_variation .price ins .woocommerce-Price-amount bdi').text();
                                
                                if(initialPrice == ''){
                                    className = '.single_variation .price .woocommerce-Price-amount bdi';
                                }
                                else{
                                    className = '.single_variation .price ins .woocommerce-Price-amount bdi';
                                }
    
                                initialPrice = original_price_formatted;
                                 
    
                                function handleQuantityChange(newValue, className) {
    
                                    $('.addf_drpc_table_for_dynamic_pricing tr').each(function() {
                                        var minQuantity = parseInt($(this).find('td:nth-child(1)').text());
                                        var maxQuantity = isNaN(parseInt($(this).find('td:nth-child(2)').text()))?0:parseInt($(this).find('td:nth-child(2)').text());
                                        var priceText = $(this).find('td:nth-child(3)').text(); 
                                        var replace_price = $(this).find('td:first').data('replace');
                                        
                                        if ((newValue >= minQuantity && newValue <= maxQuantity) || (newValue >= minQuantity && 0 == maxQuantity)) {
                                            $(className).html('<span class="woocommerce-Price-currencySymbol">' + priceText + '</span>');
  
                                            
                                            if('yes' == replace_price){
                                                
                                                $('.entry-summary .price del').hide();
                                                $('.b2b-role-based-custom-price').remove();

                                            }
                                            // else{
                                            //     $('.entry-summary .single_variation_wrap .price del').hide();
                                            //     $('.b2b-role-based-custom-price').remove();
                                            //     var delElement = '<del class="b2b-role-based-custom-price"><span class="woocommerce-Price-amount amount">' + initialPrice + '</span></del>';
                                            //     $('.entry-summary .single_variation_wrap .price').prepend(delElement);
                                            // }
                                            // return false; 
                                            // old in if discount_applied_on
                                            if(addf_drpc_php_vars.addf_drpc_option_sale_price && addf_drpc_php_vars.addf_drpc_option_sale_price == 'sale'){

                                                $('.entry-summary .price del').hide();
                                                $('.b2b-role-based-custom-price').remove();
                                                var delElement = '<del class="b2b-role-based-custom-price"><span class="woocommerce-Price-amount amount">' + initialPrice + '</span></del>';

                                                if('yes' != replace_price){
                                                    $('.entry-summary .price').prepend(delElement);
                                                }
                                            }else{
                                                
                                                if('yes' != replace_price){
                                                    $('.entry-summary .price del').show();
                                                }
                                            }
                                            
                                            $('.elementor-widget-woocommerce-product-price .price del').hide();
                                        }
                                    });
    
                                    if (!$('.addf_drpc_table_for_dynamic_pricing tr').is(function() {

                                        return (newValue >= parseInt($(this).find('td:nth-child(1)').text()) && newValue <= parseInt($(this).find('td:nth-child(2)').text()) || (newValue >= parseInt($(this).find('td:nth-child(1)').text()) && (0 == parseInt($(this).find('td:nth-child(2)').text()) || isNaN(parseInt($(this).find('td:nth-child(2)').text())))));
                                    })) {
                                        $('.addf_drpc_list_box').each(function(){
                                            $(this).removeClass('addf_drpc_selected_list')
                                        })
                                        $('[name=offer]').each(function(){
                                            $(this).prop('checked', false);
                                        })
                                        $('.addf_drpc_inner_small_box').each(function(){
                                            $(this).removeClass('addf_drpc_selected_card');
                                        })
                                        $('.entry-summary .single_variation_wrap .price del').show();
                                        $(className).text(initialPrice);
                                        $('.b2b-role-based-custom-price').remove();

                                        
                                        if('' != response.data.regular_price){
                                            $('.entry-summary .single_variation_wrap .price del').text(regular_price);
                                        }

                                    }
                                }
    
                                $(document).ready(function() {
                                    var initialValue = parseInt($('.qty').val()); 
                                    handleQuantityChange(initialValue, className); 
                                });
    
                                $(document).on('input change','.qty', function() { 
                                    var newValue = parseInt($(this).val()); 
                                    handleQuantityChange(newValue, className); 
                                });
                            }
                        }
                    });
                }
            // }

            

        }, 10);
        
    });

    setTimeout(function(){
        $('.variations select').trigger('change');
        },10);

    //card click logic
    $(document).on('click' ,'.addf_drpc_inner_small_box',function(){
        var min_qty = $(this).data('min-qty');
        if(min_qty>0){
            $('.qty').val(min_qty).trigger('change');
            $('.addf_drpc_inner_small_box').each(function(){
                $(this).removeClass('addf_drpc_selected_card');
            })
            $(this).addClass('addf_drpc_selected_card')
        }
    })



    $('.addf_drpc_radio_div').append('<input type="radio" name="offer" />');

   $(document).on('click','.addf_drpc_list_box',function(){
        var min_qty = $(this).data('min-qty');

         $(this).find('input[type="radio"]').prop('checked', true);
         $('.qty').val(min_qty).trigger('change');

         $('.addf_drpc_list_box').each(function(){
            $(this).removeClass('addf_drpc_selected_list');
        })
        $(this).addClass('addf_drpc_selected_list')

   })

   




   
});