<?php

require_once WPSG_PATH_MOD.'mod_statistics/wpsg_statisticabstract.php';
/**
 * Klasse zur Ermittlung Statistik für die Umsätze
 * @author 	robert
 * @since	11.01.2013
 */
class wpsg_turnover extends wpsg_statisticabstract 
{
	
	/**
	 * Rückgabe aller Statistikdaten
	 * @internal Bezug -> Jahr
	 * @return array
	 */
	public function getAll($point = 0, $params = array())
	{
			
		$arData = $this->db->fetchRow(" 
			SELECT 
				CAST(MIN(`cdate`) AS DATE) AS start,
				CAST(MAX(`cdate`) AS DATE) AS end
			FROM 
				`".WPSG_TBL_ORDER."` 
			WHERE ".
				$this->getSqlWhere('validOrder')
		);
		
		if (wpsg_isSizedArray($arData))
		{	
			if (!wpsg_isSizedString($arData['start'])) { $arData['start'] = date_i18n('d.m.Y', time()); }
			if (!wpsg_isSizedString($arData['end'])) { $arData['end'] = $arData['start']; }
			
			$params['oStart'] = strtotime($arData['start']);
			$params['oEnd'] = (strtotime($arData['end'])+86399);
			
			return $this->getCustomRange(0, $params);	
		}
	
		return array();
			
	}	
	
	/**
	 * Rückgabe der Statistik auf ein Jahr bezogen
	 * @internal Bezug -> Monat
	 * @param int Bezugspunkt (0 aktuelles Jahr, -1 letztes Jahr)
	 * @return array
	 */
	public function getYear($point = 0, $params = array())
	{
		
		if ($point == '0')
		{
			$year = date('Y');
		}
		else if ($point == '-1')
		{
			$year = date('Y') - 1;
		}
		
		$arData[0]['min'] = strtotime('01.01.'.$year); 
		$arData[0]['max'] = strtotime('31.12.'.$year); 
		
		$arData[0]['records'] = $this->db->fetchAssoc(" 
			SELECT 
				COUNT(*) AS orders,
				SUM( `price_gesamt` ) AS total, 
				AVG( `price_gesamt` ) AS avg_total,
				MONTH( `cdate` ) AS month, 
				YEAR( `cdate` ) AS year,
				UNIX_TIMESTAMP( `cdate` ) AS tstamp
			FROM 
		  		`".WPSG_TBL_ORDER."`
			WHERE 
		  		".$this->getSqlWhere('validOrder')." AND 
		  		YEAR( `cdate` ) = '".$year."'
		  	GROUP BY 
		  		year, month
		  	ORDER BY 
		  		year DESC
		   ", 
		   "month"
		);
		
		$arData[0]['label'] = __('Geschäftsjahr', 'wpsg').' '.$year;
		
		
		for ($i = 1; $i <= 12; $i++)
		{
			if (!array_key_exists($i, $arData[0]['records']))
			{
				$arData[0]['records'][$i] = array('orders' 		=> '0',
												  'total'	 	=> '0',
												  'avg_total'	=> '0',
												  'month'	 	=> $i,
												  'year'	 	=> $year,
												  'tstamp'		=> mktime(0, 0, 0, $i, 1, $year));
			}

			$arData[0]['records'][$i]['label'] = date_i18n('M', mktime(0, 0, 0, $i, 1, $year));
			$arData[0]['records'][$i]['tick'] = $arData[0]['records'][$i]['label'];
			
		}
		
		$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));

		if (isset($params['relatedpoint']) && is_numeric($params['relatedpoint']))
		{
			$arRelatedData = $this->getYear($params['relatedpoint']);
			
			$this->addSorting($arRelatedData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
			$arData[] = $arRelatedData[0];
		}
		
		return $arData;
		
	}
	
	/**
	 * Rückgabe der Statistik auf ein Quartal bezogen
	 * @param string
	 * @internal Bezug -> Monat 
	 * @return array
	 */
	public function getQuarter($point = 0, $params = array())
	{
		$arQuarter = array(	'1' => array(1, 2, 3),
							'2'	=> array(4, 5, 6),
							'3'	=> array(7, 8, 9),
							'4' => array(10, 11, 12));
		
		if ($point == '0')
		{
			$year = date('Y');
			$month = date('n');
		}
		else if ($point == '-1')
		{
			$year = date('Y');
			$month = date('n');
			
			foreach ($arQuarter as $index => $quarter)
			{
				if (in_array($month, $quarter))
				{
					if (isset($actQuarter[$index - 1]))
					{
						$quarterFirstMonth = $arQuarter[$index - 1][0];	
					}
					else
					{
						$quarterFirstMonth = $arQuarter[count($arQuarter)][0];	
						$year--;
					}
				}
			}
			
			$month = $quarterFirstMonth;
		}
		
		$arWeeks = array();
		
		foreach ($arQuarter as $index => $quarter)
		{
			if (in_array($month, $quarter))
			{
				
				$actQuarter = $index;
				
				$lastMonth = $arQuarter[$index][count($arQuarter[$index]) - 1];
				
				$daysLastMonth = wpsg_getDaysofMonth($lastMonth, $year);
				
				$dayLastMonthTS = mktime(0, 0, 0, $lastMonth, $daysLastMonth, $year);
				
				$firstMonth = array_shift($arQuarter[$index]);
				
				$dayFirstMonthTS = mktime(0, 0, 0, $firstMonth, 1, $year);
				
				$dayFirstMonthTSCounter = $dayFirstMonthTS;
				
				while ($dayFirstMonthTSCounter <= $dayLastMonthTS)
				{
					$week = date('W', $dayFirstMonthTSCounter);
					
					if ($week[0] == 0)
					{
						$week = str_replace('0', '', $week);
					}
					
					if ($index == 4 && $week == 1)
					{
						$week = 53;
					}
					
					$year = date('Y', $dayFirstMonthTSCounter);
					
					$month = date('n', $dayFirstMonthTSCounter);
					
					$day = date('j', $dayFirstMonthTSCounter);
					
					if (!in_array($week, $arWeeks))
					{
						$arWeeks[$week] = array('week' 	=> $week,
										        'year' 	=> $year,
												'day'  	=> $day,
												'month'	=> $month);
					}
					
					$dayFirstMonthTSCounter += 86400;
				}
			}
		}
		
		//MYSQL WEEK http://dev.mysql.com/doc/refman/5.1/de/date-and-time-functions.html Modus 3
		
		$arData[0]['records'] = $this->db->fetchAssoc(" SELECT 
														    COUNT(*) AS orders,
														    ".$actQuarter." AS quarter,
															SUM( `price_gesamt` ) AS total,
															AVG( `price_gesamt` ) AS avg_total,
															DAY( `cdate`) AS day,
															DAYOFYEAR (`cdate`) AS dayofyear,
															WEEK ( `cdate`, 3) AS week, 
															MONTH( `cdate` ) AS month, 
															YEAR( `cdate` ) AS year,
															UNIX_TIMESTAMP( `cdate` ) AS tstamp
													  FROM 
													  		`".WPSG_TBL_ORDER."`
													  WHERE 
													  		".$this->getSqlWhere('validOrder')." AND 
													  		`cdate`	>= '".date('Y-m-d 00:00:00', $dayFirstMonthTS)."' AND 
													  		`cdate` <= '".date('Y-m-d 23:59:59', $dayLastMonthTS)."'
													  GROUP BY 
													  		year, month, week
													  ORDER BY 
													  		week ASC
													  ", "week");
		
		foreach ($arWeeks as $week)
		{
			if (!array_key_exists($week['week'], (array)$arData[0]['records']))
			{
				$arData[0]['records'][$week['week']] = array(	'orders'	=> '0',
																'total'		=> '0',
																'avg_total' => '0',
																'quarter'	=> $actQuarter,
																'day'		=> $week['day'],
																'week'		=> $week['week'],
																'year'		=> $week['year'],
																'month'		=> $week['month'],
																'tstamp'	=> mktime(0, 0, 0, $week['month'], $week['day'], $week['year']));
			}
			
			$arData[0]['records'][$week['week']]['label'] = __('KW', 'wpsg').' '.$week['week'];
			
		}
		
		$arData[0]['label'] = $actQuarter.".".__('Quartal', 'wpsg').' '.$year;
		$arData[0]['year'] = $year;
		
		$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
		
		if (isset($params['relatedpoint']) && is_numeric($params['relatedpoint']))
		{
			$arRelatedData = $this->getQuarter($params['relatedpoint']);
			
			$this->addSorting($arRelatedData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
			$arData[] = $arRelatedData[0];
		}
		
		return $arData;
		
	}
	
	/**
	 * Rückgabe der Statistik auf einen Monat bezogen
	 * @internal Bezug -> Tag 
	 * @param string
	 * @return array
	 */
	public function getMonth($point = 0, $params = array())
	{
		
		if ($point == '0')
		{
			$year = date('Y');
			$month = date('n');
		}
		else if ($point == '-1')
		{
			$year = date('Y');
			$month = date('n') - 1;
			
			if ($month == 0)
			{
				$month = 12;
				$year--;
			}
		}
		
		$arData[0]['records'] = $this->db->fetchAssoc(" SELECT 
														    COUNT(*) AS orders,
															SUM( `price_gesamt` ) AS total,
															AVG( `price_gesamt` ) AS avg_total,
															DAY( `cdate`) AS day, 
															MONTH( `cdate` ) AS month, 
															YEAR( `cdate` ) AS year,
															UNIX_TIMESTAMP(`cdate`) AS tstamp
													  FROM 
													  		`".WPSG_TBL_ORDER."`
													  WHERE 
													  		".$this->getSqlWhere('validOrder')." AND 
													  		YEAR( `cdate` ) = '".$year."' AND 
													  		MONTH ( `cdate` ) = '".$month."'
													  GROUP BY 
													  		year, month, day
													  ORDER BY 
													  		year DESC
													  ", "day");
		
		$days = wpsg_getDaysofMonth($month, $year);
		
		$arData[0]['min'] = mktime(0, 0, 0, $month, 1, $year);
		$arData[0]['max'] = mktime(0, 0, 0, $month, $days, $year);
		
		$arData[0]['label'] = date_i18n('F', $arData[0]['min']).' '.date('Y', $arData[0]['min']);
	
		for ($day = 1; $day <= $days; $day++)
		{
			if (!isset($arData[0]['records'][$day]))
			{
				$arData[0]['records'][$day] = array('orders' 	=> '0',
													'total'		=> '0',
													'avg_total'	=> '0',
													'day'		=> $day,
													'month'		=> $month,
													'year'		=> $year,
													'tstamp'	=> mktime(0, 0, 0, $month, $day, $year));
			}
			
			$arData[0]['records'][$day]['label'] = str_pad($day, 2, "0", STR_PAD_LEFT).'.'.str_pad($month, 2, "0", STR_PAD_LEFT).'.'.$year;
			
		}
		
		$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
		
		if (isset($params['relatedpoint']) && is_numeric($params['relatedpoint']))
		{
			$arRelatedData = $this->getMonth($params['relatedpoint']);
			
			$this->addSorting($arRelatedData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
			$arData[] = $arRelatedData[0];
		}
		
		return $arData;
		
	}
	
	/**
	 * Rückgabe der Statistik auf eine Woche bezogen
	 * @internal Bezug -> Tag 
	 * @param string
	 * @return array
	 */
	public function getWeek($point = 0, $params = array())
	{
		
		$adjustment = 1;
		
		if ($point == '0')
		{
			$weekday = date("w", time());
		
			$firstDayofWeek = time() - (($weekday - $adjustment)*86400);
			$lastDayofWeek = time() + ((6 + $adjustment - $weekday) * 86400);
		}
		else if ($point == '-1') 
		{
			
			$time = time() - (6*86400);
			
			$weekday = date("w", $time);
		
			$firstDayofWeek = $time - (($weekday - $adjustment)*86400);
			$lastDayofWeek = $time + ((6 + $adjustment - $weekday) * 86400);
		}
		
		$arData[0]['records'] = $this->db->fetchAssoc("	SELECT 
															COUNT(*) AS orders,
															SUM( `price_gesamt` ) AS total,
															AVG( `price_gesamt` ) AS avg_total,
															DAY( `cdate`) AS day, 
															MONTH( `cdate` ) AS month, 
															YEAR( `cdate` ) AS year,
															UNIX_TIMESTAMP(`cdate`) AS tstamp
													 	FROM 
													  		`".WPSG_TBL_ORDER."`
													 	WHERE 
													  		".$this->getSqlWhere('validOrder')." AND 
													  		`cdate`	>= '".date('Y-m-d 00:00:00', $firstDayofWeek)."' AND 
													  		`cdate` <= '".date('Y-m-d 23:59:59', $lastDayofWeek)."'
													 	GROUP BY 
													 		year, month, day
														ORDER BY 
													 		year DESC
													 	", "day");
		
		$day += $firstDayofWeek;
		
		for ($i = 0; $i < 7; $i++)
		{	
			if (!isset($arData[0]['records'][date(j, $day)]))
			{
				$arData[0]['records'][date(j, $day)] = array('orders'	=> '0',
															 'total'	=> '0',
															 'avg_total'=> '0',
															 'day'		=> date('d', $day),
															 'month'	=> date('m', $day),
															 'year'		=> date('Y', $day),
															 'tstamp' 	=> $day);
			}	

			$arData[0]['records'][date(j, $day)]['label'] = date('d.m.Y', $day);	
			
			$day += 86400;
		}
		
		$arData[0]['firstdayofweek'] = $firstDayofWeek;
		$arData[0]['lastdayofweek'] = $lastDayofWeek;
		
		$arData[0]['label'] = "KW ".date('W', $firstDayofWeek)." ".date('Y', $firstDayofWeek);	
		
		$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
		
		if (isset($params['relatedpoint']) && is_numeric($params['relatedpoint']))
		{
			$arRelatedData = $this->getWeek($params['relatedpoint']);
			
			$this->addSorting($arRelatedData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
			$arData[] = $arRelatedData[0];
		}

		return $arData;		
	}
	
	
	
	/**
	 * Rückgabe der Statistik auf einen Tag bezogen
	 * @internal Bezug -> Stunde 
	 * @param string
	 * @return array
	 */
	public function getDay($point = 0, $params = array())
	{
			
		if ($point == 0)
		{
			$day = time();
		}
		else if ($point == -1)
		{
			$day = time() - 86400;
		}
		
		$arData[0]['records'] = $this->db->fetchAssoc("SELECT 
														    COUNT(*) AS orders,
															SUM( `price_gesamt` ) AS total,
															AVG( `price_gesamt` ) AS avg_total,
															HOUR( `cdate` ) AS hour, 
															DAY ( `cdate` ) AS day, 
															MONTH( `cdate` ) AS month, 
															YEAR( `cdate` ) AS year,
															HOUR( `cdate` ) AS tstamp
													 FROM 
													  		`".WPSG_TBL_ORDER."`
													 WHERE  
													  		".$this->getSqlWhere('validOrder')." AND 
													  		YEAR( `cdate` ) = '".date('Y', $day)."' AND 
										  					MONTH ( `cdate` ) = '".date('m', $day)."' AND 
										  					DAY (`cdate`) = '".date('d', $day)."'
													 GROUP BY 
													 		year, month, day, hour
													 ORDER BY 
													 		hour ASC
													 ", "hour");
		
		$daytime = strtotime(date('d.m.Y 00:00:00', $day));
		
		$arData[0]['year'] = date('Y', $daytime);
		$arData[0]['month'] = date('m', $daytime);
		$arData[0]['day'] = date('d', $daytime);
		
		$arData[0]['label'] = date('d.m.Y', $daytime);
		
		for ($i = 0; $i < 24; $i++)
		{	
			if (!isset($arData[0]['records'][date('G', $daytime)]))
			{
				$arData[0]['records'][date('G', $daytime)] = array( 'orders' 	=> '0',
																	'total'	 	=> '0',
																	'avg_total'	=> '0',
																	'hour'	 	=> date('G', $daytime),
																	'day'	 	=> date('d', $daytime),
																	'month'	 	=> date('m', $daytime),
																	'year'	 	=> date('Y', $daytime),
																	'tstamp'	=> date('G', $daytime));
			}	
			
			$arData[0]['records'][date('G', $daytime)]['label'] = date('G', $daytime);
			
			$daytime += 3600;
		}
		
		$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
		
		if (isset($params['relatedpoint']) && is_numeric($params['relatedpoint']))
		{
			$arRelatedData = $this->getDay($params['relatedpoint']);
			
			$this->addSorting($arRelatedData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
			$arData[] = $arRelatedData[0];
		}
		
		return $arData;
	}
	
	/**
	 * Rückgabe der Statistik bezogen auf einen benutzerdefinierten Zeitraum
	 * @internal Bezug -> Tag 
	 * @param string
	 * @return array
	 */
	public function getCustomRange($point = 0, $params = array())
	{	

		$arYears = array();
		$arMonths = array();
		$arWeeks = array();
		$arDays = array();
		
		if ($params['oStart'] > 0 && $params['oEnd'] > 0)		
		{
			$start = $params['oStart'];
			$end = $params['oEnd'];	
		}
		else
		{
			$start = wpsg_fieldarray_todate($_REQUEST['filter']['day'][0]);
			$end = wpsg_fieldarray_todate($_REQUEST['filter']['day'][1]);
		}
		
		$daycount = $start;

		while ($daycount <= $end)
		{
			$week = date('W', $daycount);
			
			if ($week[0] == 0 && strlen($week) == 2)
			{
				$week = str_replace('0', '', $week);
			}
			
			$year = date('Y', $daycount);	
			$month = date('n', $daycount);
			$day = date('j', $daycount);
			
			if (!in_array($year.'-'.$week, $arWeeks))
			{
				$arWeeks[$year.'-'.$week] = array('day'		=> $day,
				                    			  'week' 	=> $week,
								        	  	  'year' 	=> $year,
											  	  'month'	=> $month);
			}
			
			if (!in_array($year.'-'.$month, $arMonths))
			{

				$arMonths[$year.'-'.$month] = array('month' => $month,
											    	'year'  => $year);

			}
			
			if (!in_array($year.'-'.$month.'-'.$day, $arDays))
			{
				$arDays[$year.'-'.$month.'-'.$day] = array('day'   => $day,
														   'month' => $month,
											    		   'year'  => $year);
			}
			
			if (!in_array($year, $arYears))
			{
				$arYears[$year] = array('year' => $year);
			}

			
			$daycount += 86400;
		}
		
		if (count($arDays) <= 1)
		{
			$arData['template'] = 'day';
			
			$arData[0]['label'] = __('Statistikdaten ', 'wpsg').' '.date('d.m.Y', $start);
			
			$day = $start;
			
			$arData[0]['records'] = $this->db->fetchAssoc("	 SELECT 
																    COUNT(*) AS orders,
																	SUM( `price_gesamt` ) AS total,
																	AVG( `price_gesamt` ) AS avg_total,
																	HOUR( `cdate` ) AS hour, 
																	DAY ( `cdate` ) AS day, 
																	MONTH( `cdate` ) AS month, 
																	YEAR( `cdate` ) AS year,
																	CAST( `cdate` AS DATE ) AS dateid,
																	HOUR( `cdate` ) AS tstamp
															  FROM 
															  		`".WPSG_TBL_ORDER."`
															  WHERE 
															  		".$this->getSqlWhere('validOrder')." AND  
															  		`cdate`	>= '".date('Y-m-d 00:00:00', $start)."' AND 
														  			`cdate` <= '".date('Y-m-d 23:59:59', $end)."'
															  GROUP BY 
															  		year, month, day, hour
															  ORDER BY 
															  		hour DESC
															  ", "hour");
			
			$daytime = strtotime(date('d.m.Y 00:00:00', $day));
		
			$arData[0]['year'] = date('Y', $daytime);
			$arData[0]['month'] = date('m', $daytime);
			$arData[0]['day'] = date('d', $daytime);
			
			for ($i = 0; $i < 24; $i++)
			{	
				if (!isset($arData[0]['records'][date('G', $daytime)]))
				{
					$arData[0]['records'][date('G', $daytime)] = array( 'orders' 	=> '0',
																		'total'	 	=> '0',
																		'avg_total'	=> '0',
																		'hour'	 	=> date('G', $daytime),
																		'day'	 	=> date('d', $daytime),
																		'month'	 	=> date('m', $daytime),
																		'year'	 	=> date('Y', $daytime),
																		'tstamp' 	=> date('G', $daytime));
				}	
				
				$arData[0]['records'][date('G', $daytime)]['label'] = date('G', $daytime);
				
				$daytime += 3600;
			}
			
			$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
		}
		//Tage render
		else if (count($arDays) <= 50)
		{
	
			$arData['template'] = 'month';
			
			$arData[0]['label'] = __('Statistikdaten ', 'wpsg').' '.date('d.m.Y', $start).' - '.date('d.m.Y', $end);
			
			$arData[0]['min'] = $start;
			$arData[0]['max'] = $end;
			
			$arData[0]['records'] = $this->db->fetchAssoc("	 SELECT 
																    COUNT(*) AS orders,
																	SUM( `price_gesamt` ) AS total,
																	AVG( `price_gesamt` ) AS avg_total,
																	DAY( `cdate`) AS day, 
																	MONTH( `cdate` ) AS month, 
																	YEAR( `cdate` ) AS year,
																	CAST( `cdate` AS DATE ) AS dateid,
																	UNIX_TIMESTAMP(`cdate`) AS tstamp
															  FROM 
															  		`".WPSG_TBL_ORDER."`
															  WHERE 
															  		".$this->getSqlWhere('validOrder')." AND 
															  		`cdate`	>= '".date('Y-m-d 00:00:00', $start)."' AND 
														  			`cdate` <= '".date('Y-m-d 23:59:59', $end)."'
															  GROUP BY 
															  		year, month, day
															  ORDER BY 
															  		year DESC
															  ", "dateid");

			$daycount = $start;
	
			while ($daycount <= $end)
			{
				
				$dateid = date('Y-m-d', $daycount);
				
				if (!isset($arData[0]['records'][$dateid]))
				{
					$arData[0]['records'][$dateid] = array(	'orders'	=> '0',
															'total'		=> '0',
															'avg_total'	=> '0',
															'day'		=> date('d', $daycount),
															'month'		=> date('m', $daycount),
															'year'		=> date('Y', $daycount),
															'tstamp'	=> $daycount);
				}
				
				$arData[0]['records'][$dateid]['label'] = date('d.m.Y', $daycount);

				$daycount += 86400;
			}
			
			$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
		}
		//Wochen rendern
		else if (count($arWeeks) <= 15)
		{
			
			$arData['template'] = 'quarter';
			
			$arData[0]['label'] = __('Statistikdaten ', 'wpsg').' '.date('d.m.Y', $start).' - '.date('d.m.Y', $end);
			
			$arData[0]['records'] = $this->db->fetchAssoc(" SELECT 
															    COUNT(*) AS orders,
																SUM( `price_gesamt` ) AS total,
																AVG( `price_gesamt` ) AS avg_total,
																DAY( `cdate`) AS day,
																WEEK ( `cdate`, 3) AS week, 
																MONTH( `cdate` ) AS month, 
																YEAR( `cdate` ) AS year,
																CONCAT(YEAR( `cdate` ),'-', WEEK( `cdate`, 3) ) AS dateid,
																UNIX_TIMESTAMP(`cdate`) AS tstamp
														  FROM 
														  		`".WPSG_TBL_ORDER."`
														  WHERE 
														  		".$this->getSqlWhere('validOrder')." AND 
														  		`cdate`	>= '".date('Y-m-d 00:00:00', $start)."' AND 
														  		`cdate` <= '".date('Y-m-d 23:59:59', $end)."'
														  GROUP BY 
														  		year, month, week
														  ORDER BY 
														  		dateid ASC
														  ", "dateid");
			
			
			
			foreach ($arWeeks as $week)
			{
				
				if (!array_key_exists($week['year'].'-'.$week['week'], (array)$arData[0]['records']))
				{
					$arData[0]['records'][$week['year'].'-'.$week['week']] = array(	'orders'	=> '0',
																					'total'		=> '0',
																					'avg_total'	=> '0',
																					'day'		=> $week['day'],
																					'week'		=> $week['week'],
																					'year'		=> $week['year'],
																					'month'		=> $week['month'],
																					'tstamp'	=> mktime(0, 0, 0, $week['month'], $week['day'], $week['year']));

				}
				
				$arData[0]['records'][$week['year'].'-'.$week['week']]['label'] = __('KW', 'wpsg').' '.$week['week'].' '.$week['year'];
				
			}	
			
			$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
		}
		//Monate rendern
		else if (count($arMonths) <= 36)
		{

			$arData['template'] = 'year';
			
			$arData[0]['min'] = mktime(0, 0, 0, date('m', $start), 1, date('Y', $start));
			$arData[0]['max'] = mktime(0, 0, 0, date('m', $end), wpsg_getDaysofMonth(date('m', $end), date('Y', $end)), date('Y', $end));
			
			$arData[0]['label'] = __('Statistikdaten ', 'wpsg').' '.date('d.m.Y', $start).' - '.date('d.m.Y', $end);
			
			$arData[0]['records'] = $this->db->fetchAssoc(" SELECT 
																COUNT(*) AS orders,
																SUM(`price_gesamt`) AS total, 
																AVG( `price_gesamt` ) AS avg_total,
																MONTH(`cdate`) AS month, 
																YEAR(`cdate`) AS year,
																CONCAT(YEAR(`cdate`), '-', MONTH(`cdate`)) AS dateid,
																UNIX_TIMESTAMP(`cdate`) AS tstamp
														  FROM 
														  		`".WPSG_TBL_ORDER."`
														  WHERE 
														  		".$this->getSqlWhere('validOrder')." AND 
														  		`cdate`	>= '".date('Y-m-d 00:00:00', $start)."' AND 
													  			`cdate` <= '".date('Y-m-d 23:59:59', $end)."'
														  GROUP BY 
														  		year, month
														  ORDER BY 
														  		tstamp ASC
														   ", "dateid");
			
			foreach ($arMonths as $index => $month)
			{
				
				if (!array_key_exists($index, $arData[0]['records']))
				{
					$arData[0]['records'][$index] = array(	'orders' 	=> '0',
													   		'total'	 	=> '0',
															'avg_total'	=> '0',
													   		'month'	 	=> $month['month'],
													   		'year'	 	=> $month['year'],
															'tstamp'	=> mktime(0, 0, 0, $month['month'], 1, $month['year']));
				}

				$arData[0]['records'][$index]['label'] = date_i18n('F', mktime(0, 0, 0, $month['month'], 1, $month['year'])).' '.$month['year'];
				$arData[0]['records'][$index]['tick'] = date_i18n('M', mktime(0, 0, 0, $month['month'], 1, $month['year']));
						
			}
			
			$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));
			
		}
		//Jahre rendern
		else
		{
			
			$arData['template'] = 'all';
			
			$arData[0]['min'] = $start;
			$arData[0]['max'] = $end;
			
			$arData[0]['label'] = __('Statistikdaten ', 'wpsg').' '.date('d.m.Y', $start).' - '.date('d.m.Y', $end);
			
			$arData[0]['records'] = $this->db->fetchAssoc(" 
					SELECT 
						COUNT(*) AS orders,
						SUM(`price_gesamt`) AS total, 
						AVG( `price_gesamt` ) AS avg_total,
						YEAR(`cdate`) AS year,
						UNIX_TIMESTAMP( `cdate` ) AS tstamp
				  	FROM 
				  		`".WPSG_TBL_ORDER."`
				  	WHERE 
				  		".$this->getSqlWhere('validOrder')." AND 
				  		`cdate`	>= '".date('Y-m-d 00:00:00', $start)."' AND 
			  			`cdate` <= '".date('Y-m-d 23:59:59', $end)."'
				  	GROUP BY 
				  		year
				  	ORDER BY 
				  		year ASC
				   ", "year");
			
			foreach ($arYears as $index => $year)
			{
				
				if (!array_key_exists($index, $arData[0]['records']))
				{
					
					$arData[0]['records'][$index] = array(	'orders' 	=> '0',
													  		'total'		=> '0',
															'avg_total'	=> '0',
													   		'year'		=> $year['year'],
															'tstamp'	=> mktime(0, 0, 0, 1, 1, $year['year']));
					
				}	
				
				$arData[0]['records'][$index]['label'] = $year['year'];
			}
			
			$this->addSorting($arData[0], $params['order'], ((!wpsg_isSizedString($params['sort']))?'tstamp':$params['sort']));

		}
		
		return $arData;

	}
	
}

?>