/**
 * @package     Reporter for VirtueMart
 * 
 * @copyright   Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Abhishek Das <info@virtueplanet.com> - https://www.virtueplanet.com
 */

var VMReporter = window.VMReporter || {};

(function($, VMReporter) {

	VMReporter.overviewChart = null;

	VMReporter.analysisChart = null;

	VMReporter.showOverviewChart = function() {
		var chart_overview_data = VMReporter._('CHART_OVERVIEW_DATA', {});

		if ($.type(chart_overview_data) !== 'object') {
			console.log('Invalid overview chart data object.');
			console.log(chart_overview_data);
			return false;
		}
		
		$('#vmreporter-overview-revenue').closest('.tab-pane').show();
		
		$.plot("#vmreporter-overview-revenue", [{
			data: chart_overview_data.values.data,
			label: chart_overview_data.values.label,
			lines: {
				show: true
			}
		}], {
			xaxes: [{
				mode: "time",
				tickColor: "#ddd"
			}],
			yaxes: [{
				min: 0,
				minTickSize: 1,
				tickColor: "#ddd",
				tickFormatter: VMReporter.currency_format,
			}],
			legend: {
				show: false,
				position: "nw"
			},
			grid: {
				hoverable: true,
				borderColor: "#ddd"
			},
			tooltip: true,
			tooltipOpts: {
				content: function(xlabel, xvalue, yvalue) {
					var date = new Date(xvalue);
					date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
					return $.plot.formatDate(date, '%b %d, %Y') + ': <b>' + VMReporter.currency_format(yvalue) + '</b>';
				},
				shifts: {
					x: 20,
					y: 20
				},
				defaultTheme: false
			},
			colors: ['#4285f4']
		});
		
		$('#vmreporter-overview-revenue').closest('.tab-pane').removeAttr('style');
		
		$('#vmreporter-overview-count').closest('.tab-pane').show();
		
		$.plot("#vmreporter-overview-count", [{
			data: chart_overview_data.counts.data,
			label: chart_overview_data.counts.label,
			yaxis: 2,
			lines: {
				show: true
			},
		}], {
			xaxes: [{
				mode: "time",
				tickColor: "#ddd"
			}],
			yaxes: [{
				min: 0,
				minTickSize: 1,
				tickDecimals: 0,
				tickColor: "#ddd"
			}],
			legend: {
				show: false,
				position: "nw"
			},
			grid: {
				hoverable: true,
				borderColor: "#ddd"
			},
			tooltip: true,
			tooltipOpts: {
				//content: "%s: %y.00 <br/>%x", // show percentages, rounding to 2 decimal places
				content: function(xlabel, xvalue, yvalue) {
					var date = new Date(xvalue);
					date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
					return $.plot.formatDate(date, '%b %d, %Y') + ': <b>%y.0</b>';
				},
				shifts: {
					x: 20,
					y: 20
				},
				defaultTheme: false
			},
			colors: ['#4285f4']
		});
		
		$('#vmreporter-overview-count').closest('.tab-pane').removeAttr('style');
	};
	
	VMReporter.showAnalysisChart = function(placeholder, chartData, content) {
		content = !content ? 'order_totals' : content;

		if (!chartData.hasOwnProperty(content)) {
			console.log('Invalid chart data content: ' + content);
			return false;
		}

		$(placeholder).closest('.tab-pane').show();
		
		if (content == 'order_totals' || content == 'order_counts' || content == 'item_order_counts') {
			
			chartData[content].sort(function(a, b) {
				return a.total < b.total ? 1 : -1;
			});
			
			$.plot(placeholder, chartData[content], {
				xaxes: [{
					mode: "time",
					tickColor: "#ddd"
				}],
				yaxes: [{
					min: 0,
					minTickSize: 1,
					tickColor: "#ddd",
					tickFormatter: function(v) {
						if (content == 'order_totals') {
							v = VMReporter.currency_format(v);
						}
						return v;
					},
				}],
				legend: {
					container: $(placeholder + '-legends'),
					labelFormatter: function(label, series) {
						if(typeof series.url !== typeof undefined && series.url) {
							label = '<a href="' + series.url + '" target="_blank">' + label + '</a>';
						}
						
						if(typeof series.total !== typeof undefined && series.total) {
							var total = content == 'order_totals' ? VMReporter.currency_format(series.total) : series.total;
							
							label += ' (' + total + ')';
						}
						
						return label;
					}
				},
				grid: {
					hoverable: true
				},
				points: {
					show: false
				},
				tooltip: true,
				tooltipOpts: {
					content: "%y.00", // show percentages, rounding to 2 decimal places
					content: function(xlabel, xvalue, yvalue) {
						var date = new Date(xvalue);
						date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
						var value = content == 'order_totals' ? VMReporter.currency_format(yvalue) : yvalue;
						return '%s<br />' + $.plot.formatDate(date, '%b %d, %Y') + ': <b>' + value + '</b>';
					},
					shifts: {
						x: 20,
						y: 20
					},
					defaultTheme: false
				}
			});
		} else if (content == 'revenues') {
			
			chartData[content].sort(function(a, b) {
				return a.data < b.data ? 1 : -1;
			});
			
			$.plot(placeholder, chartData[content], {
				series: {
					pie: {
						show: true
					}
				},
				grid: {
					hoverable: true
				},
				legend: {
					container: $(placeholder + '-legends'),
					labelFormatter: function(label, series) {
						if(typeof series.url !== typeof undefined && series.url) {
							label = '<a href="' + series.url + '" target="_blank">' + label + '</a>';
						}
						if(typeof series.data !== typeof undefined && typeof series.data[0] !== typeof undefined && typeof series.data[0][1] !== typeof undefined) {
							label += ' (' + VMReporter.currency_format(series.data[0][1]) + ')';
						}
						
						return label;
					}
				},
				tooltip: true,
				tooltipOpts: {
					// content: "%p.00%, %y.0", // show percentages, rounding to 2 decimal places
					content: function(xlabel, xvalue, yvalue) {
						return '%s<br />%p.00%, ' + VMReporter.currency_format(yvalue);
					},
					shifts: {
						x: 20,
						y: 20
					},
					defaultTheme: false
				}
			});
		}
		
		$(placeholder).closest('.tab-pane').removeAttr('style');
	};
	
	VMReporter.showProductCharts = function() {
		var chart_data = VMReporter._('CHART_PRODUCT_DATA', {});

		VMReporter.showAnalysisChart('#vmreporter-product-total', chart_data, 'order_totals');
		VMReporter.showAnalysisChart('#vmreporter-product-count', chart_data, 'item_order_counts');
		VMReporter.showAnalysisChart('#vmreporter-product-quantity', chart_data, 'order_counts');
		VMReporter.showAnalysisChart('#vmreporter-product-revenue', chart_data, 'revenues');
	};
	
	VMReporter.showCategoryCharts = function() {
		var chart_data = VMReporter._('CHART_CATEGORY_DATA', {});

		VMReporter.showAnalysisChart('#vmreporter-category-total', chart_data, 'order_totals');
		VMReporter.showAnalysisChart('#vmreporter-category-count', chart_data, 'item_order_counts');
		VMReporter.showAnalysisChart('#vmreporter-category-quantity', chart_data, 'order_counts');
		VMReporter.showAnalysisChart('#vmreporter-category-revenue', chart_data, 'revenues');
	};
	
	VMReporter.manageDateFields = function() {
		if($('select#filter_period').val() == 'fixed') {
			$('input#filter_start_date[type="text"], input#filter_end_date[type="text"]').attr('readonly', false);
			$('button#filter_start_date_btn, button#filter_end_date_btn').show();
		} else {
			setTimeout(function() {
				$('input#filter_start_date[type="text"], input#filter_end_date[type="text"]').attr('readonly', true);
			}, 50);
			$('button#filter_start_date_btn, button#filter_end_date_btn').hide();
		}
	};
	
	$(function() {
		VMReporter.showOverviewChart();
		VMReporter.showProductCharts();
		VMReporter.showCategoryCharts();
		
		$('form#vmreporter-frontpage-form').on('submit', function() {
			var loader = $(this).find('.vmreporter-loader-overlay, .vmreporter-loader');

			$(loader).addClass('vmreporter-fade');
			
			setTimeout(function() {
				$(loader).addClass('vmreporter-in');
			}, 50);
		});
		
		$('form .frontpage-toolbar select').on('change', function() {
			if($(this).attr('id') == 'filter_period' && $(this).val() == 'fixed') {
				VMReporter.manageDateFields();
			} else {
				$(this).closest('form').submit();
			}
		});
		
		var startDate = $('input#filter_start_date[type="text"]').val();
		
		$('input#filter_start_date[type="text"]').on('blur', function() {
			if($(this).val() != startDate) {
				$(this).closest('form').submit();
			}
		});
		
		var endDate = $('input#filter_end_date[type="text"]').val();
		
		$('input#filter_end_date[type="text"]').on('blur', function() {
			if($(this).val() != endDate) {
				$(this).closest('form').submit();
			}
		});
		
		VMReporter.manageDateFields();
	});

})(jQuery, VMReporter);