<?php

/**
* @desc This report displays 3 graphs where you get an overview of the trends.
*/

$reports["_TREND_ANALYSIS"] = Array(
	"ClassName" => "TrendAnalysis", 
	"Category" => "_VISITOR_TRENDS", 
	"icon" => "images/icons/32x32/trendsoverview.png",
	"Options" => "daterangeField,profileselector,trafficsource,source,period,displaymode,human",
	"Filename" => "trend_analysis",
	"Distribution" => "Standard",
	"Order" => 4,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
);

class TrendAnalysis extends Report {

	function Settings() {
		$this->DefaultDisplay = "barlinechart";
		$this->DisplayModes = "barlinechart,table";		
		$this->displayReportButtons = false;
		$this->allowDateFormat = false;
		$this->dataCollectType = "days";
		
		$this->source = urldecode($this->source);
		$this->columnDefinitions[] = array("Label" => _DATE);
		
		if(!empty($this->source)) {
			if (!empty($this->addlabel)) { $this->addlabel .= " | "; }
			$this->addlabel .= ucwords($this->sourcetype).": {$this->source}";
			$this->columnDefinitions[] = array("Label" => _VISITS, "chart" => "bar");
		} else {
			$this->columnDefinitions[] = array("Label" => _VISITORS, "chart" => "bar");
		}		
		$this->columnDefinitions[] = array("Label" => _PAGEVIEWS, "chart" => "bar");
		$this->columnDefinitions[] = array("Label" => _TREND, "chart" => "line");
		$this->columnDefinitions[] = array("Label" => _PAGE." "._TREND, "chart" => "line");
		$this->sort = false;

		//$this->barchartcolors[0] = "#9ECAE1";
		$this->barchartcolors[0] = "#6baed6";
		$this->barchartcolors[1] = "#FF7F0E";
		//$this->barchartcolors[0] = "#9ECAE1";
		//$this->barchartcolors[1] = "#1F77B4";
		
		$this->barchartcolors[2] = "#001F3F";
		$this->barchartcolors[3] = "#FF4F0F";
	}
	
	function GetReportData() {
		global $reports;
		$data = [];
		if( empty($this->sourcetype) ) {			
			$this->sourcetype = "page";
		}
		
		if ($this->sourcetype == "page") {
			$r = new $reports["_TOP_PAGES"]["ClassName"]();
			$r->searchmode= "equals";
		}else if ($this->sourcetype == "keyword") {
			$r = new $reports["_TOP_KEYWORDS"]["ClassName"]();
			$r->searchmode= "equals";
		}else if ($this->sourcetype == "referrer") {
			$r = new $reports["_TOP_REFERRERS"]["ClassName"]();
			$r->searchmode= "equals";
		}
		
		if(!empty($this->source)) {
			$r->search = $this->source;
		} else {
			# Use Visitor Trends and return data for that only..
			if ($this->period == '_MONTHS') {
				$source_report = "_VISITORS_PER_MONTH";
			} else  {
				$source_report = "_VISITORS_PER_DAY";
			}

			$r = new $reports[$source_report]["ClassName"]();
			$r->from = $this->from;
			$r->to = $this->to;
			$d = $r->getReportData();
			$data = [];

			foreach($d as $k => $v){
				$timestamp = strtotime($v[0]);

				if($timestamp < $this->from || $timestamp > $this->to){
					continue;
				}

				# Define the chosen period / time unit
				if ($this->period == '_DAYS') { 
					//$format = implode($this->profile->dateFormat);
					//$date = date($format,$timestamp);
					$date = LogaDate($this->profile->dateFormat, $timestamp);
					
				} else if ($this->period == '_WEEKS') {
					$year = date("Y",$timestamp);
					$month = date("M",$timestamp);
					$week = date("W",$timestamp);

					if($month == "Dec" && $week == "01"){
						$year ++;
					}
					$date = "{$year}-W{$week}";
				} else if ($this->period == '_MONTHS') {
					//$format = "M Y";
					//$date = date($format,$timestamp);
					$date = LogaDate(array("format1" => "M", "seperator1" => " ", "format2" => "Y"), $timestamp);
				} else { # Fail period
					//$format = implode($this->profile->dateFormat);
					//$date = date($format,$timestamp);
					$date = LogaDate($this->profile->dateFormat, $timestamp);
				}

				if(empty($data[$date][1])){
					$data[$date][1] = 0;
					$data[$date][2] = 0;
				}	

				$data[$date][1] = $data[$date][1] + $v[1];
				$data[$date][2] = $data[$date][2] + $v[2];
			}

			$data = $this->ConvertData($data);	
			//dump($data);		
			return $data;
		}
		
		$r->dataCollectType = "days";
		$r->createDataFiles($this->from,$this->to);
		$d = $r->getTrendDataFromFiles($r->dataFiles($this->from,$this->to));
		
		$data = [];
		foreach($d as $k => $v){
			$l = 0;
			if( empty($v)) { 
				//zerofill this sucker
				$timestamp = mktime(0,0,0,substr($k,4,-2),substr($k,6,7),substr($k,0,4));
				$v = array(0,0,0,0);				
				
			}
			foreach($v as $val){		
				if ($this->limit < 50 && $l > ($this->limit * 5)){
					break;
				} else if ($this->limit >= 50 && $l > ($this->limit * 2)){
					break;
				}
				if(strlen($k > 7)){
					$timestamp = mktime(0,0,0,substr($k,4,-2),substr($k,6,7),substr($k,0,4));
				} else {
					continue;
				}

				if($timestamp < $this->from || $timestamp > $this->to){
					continue;
				}

				# Define the chosen period / time unit
				if ($this->period == '_DAYS') { 
					$format = implode($this->profile->dateFormat);
					$date = date($format,$timestamp);
					
				} else if ($this->period == '_WEEKS') {
					$year = date("Y",$timestamp);
					$month = date("M",$timestamp);
					$week = date("W",$timestamp);

					if($month == "Dec" && $week == "01"){
						$year ++;
					}
					$date = "{$year}-W{$week}";
				} else if ($this->period == '_MONTHS') {
					$format = "M Y";
					$date = date($format,$timestamp);
				} else { # Fail period
					$format = implode($this->profile->dateFormat);
					$date = date($format,$timestamp);
				}	
					
				
				$visits = $val[1];
				$views = $val[2];
				
				if(isset($data[$date][1])) {				
					$data[$date][1] = $data[$date][1] + $visits;
				} else {	
					$data[$date][1] = $visits;
				}

				if(isset($data[$date][2])) {				
					$data[$date][2] = $data[$date][2] + $views;
				} else {	
					$data[$date][2] = $views;
				}
				$l ++;
		
			}
		}
		
		$data = $this->ConvertData($data);		
		return $data;
	}
	
	function ConvertData($merge = []) {
		$n = count(@$merge);
		
		if ($n == 0) {
			return [];
		}
		
		reset($merge);
		$i = 1;
		//dump($merge);

		foreach($merge as $day => $row) {		
			$traffic_x[$i] = $i; // trend line for total traffic

			$traffic_y1[$i] = $row[1];
			$traffic_y2[$i] = $row[2];

			//begin calculation
			$traffic_xy1[$i] = $traffic_x[$i] * $row[1];
			$traffic_xy2[$i] = $traffic_x[$i] * $row[2];

			$traffic_xsq[$i] = $traffic_x[$i] * $traffic_x[$i];

			$i++;
		}

		// $n has already been vetted to be <> 0, so we can divide by $n with impunity here
		$traffic_a_part1=array_sum($traffic_xy1)-((array_sum($traffic_x)*array_sum($traffic_y1))/$n);
		$traffic_a_part2=array_sum($traffic_xy2)-((array_sum($traffic_x)*array_sum($traffic_y2))/$n);

		// array_sum($x) isn't vetted, so we need to protect from a division by 0 here.
		$traffic_a1=@($traffic_a_part1/(array_sum($traffic_xsq)-(1/$n)*(array_sum($traffic_x)*array_sum($traffic_x))));
		$traffic_a2=@($traffic_a_part2/(array_sum($traffic_xsq)-(1/$n)*(array_sum($traffic_x)*array_sum($traffic_x))));

		$traffic_b1=(array_sum($traffic_y1)/$n)-($traffic_a1 * (array_sum($traffic_x)/$n));
		$traffic_b2=(array_sum($traffic_y2)/$n)-($traffic_a2 * (array_sum($traffic_x)/$n));
		//now we have eveything to plot our 2 regression lines

		//add plot point for trend			
		$i=0;
		foreach($merge as $day => $row) {
		
			foreach($row as $skey => $sval) {
			
				switch ($skey) {
					case 1:
						$traffic_regval[$i][0]=($traffic_a1 * $traffic_x[($i+1)]) + $traffic_b1;
						break;
					case 2:
						$traffic_regval[$i][1]=($traffic_a2 * $traffic_x[($i+1)]) + $traffic_b2;
						break;
				}
			}
			
			$i++;
		}
		
		$looptime = getmicrotime();
		
		reset($merge);
		$i = 0;
		while (list ($day, $row) = each ($merge)) {
						
			$graphdata[$i][0] = $day;
			$graphdata[$i][1] = $row[1];
			$graphdata[$i][2] = $row[2];
			if($traffic_regval[($i)][0] <= 0) {
				$graphdata[$i][3] = 0;
			} else {
				$graphdata[$i][3] = round($traffic_regval[($i)][0], 2);
			}
			if($traffic_regval[($i)][1] <= 0) {
				$graphdata[$i][4] = 0;
			} else {
				$graphdata[$i][4] = round($traffic_regval[($i)][1], 2);
			}
			
			
			$i++;
		}
		
		return $graphdata;
	}
	
	function DisplayReport() {
		global $sqlst,$reports, $qd, $n, $cdate, $cnames, $databasedriver;
		
		$data = $this->GetReportData();

		//$data = $this->ConvertData($data);
		
		if(empty($data)){
			$this->ReportHeader();
			echoWarning( _NO_DATA_TO_DISPLAY, "margin:10px;");
			return false;
		}
		
		if (!empty($this->source)) {
			$dlabel = _VISITS;
		} else {
			$dlabel = _UNIQUE_VISITORS;
		}

		if($this->displaymode == 'barlinechart') {
			$this->ReportHeader();
			$this->MultiChart($data);
			
		} else {
			$this->ReportHeader();
			$this->Table($data);
		}
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		# it's not going to use datafiles.
		return false;		
	}
	
	function DisplaySparkline() {
        $data = $this->GetReportData();
		//$data = $this->ConvertData($data);
        $this->Sparkline($data);
    }
}
?>