
let myChart;
let root = null;
jQuery(document).ready(function($) {
	jQuery(".elex_simple_select").select2({
		minimumResultsForSearch: -1,
		// allowClear: true
       });
	   jQuery(".elex_simple_select_filter").select2({
		minimumResultsForSearch: -1,
       });
	
	"use strict";

	get_map_vendor_dashboard_details();
	// Handling uploading of the logo on shipment label printing settings form.
	// Adapted from Mike Jolley
	// http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/
	var file_frame;

	
   
	$('#elex_multivendor_new_product_img_label').click(function( event ){

		event.preventDefault();
		// If the media frame already exists, reopen it.
		if ( file_frame ) {
			file_frame.open();
			return;
		}
		// Create the media frame.
		file_frame = wp.media.frames.file_frame = wp.media({
			title: jQuery( this ).data( 'uploader_title' ),
			button: {
				text: jQuery( this ).data( 'uploader_button_text' ),
			},
			// Set to true to allow multiple files to be selected
			multiple: false
		});
		// When an image is selected, run a callback.
		file_frame.on( 'select', function() {
			// We set multiple to false so only get one image from the uploader
			var attachment = file_frame.state().get('selection').first().toJSON();
			// Send the value of attachment.url back to shipment label printing settings form
			jQuery('#elex_multivendor_new_product_img').val(attachment.url);
		});

		// Finally, open the modal
		file_frame.open();
	});
	elex_mv_chart_callback();
	elex_mv_map_chart_callback();
	jQuery("#elex_mv_sales_chart_product").on('change',function(){  
		    myChart.destroy();
		  	elex_mv_chart_callback();
	});
	jQuery("#elex_mv_country_days_data").on('change',function(){
		if ( root ) {
			root.remove();
			root = null;
		}
		elex_mv_map_chart_callback();
    });
	function elex_mv_map_chart_callback(){
		var days = jQuery("#elex_mv_country_days_data").val();
		var store_id = jQuery("#elex_mv_country_days_data*").attr("data-attr-store-id");

		jQuery.ajax({
			url: elex_mv_vendor_dashboard_params.ajax_url,
			type: 'POST',
			data: {
				action: "elex_mv_country_data",
				_ajax_nonce: elex_mv_vendor_dashboard_params.nonce,
				store_id : store_id,
				days: days,
	
			},
			success: function (result) {
				var data = result.data;
				if ( document.getElementById( 'chartdiv' ) ) {
					map_chart_dashboard( data );
				}
			}
		});
	}
});

	function get_map_vendor_dashboard_details(){
		var link_dash = elex_mv_vendor_dashboard_params.ajax_url;

		link_dash += "?action=elex_mv_vendor_dashboard_page";
		jQuery.ajax({
			url: link_dash,
			type: 'POST',
			// processData: false,
			// contentType: false,
			data: {
				_ajax_nonce: elex_mv_vendor_dashboard_params.nonce,
			},
			success: function (result) {
						
				var data = result.data;
				map_vendor_dashboard_details( data );
			}
		});
	}

	function map_vendor_dashboard_details(data){
		jQuery("#vendor_total_vendor_sales").html(data['total_vendor_sales']);
		jQuery("#vendor_total_commission").html(data['commission_amount']);
		jQuery("#vendor_total_refund_amount").html(data['elex_mv_refund_amount']);
		jQuery("#vendor_total_shipping_cost").html(data['total_shipping_amount']);
		jQuery("#vendor_total_shipping_refunded_cost").html(data['total_shipping_refund_amount']);

		jQuery("#vendor_total_earning_after_refund").html(data['total_vendor_earnings']);
		jQuery("#vendor_total_orders").text(data['total_orders']);
		jQuery("#vendor_total_on_hold_orders b").text(data['total_on_hold_orders']);
		jQuery("#vendor_total_completed_orders b").text(data['total_completed_orders']);
		jQuery("#vendor_total_cancelled_orders b").text(data['total_cancelled_orders']);
		jQuery("#vendor_total_pending_orders b").text(data['total_pending_orders']);
		jQuery("#vendor_total_processing_orders b").text(data['total_processing_orders']);
		jQuery("#vendor_total_refunded_orders b").text(data['total_refunded_orders']);
		jQuery("#vendor_total_products").text(data['products']);
		jQuery("#vendor_total_approved_products b").text(data['count_published_product']);
		jQuery("#vendor_total_pending_products b").text(data['count_pending_product']);
		jQuery("#vendor_total_rejected_products b").text(data['count_rejected_product']);

	}

	function get_colour( country ){
		
			// var hash = 0;
			// for (var i = 0; i < country.length; i++) {
			// hash = country.charCodeAt(i) + ((hash << 5) - hash);
			// }
			// var colour = '#';
			//var letters = "0123456789ABCDEF";
			// for (var i = 0; i < 3; i++) {
			// 	var value = (hash >> (i * 8)) & 0xFF;
			// 	colour += value.toString(16).padStart(2, "0");
			// }
			// return colour;
			var hash = 0;
			for(var i=0; i < country.length; i++) {
				hash = country.charCodeAt(i) + ((hash << 3) - hash);
			}
			var color = Math.abs(hash).toString(16).substring(0, 6);

			return "#" + '000000'.substring(0, 6 - color.length) + color;
		
	}
 function elex_mv_chart_callback(){
	var id = jQuery("#elex_mv_sales_chart_product").val();
	var store_id = jQuery("#elex_mv_sales_chart_product").attr("data-attr-store-id");
	var labels = "";
	jQuery.ajax({
        url: elex_mv_vendor_dashboard_params.ajax_url,
        type: 'POST',
        data: {
            action: "elex_mv_product_data_last_seven_days",
            _ajax_nonce: elex_mv_vendor_dashboard_params.nonce,
            product_id: id,
			store_id : store_id,
			days: 7,
			type :'',

        },
        success: function (result) {
		 var resu= JSON.parse(result.data)
		
		 total_vendor_earning= [];
		 order_date = [];
		 total_sales_product = [];
		 resu.forEach(function(curr, index, arr){
			total_vendor_earning.push(curr['total_vendor_earning']);
			order_date.push(curr['order_date']);
			total_sales_product.push(curr['total_sales_product']);

		 })
		 var label = total_vendor_earning;
		 var date = order_date;
		 var qty = total_sales_product;
		 dashboard_chart(label,date,qty);
		
    	}
	});
 }
function dashboard_chart(label,date,qty){
	
	const data = {
		options: {
			responsive: true,
			maintainAspectRatio: false,
		},
		labels: date,
		datasets: [{
			barThickness: 20,
			label: 'Earnings',
			fill: '+1',
			data: label,
			backgroundColor: [
				'#3F5980',
			],
			borderColor: [
				'rgba(15, 177, 155, 0)',
			],
			backgroundShadowColor: 'black',
			shadowBlur: 3,
			shadowOffsetX: 3,
			shadowOffsetY: 10,
			borderWidth: 0,
			borderRadius: 5,
		}, {
			barThickness: 20,
			label: 'Sales',
			data:  qty,
			backgroundColor: [
				'#E6EDF8',
			],
			borderColor: [
				'rgba(255, 26, 104, 0)',
			],
			borderWidth: 0,
			borderRadius: 5,
		}]
	};

	// config 
	const config = {
		type: 'bar',
		data,
		options: {
			plugins: {
				legend:{
					position: 'bottom',
					
					labels:{
					boxWidth: 20,
					boxHeight: 20,
					padding: 20,
					usePointStyle: true,
					pointStyle: 'circle'
					}
				},
				tooltip: {
					yAlign: 'bottom',
					enabled: true,
					backgroundColor: 'grey',
					borderColor: 'rgba(0,0,0,0.2)',
					borderWidth: 2,
					titleColor: 'black',
				}
			},
			interaction: {
				intersect: false,
				mode: 'index',
			},

			maintainAspectRatio: false,
			scales: {
				x: {

					stacked: true,
					grid: {
						display: false
					}
				},
				y: {

					display: false,
					beginAtZero: true,
					grid: {
						drawBorder: false,
						display: false,
					}
				}

			}
		}
	};
	
	// // render init block
	 myChart = new Chart(
		document.getElementById('myChart'), 
		config 
	);
	
		
}

function map_chart_dashboard( data_chart ){
	if ( root ) {
		root.remove();
		root = null;
	}

	root = L.map( 'chartdiv', {
		center: [20, 0],
		zoom: 2,
		scrollWheelZoom: false
	} );

	L.tileLayer( 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
		attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
		subdomains: 'abcd',
		maxZoom: 19
	} ).addTo( root );

	var maxValue = 0;
	data_chart.forEach( function( item ) {
		if ( item.value > maxValue ) {
			maxValue = item.value;
		}
	} );

	data_chart.forEach( function( item ) {
		var coords = elexMvCountryCentroids[ item.id ];
		if ( ! coords ) {
			return;
		}
		var radius = maxValue > 0 ? ( 4 + ( item.value / maxValue ) * 18 ) : 5;
		var color  = get_colour( item.id );

		L.circleMarker( coords, {
			radius:      radius,
			fillColor:   color,
			color:       '#ffffff',
			weight:      1,
			opacity:     1,
			fillOpacity: 0.8
		} ).bindTooltip( item.name + ': ' + item.value ).addTo( root );
	} );
}

