// JavaScript Document
jQuery(document).ready(function($){
	
	

	function parse_query_string(query) {
	  var vars = query.split("&");
	  var query_string = {};
	  for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		// If first entry with this name
		if (typeof query_string[pair[0]] === "undefined") {
		  query_string[pair[0]] = decodeURIComponent(pair[1]);
		  // If second entry with this name
		} else if (typeof query_string[pair[0]] === "string") {
		  var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
		  query_string[pair[0]] = arr;
		  // If third or later entry with this name
		} else {
		  query_string[pair[0]].push(decodeURIComponent(pair[1]));
		}
	  }
	  return query_string;
	}	
	var query = window.location.search.substring(1);
	var qs = parse_query_string(query);		
	
	if(typeof(qs.t)!='undefined'){
		$('.woie-wrapper a.nav-tab').eq(qs.t).click();
		
	}
	
	$('.woie-wrapper a.nav-tab').click(function(){

		$(this).siblings().removeClass('nav-tab-active');
		$(this).addClass('nav-tab-active');
		$('.nav-tab-content').hide();
		$('.nav-tab-content').eq($(this).index()).show();
		window.history.replaceState('', '', woie_object.this_url+'&t='+$(this).index());
		woie_object.woie_tab = $(this).index();

	});
	
	if(woie_object.is_orders_list && (Object.values(woie_object.export_buttons.button_display).indexOf('orders_list') > -1)){
		var export_btn = '<a href="'+woie_object.export_buttons.action_url+'" class="page-title-action woie-export-orders" target="_blank" title="'+woie_object.export_buttons.button_title+'">'+woie_object.export_buttons.button_text_multiple+'</a>';
		$(export_btn).insertAfter($('body.post-type-shop_order a.page-title-action').last());		
	}
	
	if(woie_object.is_edit_order && (Object.values(woie_object.export_buttons.button_display).indexOf('edit_order') > -1)){
		var export_btn = '<a href="'+woie_object.export_buttons.action_url+'" class="page-title-action woie-export-order" target="_blank" title="'+woie_object.export_buttons.button_title+'">'+woie_object.export_buttons.button_text_single+'</a>';
		$(export_btn).insertAfter($('body.post-type-shop_order a.page-title-action').last());		
	}
	
	$('body').on('click', 'a.page-title-action.woie-export-orders, a.page-title-action.woie-export-order', function(e){
		
		e.preventDefault();
		
		
		var order_ids = {};
		var o=0;
		$.each($('input[name="post[]"]'), function(){
			var checked = $(this).prop('checked');
			if(checked){
				
				order_ids[o] = $(this).val();
				o++;
			}
		});
		
		if(woie_object.is_edit_order && woie_object.order_id>0){
			order_ids[o] = woie_object.order_id;
		}
		
		var data = {

			action : 'woie_export_orders',
			woie_update_option_nonce : woie_object.nonce,
			woie_orders : order_ids,
			woie_export_data: true,

		}

		$.blockUI({message:''});
		$.post(ajaxurl, data, function(html, response){

			
			$.unblockUI();
			if(response == 'success'){
				html = $.parseJSON(html);
				if(typeof html.msg!='undefined'){
					
					if($('div.export_alert').length>0){ $('div.export_alert').remove(); }
						
					$('<div class="alert alert-success export_alert mb-4">'+html.msg+'</div>').insertAfter($('a.page-title-action').last()).show();
				}
			}
			
			
		});
	});
	
	$('input[name^="woie_options"], select[name^="woie_options"]').on('change', function(){
		//console.log($(this));
		//console.log($(this).parents().eq(1));
		$(this).parents().eq(1).find('ul').toggleClass('d-none');
		
		$('.woie_log ul li.selected').removeClass('selected');
		

		var woie_option_checked = $('input[name^="woie_options"][type="checkbox"]:checked');
		var woie_option_text = $('input[name^="woie_options"][type="text"]');
		var woie_option_select = $('select[name^="woie_options"]');

		var woie_options_post = {};

		if(woie_object.empty_settings){

			woie_options_post['woie_options_update'] = true;

		}

		if(woie_option_select.length > 0 ){
			$.each(woie_option_select, function () {

				woie_options_post[$(this).data('name')] = $(this).val();

			});
		}


		if(woie_option_text.length > 0 ){
			$.each(woie_option_text, function () {

				woie_options_post[$(this).data('name')] = $(this).val();

			});
		}

		if(woie_option_checked.length > 0 ){
			$.each(woie_option_checked, function () {

				woie_options_post[$(this).val()] = true;
				
				$(this).parents().eq(1).addClass('selected');

			});
		}
	


		var data = {

			action : 'woie_update_option',
			woie_update_option_nonce : woie_object.nonce,
			woie_options : woie_options_post,

		}

		$.post(ajaxurl, data, function(code, response){

			//console.log(response);

			if(response == 'success'){

				$('.woie-options .alert').removeClass('d-none').addClass('show');
				setTimeout(function(){
					$('.woie-options .alert').addClass('d-none');
				}, 10000);

			}



		});
		

	});

	if(woie_object.empty_settings){

		$('input[name^="woie_options"]').change();

	}
	
	if(typeof SlimSelect!='undefined'){
		
		var woie_export_post_type = new SlimSelect({
	
			select:'#woie_export_post_type',
			placeholder: woie_object.post_type_str,
			closeOnSelect: false,
	
	
		});
		
		if(typeof woie_object._woie_settings_obj!='undefined' && typeof woie_object._woie_settings_obj.args!='undefined'){
	
			woie_export_post_type.setSelected(woie_object._woie_settings_obj.args.post_type);
	
		}

		
		var woie_export_post_status = new SlimSelect({
	
			select:'#woie_export_post_status',
			placeholder: woie_object.post_status_str,
			closeOnSelect: false,
	
	
		});
		
		
		
		if(typeof woie_object._woie_settings_obj!='undefined' && typeof woie_object._woie_settings_obj.args!='undefined'){
			
			woie_export_post_status.setSelected(woie_object._woie_settings_obj.args.post_status);
			
		}
		
	}

	$('body').on('keydown','.woie_include_ids_select input[type="search"]', function(e){


		if(e.key == ','){

			$('body').find('.woie_include_ids_select .ss-addable').click();

		}

	});
	
	if(typeof SlimSelect!='undefined' && $('#woie_export_include_ids').length>0){
		new SlimSelect({
	
			select:'#woie_export_include_ids',
			searchPlaceholder: woie_object.comma_str,
			placeholder: woie_object.include_id_str,
			closeOnSelect: false,
			addable: function(value){
	
				value = value.trim();
				value = value.replace(',', '');
	
				if(isNaN(value)){
					return false;
				}
	
				$('body').find('.woie_include_ids_select input[type="search"]').val('');
	
				return value;
	
			}
		});
	}

	$('#woie_export_include_ids').on('change', function(){

		$('body').find('.woie_include_ids_select input[type="search"]').val('');

	});

	//Tag hack with slim select finish


	$('input[name="woie_export[export_number]"]').on('change', function(){

		if($(this).val() == 'include'){

			$('.woie_include_ids_select_wrapper').show();

		}else{

			$('.woie_include_ids_select_wrapper').hide();
		}


	});

	$('.woie_import_settings').on('change', function(){

		var this_val = $(this).val();

		if(this_val == 'file'){

			$('.woie_import_settings_file_wrapper').removeClass('hide');
			$('.woie_import_exported_string_row').addClass('hide');

		}else{

			$('.woie_import_exported_string_row').removeClass('hide');
			$('.woie_import_settings_file_wrapper').addClass('hide');

		}

	});



   function woie_get_arg_object (){

        var settings_input =  $('.export_section .woie_export_settings:not(div)');

        // console.log(settings_input);

        var settings_obj_main = {};
        var settings_obj = {};
        var export_type = 'string';
        var export_number = 'all';
        var pro = woie_object.is_pro;
        var pro_array = ['post_title', 'post_name', 'ids']

		var column_count = 0;
		var label_count = 0;

        $.each(settings_input, function(i,v){

            var this_obj = $(this);
            var is_radio = this_obj.prop('type') == 'radio';
			var is_checkbox = this_obj.prop('type') == 'checkbox';
            var this_name = this_obj.data('name');
            var this_val = this_obj.val();
			
			
			//console.log(i);
			//console.log(v);

            if(is_radio && this_obj.prop('checked')){

				export_type = this_val;


				switch (this_name){

                    case  'export_type':

                        export_type = this_val;

                        break;

					case  'export_number':

						export_type = this_val;

						break;


                }

            }else if(is_checkbox && this_obj.prop('checked')){
				
				if(typeof settings_obj[this_name]=='undefined'){ settings_obj[this_name] = []; }
				
				
				
				switch(this_name){
					
					case 'export_order_field':
					
						if(typeof settings_obj['export_order_field_label']=='undefined'){ settings_obj['export_order_field_label'] = []; }
					
						settings_obj[this_name][column_count] = this_val;
						
						var this_field = $('input[data-field="'+this_val+'"]');
						
						settings_obj['export_order_field_label'][column_count] = this_field.val();
						
						column_count++;
						
					break;
					
					default:
					
						settings_obj[this_name][i] = this_val;
					
					break;
				}
				
			
				
			}else if(!is_radio && !is_checkbox){

            	if(!pro && $.inArray(this_name, pro_array) > -1){

				}else{
				
					switch(this_name){
						case 'export_order_field_label':
							//silence
							
						break;
						default:
							settings_obj[this_name] = this_val;
						break;
					}

				}
            }


        });

        settings_obj_main.number = export_number;
        settings_obj_main.type = export_type;
        settings_obj_main.args = settings_obj;

        return settings_obj_main;

    }

    var load_modal = $('.wpie_load_modal');

    $('.export_section button.woie_export_btn').on('click', function (){

        $('.export_alert').hide();
        var settings_obj = woie_get_arg_object();
        load_modal.show();

        var data = {
            action : 'woie_export_posts_data',
            woie_settings_obj : settings_obj,
            woie_nonce : woie_object.nonce,
        }


        $.post(ajaxurl, data, function(response, code){

            load_modal.hide();

            if(code == 'success' && response.status){

                if(settings_obj.type == 'string'){
                    $('.woie_export_exported_string_row').removeClass('hide');
                    $('.woie_export_exported_string_row textarea').html(response.data);
                }else{
                    $('.woie_export_exported_string_row').addClass('hide');
					
					if($('input[name="woie_export[export_type]"]:checked').val()!='csv'){
                    	$('.export_alert').show();
					}
                    $('.export_alert a').prop('href', response.file_link);
                }
            }


        });


    });




    function woie_file_import(){

        var import_alert = $('.alert.import_alert');

        var form_object = {

            url : ajaxurl,
            beforeSubmit : function(formData, jqForm, options){




                var filename = $("input:file.woie_import_settings_file").val();

                if(filename == "") {
                   alert(woie_object.nothing_str);
                    return false;
                }else{

                    load_modal.show();

                    var fileExtension = ['txt'];



                    var extension = filename.replace(/^.*\./, '');

                    if ($.inArray(extension, fileExtension) == -1) {
                        alert(woie_object.txt_file_str);

                        return false;
                    }


                }



            },
            uploadProgress : function(event, position, total, percentComplete){},
            error : function(response, status, e){},
            complete : function(xhr){
                load_modal.hide();
                var response = xhr.responseText;
                response = JSON.parse(response);
                if(xhr.status == 200 && response.status){

                    import_alert.show();
                    import_alert.html(response.alert_string);

                }

            },
        }

        $('#woie_import_form').ajaxForm(form_object);

    }


	
	 $('.woie_filters_save_btn').on('click', function (e){
		 
		 	e.preventDefault();
		 
		 	$.blockUI({message:''});
			
			var arr = {};
			
			$.each($('input[name^="filter_meta_keys"]'), function(i,v){
				if($(this).is(':checked')){
					arr[i] = $(this).val();
				}
			});
			
			var data = {
				action : 'woie_filters_save',
				filter_meta_keys : arr,
				woie_nonce : woie_object.nonce,
			}
			
			//console.log(data);
			
			$.post(ajaxurl, data, function(response, code){
				
				$.unblockUI();
				
				if(code == 'success' && response.status){
			
			
				}
			
			
			});
	 });


    $('.import_section button.woie_import_btn').on('click', function (e){



        var import_type = $('.woie_import_settings:checked').val();
        var import_alert = $('.alert.import_alert');



        if(import_type  == 'file'){

            woie_file_import();

        }else{

            var import_string = $('#woie_import_exported_string').val();

            e.preventDefault();

            if(import_string.length < 1){
                alert(woie_object.nothing_str);

                return ;
            }




            import_alert.hide();
            load_modal.show();


            var data = {
                action : 'woie_import_posts_data',
                woie_import_string : $('#woie_import_exported_string').val(),
                woie_nonce : woie_object.nonce,
            }

            $.post(ajaxurl, data, function(response, code){

                load_modal.hide();

                if(code == 'success' && response.status){

                    import_alert.show();
                    import_alert.html(response.alert_string);

                }


            });

        }







    });
	
	function removeParam(key, sourceURL) {
		var rtn = sourceURL.split("?")[0],
			param,
			params_arr = [],
			queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
		if (queryString !== "") {
			params_arr = queryString.split("&");
			for (var i = params_arr.length - 1; i >= 0; i -= 1) {
				param = params_arr[i].split("=")[0];
				if (param === key) {
					params_arr.splice(i, 1);
				}
			}
			if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
		}
		return rtn;
	}
	
	
	if(typeof woie_object.custom_meta_vals_arr!='undefined'){
		
		var this_url = removeParam('_meta_key', woie_object.current_url);
		this_url = removeParam('_meta_value', this_url);
		this_url = removeParam('filter_action', this_url);
		var filter_str = $('#post-query-submit').val();
		
		$.each(woie_object.custom_meta_vals_arr, function(meta_key, meta_values){
			
			var li_str = '<li class="woo-ie-'+meta_key+' subsubsub-inner"> | <a>'+meta_key+'</a><ul>';
			
			
			
			$.each(meta_values, function(i, obj){
				
				li_str += '<li class="woo-ie-trigger woo-ie-'+meta_key+'"><a data-key="'+meta_key+'" data-label="'+obj.label+'" href="'+this_url+'&_meta_key='+meta_key+'&_meta_value='+obj.label+'&filter_action='+filter_str+'">'+obj.label+' <span class="count">('+obj.count+')</span></a></li>';
			
				
			});
			
			li_str += '</ul></li>';
			
			if(li_str!=''){
				$('ul.subsubsub').append(li_str);
			}
			
		});
		
		$('body').on('click', 'li.subsubsub-inner > a', function(){
			$(this).parent().find(' > ul').toggle();
		});
		
	}
	
	$('body.post-type-shop_order').on('click', 'ul.subsubsub li.woo-ie-trigger > a', function(e){
		e.preventDefault();
		
		$('.wuoc-meta-filter').find('input[name="_meta_key"]').val($(this).data('key')); 
		$('.wuoc-meta-filter').find('input[name="_meta_value"]').val($(this).data('label'));
		$('input[name="filter_action"]').click();
	});

	
});