
let adminChart;
let adminroot = null;
jQuery(document).ready(function($) {




	// 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/
	
	elex_mv_get_details_admin_dashboard();
   
	elex_mv_chart_callback();
	elex_mv_map_chart_callback();
	
	
	
});

function elex_mv_get_details_admin_dashboard(){
    jQuery.ajax({
        url: elex_mv_admin_dashboard_params.ajax_url,
        type: 'POST',
        data: {
            action: "elex_mv_admin_dashboard_page",
            _ajax_nonce: elex_mv_admin_dashboard_params.nonce,

        },
        success: function (result) {
            var data = result.data;
            map_admin_dashboard_details( data );
        }
    });
}

function map_admin_dashboard_details(data){

	jQuery("#admin-dashboard-net-sales").html(data["last_30_days_net_sales"]);
	jQuery("#admin-dashboard-order-placed").text(data["last_30days_order"]);
	jQuery("#admin-dashboard-commission-earned").html(data["last_30days_commission"]);
	jQuery("#admin-dashboard-vendor-count").text(data["vendor_count"]['last_30_days']);
	jQuery("#admin-dashboard-product-count").text(data["product_count"]['30_days']);

	jQuery("#admin-dashboard-vendor-refund").html(data['total_refund_amount']);

	jQuery("#admin-dashboard-total-orders-section").text(data['last_30days_order']);
	jQuery("#admin-dashboard-total-orders-on-hold b").text(data["status"]['on-hold']);
	jQuery("#admin-dashboard-total-orders-completed b").text(data["status"]['completed']);
	jQuery("#admin-dashboard-total-orders-cancelled b").text(data["status"]['cancelled']);
	jQuery("#admin-dashboard-total-orders-pending b").text(data["status"]['pending']);
	jQuery("#admin-dashboard-total-orders-processing b").text(data["status"]['processing']);
	jQuery("#admin-dashboard-total-orders-refunded b").text(data["status"]['refunded']);
	jQuery("#admin-dashboard-total-product-count").text(data['product_count']["30_days"]);
	jQuery("#admin-dashboard-product-status-publish b").text(data['product_status_count']['publish']);
	jQuery("#admin-dashboard-product-status-pending b").text(data['product_status_count']['pending']);
	jQuery("#admin-dashboard-product-status-rejected b").text(data['product_status_count']['reject']);
	if (data['top_vendor']['total_vendor_earning'] === undefined || data['top_vendor']['total_vendor_earning'] === null || data['top_vendor']['total_vendor_earning'] === '') {
		jQuery("#admin-dashboard-top-vendor-sales b").html('-');
	}else{	
		jQuery("#admin-dashboard-top-vendor-name").text(data['top_vendor']['display_name']);
		jQuery("#admin-dashboard-top-vendor-email small").text(data['top_vendor']['email']);
		jQuery("#admin-dashboard-top-vendor-sales b").html(  parseFloat(data['top_vendor']['total_vendor_earning']).toFixed(2) );
		jQuery("#top_vendor_image").attr( 'src', data['top_vendor']['image'] );
	}
	if( data['top_vendor']['total_admin_commission'] === undefined || data['top_vendor']['total_admin_commission'] === null || data['top_vendor']['total_admin_commission'] === '' ){
	 	jQuery("#admin-dashboard-top-vendor-commission b").html('-');
	}else{
		jQuery("#admin-dashboard-top-vendor-commission b").html(parseFloat(data['top_vendor']['total_admin_commission']).toFixed(2));
	}

	
	jQuery("#admin-dashboard-top-sold-product-name").text(data['most_sold_product']['product_name']);
	jQuery("#admin-dashboard-top-sold-product-author small").text(data['most_sold_product']['author_name']);
	if(data['most_sold_product']['unit_sold'] === undefined || data['most_sold_product']['unit_sold'] === null || data['most_sold_product']['unit_sold'] === '' ){
		jQuery("#admin-dashboard-top-sold-product-unit-sold b").text(0);
	}
	else{
		jQuery("#admin-dashboard-top-sold-product-unit-sold b").text(data['most_sold_product']['unit_sold']);
	}
	jQuery("#most_sold_product_image").html( data['most_sold_product']['image'] );

}

function elex_mv_map_chart_callback(){
    jQuery.ajax({
        url: elex_mv_admin_dashboard_params.ajax_url,
        type: 'POST',
        data: {
            action: "elex_mv_admin_country_data",
            _ajax_nonce: elex_mv_admin_dashboard_params.nonce,
            days: "-29 days",

        },
        success: function (result) {
            var data = result.data;
            map_chart_dashboard( data );
        }
    });
}
	function get_colour( country ){
			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(){
	jQuery.ajax({
        url: elex_mv_admin_dashboard_params.ajax_url,
        type: 'POST',
        data: {
            action: "elex_mv_admin_product_data_last_thirty_days",
            _ajax_nonce: elex_mv_admin_dashboard_params.nonce,
			days: 30,
        },
        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_admin_commission']);
			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
	 adminChart = new Chart(
		document.getElementById('adminChart'), 
		config 
	);
	

}

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

	adminroot = L.map( 'chartmap', {
		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( adminroot );

	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( adminroot );
	} );
}