<?php

	/**
	 * Modul für Erzeugung von Statistiken in der Admin-Widget-Area
	 */
	class wpsg_mod_statistics extends wpsg_mod_basic 
	{
		
		var $lizenz = 1;
		var $id = 440;
		var $inline = false;
		var $version = "9.9.9";
		var $hilfeURL = 'http://wpshopgermany.de/?p=3210';
		
		var $observeStatuscodes = null;
		
		/** Hier sind alle möglichen Typen drin, wird von loadFields gefüllt */
		var $fields = array();
		
		/** Array für die möglichen Format Umwandlungen */
		var $arFormats = array();
		
		var $arCache = array();
		
		var $standardFilter = array();
		
		var $simulateUrl = '';
		
		/**
		 * Constructor
		 */
		public function __construct()
		{
			
			parent::__construct();
									
			$this->name = __('Statistik', 'wpsg');
			$this->group = __('Sonstiges', 'wpsg');
			$this->desc = __('Darstellung und Auswertung von Statistiken, Piwik Integration, Eckdaten als Dashboard-Widget', 'wpsg');
						
		}

		/**
		 * setzen der Default-Zustände ab welchen eine Rechnung als abgeschlossen gilt
		 * 100 - Zahlung akzeptiert
		 * 110 - Rechnung geschrieben
		 * Breiten- und Höhenangabe für Charttypen (Pie, Bar, Line)
		 * Anzahl der darzustellenden Top-Produkte
		 * (non-PHPdoc)
		 * @see mods/wpsg_mod_basic#install()
		 */
		public function install()
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			$this->shop->checkDefault('wpsg_mod_statistics_topproductcount', '5');
			
			$this->shop->checkDefault('wpsg_mod_statistics_line_chart_width', '800');
			$this->shop->checkDefault('wpsg_mod_statistics_line_chart_height', '500');
			$this->shop->checkDefault('wpsg_mod_statistics_pie_chart_width', '600');
			$this->shop->checkDefault('wpsg_mod_statistics_pie_chart_height', '500');
			$this->shop->checkDefault('wpsg_mod_statistics_bar_chart_width', '600');
			$this->shop->checkDefault('wpsg_mod_statistics_bar_chart_height', '500');
			$this->shop->checkDefault('wpsg_mod_statistics_piwik_SiteId', '1'); 
			
			$this->shop->checkDefault('wpsg_mod_statistics_status', implode(',', array(100, 110)));
	
			/**
			 * Produkttabelle für Kundenkarte erweitern
			*/
			$sql = "CREATE TABLE ".WPSG_TBL_KU." (
			  	wpsg_mod_statistics_long VARCHAR(100) DEFAULT '' NOT NULL,
				wpsg_mod_statistics_lat VARCHAR(100) DEFAULT '' NOT NULL
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
		} // public function install()
		
		public function checkGeneralBackendError() 
		{ 

			$wpsg_mod_statistics_piwik_SiteId = $this->shop->get_option('wpsg_mod_statistics_piwik_SiteId');
			
			if (!wpsg_isSizedInt($wpsg_mod_statistics_piwik_SiteId) && $this->usePiwik())
			{
				
				$this->shop->addBackendError('nohspc_'.wpsg_translate(__('Bitte überprüfen Sie die Konfiguration im <a href="#1#">Statistikmodul</a>. Es wurde keine Piwik Seiten ID angegeben.', 'wpsg'), WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Admin&action=module&modul=wpsg_mod_statistics'));
				
			}
			
		} // public function checkGeneralBackendError()
		
		public function wpsg_enqueue_scripts() 
		{
		
			if (is_admin())
			{
			
				wp_register_script('wpsg-mod_statistics-gmap', 'https://maps.googleapis.com/maps/api/js?sensor=false');
				wp_enqueue_script('wpsg-mod_statistics-gmap');
				
			}
			
		} // public wpsg_enqueue_scripts()
		 		
		/**
		 * Rechte setzen
		 * (non-PHPdoc)
		 * @see mods/wpsg_mod_basic#admin_setcapabilities()
		 */
		public function admin_setcapabilities() { 
			
			$this->render(WPSG_PATH_VIEW.'/mods/mod_statistics/admin_setcapabilities.phtml');
			
		}
		
		public function checkout_inner_prebutton(&$checkout_view) 
		{ 
			
			if ($this->shop->get_option('wpsg_mod_statistics_piwik_checkout') == '1')
			{
				
				$this->trackTarget($this->shop->get_option('wpsg_mod_statistics_piwik_checkout_target'));
				
			}
			
		} // public function checkout_inner_prebutton(&$checkout_view)
		
		public function checkout2_inner_prebutton(&$checkout_view) 
		{ 
			
			if ($this->shop->get_option('wpsg_mod_statistics_piwik_checkout2') == '1')
			{
					
				$this->trackTarget($this->shop->get_option('wpsg_mod_statistics_piwik_checkout2_target'));
					
			}
			
		} // public function checkout2_inner_prebutton(&$checkout_view)
		
		public function overview_inner_prebutton(&$basket_view) 
		{ 
			
			if ($this->shop->get_option('wpsg_mod_statistics_piwik_overview') == '1')
			{
					
				$this->trackTarget($this->shop->get_option('wpsg_mod_statistics_piwik_overview_target'));
					
			}
			
		} // public function overview_inner_prebutton(&$basket_view)
		
		public function order_done(&$order_id, &$done_view) 
		{

			if ($this->shop->get_option('wpsg_mod_statistics_piwik_done') == '1')
			{
					
				$this->trackTarget($this->shop->get_option('wpsg_mod_statistics_piwik_done_target'));
					
			}
			
			if ($this->shop->get_option('wpsg_mod_statistics_piwik_ecommerce') == '1')
			{
				
				echo '<script type="text/javascript">';
				
				foreach ($done_view['basket']['produkte'] as $k => $p) 
				{
				
 					echo 'piwikTracker.addEcommerceItem("'.wpsg_hspc($p['id']).'", "'.wpsg_hspc($p['name']).'", "", '.wpsg_tf($p['preis']).', '.$p['menge'].');';
					
				}

				echo 'piwikTracker.trackEcommerceOrder("BestellNr.: '.$done_view['o_id'].'" , '.wpsg_tf($done_view['basket']['sum']['preis_gesamt_brutto']).');';
				echo '</script>';
				
			}
			
			if ((int)$this->shop->get_option('wpsg_mod_statistics_google_active') == 1)
			{
				$this->simulateUrl = $this->shop->getURL(wpsg_ShopController::URL_BASKET).'?wpsg_done';
				add_action('wp_footer', array($this, 'get_googleanalytics_html'), 100);
			}
			
		} // public function order_done($order_id)
		
		/* Modulfunktionen */
		
		/**
		 * Gibt den Piwik Code für ein Piwik Ziel zurück
		 */
		private function trackTarget($target_id)
		{
			
			if ($target_id > 0) echo '<script type="text/javascript"> piwikTracker.trackGoal('.$target_id.'); </script>';
			
		} // private function trackTarget($target_id)
		
		public function basket_after(&$basket_view) 
		{  
			
			if ($this->shop->get_option('wpsg_mod_statistics_piwik_basket') == '1')
			{
				
				$this->trackTarget($this->shop->get_option('wpsg_mod_statistics_piwik_basket_target'));
				
			}
			
		} // public function basket_after(&$basket_view)
		
		public function wp_head()
		{
			
			if (!$this->usePiwik()) return false;
						 
			$url = $this->shop->get_option('wpsg_mod_statistics_piwik_url');
			
			echo '
				<script type="text/javascript">
					var pkBaseURL = (("https:" == document.location.protocol) ? "https://'.$url.'/" : "http://'.$url.'/");
					document.write(unescape("%3Cscript src=\'" + pkBaseURL + "piwik.js\' type=\'text/javascript\'%3E%3C/script%3E"));
				</script>
			';
			
			if ($this->shop->get_option('wpsg_mod_statistics_piwik_generel') == '1')
			{
			
				echo '
					<!-- Piwik Tracking Code -->				
					<script type="text/javascript">
						try {
						
							var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", '.$this->shop->get_option('wpsg_mod_statistics_piwik_SiteId').');
							piwikTracker.trackPageView();
							piwikTracker.enableLinkTracking();
	
						} catch(err) { }
					</script>
					<!-- End Piwik Tracking Code -->
				';
				
			}
			else
			{
				
				echo '
					<!-- Piwik Tracking Code -->				
					<script type="text/javascript">
						try {
						
							var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", '.$this->shop->get_option('wpsg_mod_statistics_piwik_SiteId').');
	
						} catch(err) { }
					</script>
					<!-- End Piwik Tracking Code -->
				';
				
			}
			
		} // public function wp_head()
		
		/**
		 * Anzeige des Dashboard-Widgets
		 * @return none
		 */
		function wpsg_statistics_dashboard_widget_function() 
		{
			
			include dirname(__FILE__).'/mod_statistics/wpsg_statisticabstract.php';
			
			$objStatistik = new wpsg_statisticabstract();
			
			$this->shop->view['rows'][] = array('Kunden' => $objStatistik->getCustomerCount(), 
												'Bestellungen' => $objStatistik->getOrderCount(), 
												'Produkte' => $objStatistik->getProductCount());
			
			$this->shop->view['rows'][] = array('Umsatz in '.$this->shop->get_option('wpsg_currency') => '');
			
			$this->shop->view['rows'][] = array('####-1' => __('heute', 'wpsg').': '.wpsg_ff($objStatistik->getDailyTurnover()), 
												'####-2' => __('gestern', 'wpsg').': '.wpsg_ff($objStatistik->getDailyTurnover(time() - 86400)),
												'####-3' => __('gesamt', 'wpsg').': '.wpsg_ff($objStatistik->getTotalTurnover()));
			
			$this->render(WPSG_PATH_VIEW.'/mods/mod_statistics/totals.phtml');
			
		} 
		
		function be_ajax()
		{
			
			if ($_REQUEST['do'] == 'related')
			{
				
				$arRelated = array();
				
				foreach ($this->shop->view['standardFilter'] as $index => $filter)
				{
					if ($index == $_REQUEST['selection'])
					{
						if (is_array($filter['related']))
						{
							foreach ($filter['related'] as $related)
							{
								$arRelated[] = array('name' => $this->shop->view['standardFilter'][$related]['name'], 'value' => $related);
							}
						}	
					}
				}
				
				die(json_encode($arRelated));
			}
			else if ($_REQUEST['do'] == 'sorting') 
			{
				$this->dispatch();
			}
		}
		
		function wpsg_statistics_add_dashboard_widgets() 
		{
			
			wp_add_dashboard_widget('wpsg_statistics_dashboard_widget', __('wpShopGermany', 'wpsg').' - '.__('Statistik', 'wpsg'), array($this, 'wpsg_statistics_dashboard_widget_function'));	
		
		} 
		
		public function init()
		{

			$this->shop->view['standardFilter'] = array(	'0'	=>	array(	'name'		=>	__('Alle', 'wpsg'),
																			'func'		=>	'getAll',
																			'point'		=>	0,
																			'order'		=>	0),
															'1'	=>	array(	'name'		=>  __('Heute', 'wpsg'),
																			'func'		=>  'getDay',
																			'point'		=> 	0,
																			'order'		=>	1,
																			'related'	=>  array('6')),
															'2'	=>	array(	'name'		=>	__('Diese Woche', 'wpsg'),
																			'func'		=>	'getWeek',
																			'point'		=>	0,
																			'order'		=>	2,
																			'related'	=>  array('7')),
															'3' =>	array(	'name'		=>	__('Dieser Monat', 'wpsg'),
																			'func'		=>	'getMonth',
																			'point'		=> 	0,
																			'order'		=>	3,
																			'related'	=>	array('8')),
															'4'	=>	array(	'name'		=>  __('Dieses Quartal', 'wpsg'),
																			'func'		=> 	'getQuarter',
																			'point'		=> 	0,
																			'order'		=>	4,
																			'related'	=>  array('9')),
															'5'	=>	array(	'name'		=>  __('Dieses Geschäftjahr', 'wpsg'),
																			'func'		=>	'getYear',
																			'point'		=>	0,
																			'order'		=>	5,
																			'related'	=>  array('10')),
															'6'	=>	array(	'name'		=>  __('Gestern', 'wpsg'),
																			'func'		=>  'getDay',
																			'point'		=> 	-1,
																			'order'		=>	6,
																			'related'	=>	array('1')),
															'7'	=>	array(	'name'		=>  __('Letzte Woche', 'wpsg'),
																			'func'		=>  'getWeek',
																			'point'		=> 	-1,
																			'order'		=>	7,
																			'related'	=>  array('2')),
															'8'	=>	array(	'name'		=>  __('Letzter Monat', 'wpsg'),
																			'func'		=>  'getMonth',
																			'point'		=> 	-1,
																			'order'		=>	8,
																			'related'	=>  array('3')),
															'9'	=>	array(	'name'		=>  __('Vorjahresquartal', 'wpsg'),
																			'func'		=>  'getQuarter',
																			'point'		=> 	-1,
																			'order'		=>	9,
																			'related'	=> 	array('4')),
															'10'=>	array(	'name'		=>  __('Letztes Geschäftsjahr', 'wpsg'),
																			'func'		=>  'getYear',
																			'point'		=> 	-1,
																			'order'		=>	10,
																			'related'	=>  array('5')),
															'11'=>	array(	'name'		=>	__('Benutzerdefiniert', 'wpsg'),
																			'func'		=>	'getCustomRange',
																			'order'		=>	11));
			
			$this->shop->view['standardFilter'] = wpsg_array_csort($this->shop->view['standardFilter'], 'order');
			
			$this->observeStatuscodes = $this->shop->get_option('wpsg_mod_statistics_status');
			
			$this->topProductCount = $this->shop->get_option('wpsg_mod_statistics_topproductcount');
			
			$this->shop->view['modul_name'] = get_class($this);
			
			$role_object = get_role('administrator');
			$role_object->add_cap('wpsg_statistics');
			
			add_action('wp_dashboard_setup', array($this, 'wpsg_statistics_add_dashboard_widgets')); // Hint: For Multisite Network Admin Dashboard use wp_network_dashboard_setup instead of wp_dashboard_setup.	
			
			if ((int)$this->shop->get_option('wpsg_mod_statistics_google_active') == 1 && !isset($_GET['wpsg_done']))
			{
				add_action('wp_footer', array($this, 'get_googleanalytics_html'), 100);
			}
		}
			 
		/**
		 * Sammeln von Chartdaten und Rückgabe
		 * @return none
		 */
		public function dispatch()
		{
			
			$this->shop->view['charts'] = array(	'0'	=> array(	'name' =>	__('Verkäufe nach Zahlungsart', 'wpsg'),
																	'func' =>	'chartSalesToPaymentMethod',
																	'class'=>	'wpsg_salestopaymentmethod',
																	'order'=>   40,
			
																	'type' =>   array('all'	=> array('name'			=> __('Verkäufe nach Zahlungsart', 'wpsg').' ('.$this->shop->get_option('wpsg_currency').')',
																									 'title'		=> __('Verkäufe nach Zahlungsart', 'wpsg').' ('.$this->shop->get_option('wpsg_currency').')',
																									 'yaxis'		=> array('label'												=>  __('Umsatz in', 'wpsg').' '.$this->shop->get_option('wpsg_currency')),
																									 'template'		=> 'chartsalestopaymentmethod-all',
																									 'js'			=> array('wpsg_mod_statistics_js_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.js',
																															 'wpsg_mod_statistics_js_jqplot_barrenderer' 			=> 	'lib/jqplot/plugins/jqplot.barRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_pierenderer' 			=> 	'lib/jqplot/plugins/jqplot.pieRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_donutrenderer' 			=>	'lib/jqplot/plugins/jqplot.donutRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_categoryaxisrenderer' 	=>	'lib/jqplot/plugins/jqplot.categoryAxisRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvastextrenderer' 	=>	'lib/jqplot/plugins/jqplot.canvasTextRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvasaxislabelrenderer'=>	'lib/jqplot/plugins/jqplot.canvasAxisLabelRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvasaxistickrenderer'	=>	'lib/jqplot/plugins/jqplot.canvasAxisTickRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_pointlabels' 			=>	'lib/jqplot/plugins/jqplot.pointLabels.js'),
																									 'css'			=> array('wpsg_mod_statistics_css_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.css')))),
			
													'1'	=> array(	'name' 	=> 	__('Top', 'wpsg').' '.$this->topProductCount.' '.__('Pro.', 'wpsg').' ('.__('Umsatz/Menge', 'wpsg').')',
																	'func' 	=> 	'chartTopsellerToSales',
																	'class'	=> 	'wpsg_topsellertosales',
																	'order'	=>   30,
			
																	'type'	=>  array('all'	=> array('name'			=> __('Top', 'wpsg').' '.$this->shop->get_option('wpsg_mod_statistics_topproductcount').' '.__('verkaufter Produkte', 'wpsg').' ('.__('Umsatz in', 'wpsg').' '.$this->shop->get_option('wpsg_currency').' / '.__('Menge in Stck.', 'wpsg').')',
																									 'title'		=> __('Top', 'wpsg').' '.$this->shop->get_option('wpsg_mod_statistics_topproductcount').' '.__('verkaufter Produkte', 'wpsg').' ('.__('Umsatz in', 'wpsg').' '.$this->shop->get_option('wpsg_currency').' / '.__('Menge in Stck.', 'wpsg').')',
																									 'yaxis'		=> array('label'	=>  __('Umsatz in', 'wpsg').' '.$this->shop->get_option('wpsg_currency')),
																									 'template'		=> 'charttopsellertosales-all',
																									 'js'			=> array('wpsg_mod_statistics_js_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.js',
																															 'wpsg_mod_statistics_js_jqplot_highlighter' 			=>	'lib/jqplot/plugins/jqplot.highlighter.js',
																															 'wpsg_mod_statistics_js_jqplot_barrenderer' 			=> 	'lib/jqplot/plugins/jqplot.barRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_pierenderer' 			=> 	'lib/jqplot/plugins/jqplot.pieRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_donutrenderer' 			=>	'lib/jqplot/plugins/jqplot.donutRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_categoryaxisrenderer' 	=>	'lib/jqplot/plugins/jqplot.categoryAxisRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvastextrenderer' 	=>	'lib/jqplot/plugins/jqplot.canvasTextRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvasaxislabelrenderer'=>	'lib/jqplot/plugins/jqplot.canvasAxisLabelRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvasaxistickrenderer'	=>	'lib/jqplot/plugins/jqplot.canvasAxisTickRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_pointlabels' 			=>	'lib/jqplot/plugins/jqplot.pointLabels.js'),
																									 'css'			=> array('wpsg_mod_statistics_css_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.css')))),
			
													'2'	=> array(	'name'	=>  __('Umsatz', 'wpsg'),
																	'func'	=>  'chartTurnover',
																	'class'	=>	'wpsg_turnover',
																	'order'	=>   10,
																	
																	'type'	=>  array('line'=> array('name'			=> __('Umsatz', 'wpsg'),
																									 'title'		=> __('Umsatz', 'wpsg'),
																									 'yaxis'		=> array('label'	=>  __('Umsatz in', 'wpsg').' '.$this->shop->get_option('wpsg_currency')),
																									  'js'			=> array('wpsg_mod_statistics_js_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.js',
																															 'wpsg_mod_statistics_js_jqplot_highlighter' 			=>	'lib/jqplot/plugins/jqplot.highlighter.js',
																															 'wpsg_mod_statistics_js_jqplot_canvastextrenderer' 	=>	'lib/jqplot/plugins/jqplot.canvasTextRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvasaxislabelrenderer'=>	'lib/jqplot/plugins/jqplot.canvasAxisLabelRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_dateaxisrenderer'		=>  'lib/jqplot/plugins/jqplot.dateAxisRenderer.js'),
																									  'css'			=> array('wpsg_mod_statistics_css_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.css')))),
									
													'3'	=> array(	'name' 	=> 	__('Umsatz pro Stunde', 'wpsg'),
																	'func' 	=> 	'chartTurnoverPerHour',
																	'class'	=> 	'wpsg_turnoverperhour',
																	'order'	=>   20,
			
																	'type'	=>  array('line'=> array('name'			=> __('Umsatz pro Stunde', 'wpsg'),
																									 'title'		=> __('Umsatz pro Stunde', 'wpsg'),
																									 'yaxis'		=> array('label'	=>  __('Umsatz in', 'wpsg').' '.$this->shop->get_option('wpsg_currency')),
																									  'js'			=> array('wpsg_mod_statistics_js_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.js',
																															 'wpsg_mod_statistics_js_jqplot_highlighter' 			=>	'lib/jqplot/plugins/jqplot.highlighter.js',
																															 'wpsg_mod_statistics_js_jqplot_canvastextrenderer' 	=>	'lib/jqplot/plugins/jqplot.canvasTextRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_canvasaxislabelrenderer'=>	'lib/jqplot/plugins/jqplot.canvasAxisLabelRenderer.js',
																															 'wpsg_mod_statistics_js_jqplot_dateaxisrenderer'		=>  'lib/jqplot/plugins/jqplot.dateAxisRenderer.js'),
																									  'css'			=> array('wpsg_mod_statistics_css_jqplot' 						=> 	'lib/jqplot/jquery.jqplot.css')))),
				'14' => array(
					'name' => __('Kundenkarte', 'wpsg'),
					'func' => 'customerMap',
					'class' => 'wpsg_customerMap',
					'type' => array(),
					'order'	=>   50,
				)
			);

				
			//Statistikarray nach order sortieren 
			$this->shop->view['charts'] = wpsg_array_csort($this->shop->view['charts'], 'order');
			
			//Default-Statistiken laden wenn keine REQUEST-Parameter für id bzw. Type übergeben wurden
			if (!isset($_REQUEST['id'])) 
			{ 
				$_REQUEST['id'] = '0'; 
				$_REQUEST['type'] = array_shift(array_keys($this->shop->view['charts'][$_REQUEST['id']]['type']));  
			}
			else if (isset($_REQUEST['id']) && !isset($_REQUEST['type']))
			{
				$_REQUEST['type'] = array_shift(array_keys($this->shop->view['charts'][$_REQUEST['id']]['type']));  	
			}
			
			/**
			 * Skripte für jQPlot in Abhängigkeit von Statistiktyp einbinden
			 */
			if ($_REQUEST['page'] == 'wpsg-Statistics')
			{
				if (is_array($this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']]['js']) && count($this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']]) > 0)
				{
					foreach ($this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']]['js'] as $index => $value)
					{
						wp_enqueue_script($index, WPSG_URL_CONTENT.'plugins/wpshopgermany/'.$value);		
					}	
				}
				
				if (is_array($this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']]['css']) && count($this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']]) > 0)
				{
					foreach ($this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']]['css'] as $index => $value)
					{
						wp_enqueue_style($index, WPSG_URL_CONTENT.'plugins/wpshopgermany/'.$value);		
					}	
				}
				
				$this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']];
			}
			
			$this->shop->view['filter'] = array();
			if (wpsg_isSizedArray($_REQUEST['filter'])) $this->shop->view['filter'] = $_REQUEST['filter'];
						
			if (!isset($this->shop->view['filter']['standard'])) { $this->shop->view['filter']['standard'] = '0'; }
			
			$chartFunction = $this->shop->view['charts'][$_REQUEST['id']]['func'];
			
			$chartClass = $this->shop->view['charts'][$_REQUEST['id']]['class'];

			include dirname(__FILE__).'/mod_statistics/'.$chartClass.'.class.php';
			
			$objchartClass = new $chartClass($this->shop, $this->db);
			
			$chartFunction = $this->shop->view['standardFilter'][$this->shop->view['filter']['standard']]['func'];
			
			if (method_exists($objchartClass, $chartFunction))
			{
				$this->shop->view['chart']['data'] = $objchartClass->$chartFunction($this->shop->view['standardFilter'][$this->shop->view['filter']['standard']]['point'], array('relatedpoint' => $this->shop->view['standardFilter'][$this->shop->view['filter']['related']]['point'], 'order' => $this->shop->view['filter']['order'], 'sort' => $this->shop->view['filter']['sort']));
				$this->shop->view['chart']['info'] = $this->shop->view['charts'][$_REQUEST['id']]['type'][$_REQUEST['type']];
			}
			
			if (wpsg_isAjaxRequest())
			{
				//wpsg_debug($_REQUEST); die();
				$this->render(WPSG_PATH_VIEW.'/mods/mod_statistics/'.strtolower($this->shop->view['charts'][$_REQUEST['id']]['func']).'/data.phtml');
			}
			else
			{
				$this->render(WPSG_PATH_VIEW.'/mods/mod_statistics/statistics.phtml');
			}
		
		}
		
		/**
		 * TODO eigenes Recht für Statistikeinsicht hinzufügen
		 * (non-PHPdoc)
		 * @see mods/wpsg_mod_basic#wpsg_add_pages()
		 */
		public function wpsg_add_pages()
		{
			
			add_submenu_page('wpsg-Admin', __("Statistik", "wpsg"), __("Statistik", "wpsg"), 'wpsg_statistics', 'wpsg-Statistics', array($this, 'dispatch'));
			
		}
		
		public function load()
		{
			
			if (isset($_REQUEST['page']) && $_REQUEST['page'] == 'wpsg-Statistics')
			{
				wp_enqueue_style('wpsg_mod_statistics_css_jqplot', WPSG_URL_CONTENT.'plugins/wpshopgermany/lib/jqplot/jquery.jqplot.css');
			}
			
		}
		
		public function settings_edit()
		{
						
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_statistics/settings_edit.phtml');
			
		}
		
		public function settings_save() 
		{
			$this->shop->update_option('wpsg_mod_statistics_piwik_url', $_REQUEST['wpsg_mod_statistics_piwik_url']);
			
			$this->shop->update_option('wpsg_mod_statistics_piwik_generel', $_REQUEST['wpsg_mod_statistics_piwik_generel']);	
			$this->shop->update_option('wpsg_mod_statistics_piwik_SiteId', $_REQUEST['wpsg_mod_statistics_piwik_SiteId']);		
			$this->shop->update_option('wpsg_mod_statistics_piwik_ecommerce', $_REQUEST['wpsg_mod_statistics_piwik_ecommerce']);
			
			$this->shop->update_option('wpsg_mod_statistics_piwik_basket', $_REQUEST['wpsg_mod_statistics_piwik_basket']);
			$this->shop->update_option('wpsg_mod_statistics_piwik_basket_target', $_REQUEST['wpsg_mod_statistics_piwik_basket_target']);
			
			$this->shop->update_option('wpsg_mod_statistics_piwik_checkout', $_REQUEST['wpsg_mod_statistics_piwik_checkout']);
			$this->shop->update_option('wpsg_mod_statistics_piwik_checkout_target', $_REQUEST['wpsg_mod_statistics_piwik_checkout_target']);
			
			$this->shop->update_option('wpsg_mod_statistics_piwik_checkout2', $_REQUEST['wpsg_mod_statistics_piwik_checkout2']);
			$this->shop->update_option('wpsg_mod_statistics_piwik_checkout2_target', $_REQUEST['wpsg_mod_statistics_piwik_checkout2_target']);
			
			$this->shop->update_option('wpsg_mod_statistics_piwik_overview', $_REQUEST['wpsg_mod_statistics_piwik_overview']);
			$this->shop->update_option('wpsg_mod_statistics_piwik_overview_target', $_REQUEST['wpsg_mod_statistics_piwik_overview_target']);
			
			$this->shop->update_option('wpsg_mod_statistics_piwik_done', $_REQUEST['wpsg_mod_statistics_piwik_done']);
			$this->shop->update_option('wpsg_mod_statistics_piwik_done_target', $_REQUEST['wpsg_mod_statistics_piwik_done_target']);
			
			$this->shop->update_option('wpsg_mod_statistics_google_active', $_REQUEST['wpsg_mod_statistics_google_active']);
			$this->shop->update_option('wpsg_mod_statistics_google_domainname', $_REQUEST['wpsg_mod_statistics_google_domainname']);
			$this->shop->update_option('wpsg_mod_statistics_google_tracking_code', $_REQUEST['wpsg_mod_statistics_google_tracking_code']);
			$this->shop->update_option('wpsg_mod_statistics_google_anonymise_ip_address', $_REQUEST['wpsg_mod_statistics_google_anonymise_ip_address']);
			$this->shop->update_option('wpsg_mod_statistics_google_track_page_load_time', $_REQUEST['wpsg_mod_statistics_google_track_page_load_time']);
			
			$this->shop->update_option('wpsg_mod_statistics_line_chart_width', $_REQUEST['wpsg_mod_statistics_line_chart_width']);
			$this->shop->update_option('wpsg_mod_statistics_line_chart_height', $_REQUEST['wpsg_mod_statistics_line_chart_height']);
			$this->shop->update_option('wpsg_mod_statistics_pie_chart_width', $_REQUEST['wpsg_mod_statistics_pie_chart_width']);
			$this->shop->update_option('wpsg_mod_statistics_pie_chart_height', $_REQUEST['wpsg_mod_statistics_pie_chart_height']);
			$this->shop->update_option('wpsg_mod_statistics_bar_chart_width', $_REQUEST['wpsg_mod_statistics_bar_chart_width']);
			$this->shop->update_option('wpsg_mod_statistics_bar_chart_height', $_REQUEST['wpsg_mod_statistics_bar_chart_height']);
			$this->shop->update_option('wpsg_mod_statistics_topproductcount', $_REQUEST['wpsg_mod_statistics_topproductcount']);
			$this->shop->update_option('wpsg_mod_statistics_status', implode(',', array_keys(array_filter((array)$_REQUEST['wpsg_mod_statistics_status'], create_function('$a','return $a != 0;')))));
			
		}
		 
		public function get_pagetrackingcode()
		{
			
			if (wpsg_isSizedString($this->simulateUrl))
			{
				$requestURI = $this->simulateUrl;
			}
			else
			{
				$requestURI = $_SERVER['REQUEST_URI'];
			}
			
			//url to track
	        $pageURL = trim(str_replace(get_site_url().'/', '', $requestURI));
	        if ($pageURL && preg_match('/^\/.*/i', $pageURL)) {
	            $pageURL = strval(wpsg_jsquoteescape($pageURL));
	        }

			$html = '
            _gaq.push(["_setAccount", "' . wpsg_jsquoteescape($this->shop->get_option('wpsg_mod_statistics_google_tracking_code')) . '"]';

			if ($domainName = $this->shop->get_option('wpsg_mod_statistics_google_domainname')) {
	            $html .=' ,["_setDomainName","' . $domainName . '"]';
	        }
	        if($anonymise = $this->shop->get_option('wpsg_mod_statistics_google_anonymise_ip_address')) {
	            $html .=', ["_gat._anonymizeIp"]';
	        }
	        
			/*if($this->shop->get_option('wpsg_mod_statistics_google_enable_first_touch_tracking')) {
	            $html .=');
	            asyncDistilledFirstTouch(_gaq);
	            _gaq.push(["_trackPageview","' . $pageURL . '"]';
	        } else {
	            $html .=', ["_trackPageview","' . $pageURL . '"]';
	        }*/
	        
			if($this->shop->get_option('wpsg_mod_statistics_google_track_page_load_time')) {
            	$html .=', ["_trackPageLoadTime"]';
        	}        
        	
        	$html .=');';
        	
        	return $html;
        	
		}
		
		public function get_googleanalytics_html()
		{
			
			$html = '
<!-- BEGIN_WPSG_GOOGLE_ANALYTICS_CODE -->
<script type="text/javascript">
//<![CDATA[
            (function() {
            	var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;';
            
			$html .= 'ga.src = \'https://google-analytics.com/ga.js\';';
			
			$html .= '
                var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);
            })();
            var _gaq = _gaq || [];
'
			.$this->get_pagetrackingcode().'
            //]]>
</script>
<!-- END_WPSG_GOOGLE_ANALYTICS_CODE -->
';
			echo $html;
		}
		
		/** Modulfunktionen */
		
		/**
		 * Wird irgendeine PIWIK Konfiguration verwendet
		 */
		private function usePiwik()
		{
			
			$arConfPiwik = array(
				'wpsg_mod_statistics_piwik_generel', 
				'wpsg_mod_statistics_piwik_ecommerce', 
				'wpsg_mod_statistics_piwik_basket', 
				'wpsg_mod_statistics_piwik_checkout', 
				'wpsg_mod_statistics_piwik_checkout2', 
				'wpsg_mod_statistics_piwik_overview', 
				'wpsg_mod_statistics_piwik_done'
			);
				
			foreach ($arConfPiwik as $c) { if ($this->shop->get_option($c) == '1') { return true; } }
			
			return false;
			
		} // private function usePiwik()
		
		/**
		 * Lädt die TopProdukte wird von dem TopProducts Modul aufgerufen
		 */
		public function loadTopProducts(&$strQueryLIMIT)
		{
			
			return $this->db->fetchAssoc("
				SELECT
					P.`id`, SUM(OP.`menge`) AS `count_buy`
				FROM
			 		`".WPSG_TBL_PRODUCTS."` AS P
			 			LEFT JOIN `".WPSG_TBL_ORDERPRODUCT."` AS OP ON (P.`id` = OP.`p_id`)				 			
			 	WHERE
			 		P.`deleted` != '1' AND
			 		P.`wpsg_mod_topseller` != '1'
			 	GROUP BY
			 		P.`id` 
			 	HAVING
			 		`count_buy` > 0				 	
			 	ORDER BY
			 		`count_buy` DESC
			 	".$strQueryLIMIT."				 	
			");
			
		} // public function loadTopProducts()
		
		public function onBasketShow()
		{
				
		}
		
	}

?>