<?php

/**
* @desc This report displays the browser trends
*/

$reports["_BROWSER_TRENDS"] = Array(
	"ClassName" => "BrowserTrends", 
	"Category" => "_CLIENT_SYSTEM", 
	"icon" => "images/icons/32x32/clientbrowsertrends.png",
	"Options" => "daterangeField,profileselector,country,trafficsource,period,displaymode,limit",
	"Filename" => "browser_trends",
	"Distribution" => "Premium",
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"Order" => 4,
	"EmailAlerts" => false,
	"Update" => false,
	"canAggregate" => true
);

class BrowserTrends extends Report {
	
	function Settings() {
		global $cnames;
		$this->DefaultDisplay = "areachart";
		$this->DisplayModes = "table,linechart,areachart";
		$this->help = "";
		$this->displayReportButtons = false;
		$this->remove_outputmodes = array("xml");
		if(empty($this->period)){ $this->period = '_DAYS';  }		
		$this->chartoptions = array("stacked_graph_style" => "stack", "stacked_showcontrols" => true, "showlegend" => true);

		if(isset($_REQUEST["country_name"])){
			# country code unknown check on name..
			$flip = $cnames;
			$flip = array_flip($flip);
			$this->country = $flip[$_REQUEST["country_name"]];			
		}

		if(!empty($_REQUEST["country"])) {
			$this->country = $_REQUEST["country"];
		}
		if (!empty($this->country)) {			
			$this->addlabel = $cnames[$this->country];
		}
		$this->sort=false;
		
		// this is for the aggregation framework
		if (isset($this->limit)) {
			$this->limit_per_day = $this->limit;	
		} else {
			$this->limit_per_day = 10;
		}
	}
	
	function GetReportData() {
		
		$data = $this->rawGetReportData();		
		$data = $this->ConvertData($data);
		//dump($this->columnDefinitions);
		//dump($data);
		return $data;	

	}

	function rawGetReportData() {
		global $reports;
		$r = new $reports["_BROWSER_VERSIONS"]["ClassName"]();
		# Reset to default report settings
		if (!empty($this->country)) {
			$r->country = $this->country;
			$r->Settings();
		}
		//$r->sort_order = false;
		$r->sort = false;
		$r->sort_key = 0;
		$r->key_col = 0;

		$r->dataCollectType = "days";
		$r->createDataFiles($this->from,$this->to);	
		$d = $r->getTrendDataFromFiles($r->dataFiles($this->from,$this->to));
		//dump($d);
		//exit();
		$data = [];
		foreach($d as $k => $v){
			$l = 0;
			if(empty($v)){ continue; }
			foreach($v as $val){
				if ($this->limit < 50 && $l > ($this->limit * 5)){
					break;
				} else if ($this->limit >= 50 && $l > ($this->limit * 2)){
					break;
				}
				$timestamp = mktime(0,0,0,substr($k,4,-2),substr($k,6,7),substr($k,0,4));
				//$browser = $val[0] . " " . $val[1];
				$browser = $val[0];
				$visits = $val[2];
				
				# Define the chosen period / time unit
				if ($this->period == '_DAYS') { 
					$format = "D, m/d/Y";
					$date = date($format,$timestamp);
					
				} else if ($this->period == '_WEEKS') {
					$format = "Y-#W";
					$date = date($format,$timestamp);
					$date = str_replace("#","W",$date);
				} else if ($this->period == '_MONTHS') {
					$format = "M Y";
					$date = date($format,$timestamp);
				}				
				
				if(isset($data[$browser][$date])) {				
					$data[$browser][$date] = $data[$browser][$date] + $visits;
				} else {	
					$data[$browser][$date] = $visits;
				}
				$l ++;
			}
		}
		
		$temp_d = [];
		foreach($data as $browser => $v){
			$temp_d[$browser] = array_sum($v);
		}
		arsort($temp_d);
		
		$final = [];
		$i = 0;
		$l = 0;
		//dump($this->limit);
		//dump($temp_d);
		foreach($temp_d as $browser => $v){
			if($l > $this->limit){
				break;
			}			
			foreach($data[$browser] as $date => $visits){
				$final[$i][0] = $date; 
				$final[$i][1] = $browser; 
				$final[$i][2] = $visits; 
				$i ++;
			}			
			$l ++;
		}
		//dump($final);
		return $final;
	}
	function ConvertData($data = "") {
		//if(empty($data)) { $data = $this->GetReportData(); }
		
		# transform the data array to a column for each serie
		$data = $this->seriesToColumns($data);
		if(!$data){
			return $this->EmptyTrendData();
		}		

		foreach($data['fields'] as $key => $countrycode) { // Convert country codes to countries
			if(isset($cnames[$countrycode])) {
				$data['fields'][$key] = $cnames[$countrycode];
				$this->columnDefinitions[] = array("Label" => $cnames[$countrycode] );
			} else {
				$this->columnDefinitions[] = array("Label" => $countrycode );
			}
		}
		$this->setupColumnDefinitions();
		
		# create an empty seed array with the right dimensions
		$ncols = count($data['fields']);
		$nrows = $this->dateNumber($this->from, $this->to, $this->period);
		
		$seed_data = $this->newReportArray($nrows, $ncols);
		# add a date to he first value of each row.
		$seed_data = $this->AddDateToZeroArray($seed_data);
		
		# merge the actual results with the seed_data array
		foreach ($data['data'] as $key => $val) {
			if($this->period == '_WEEKS'){
				$dparts = explode("-",$key);
				$year = mktime(0,0,0,1,1,$dparts[0]);
				$week = str_replace("W","",$dparts[1]);
			
				$timestamp = (86400 * 7 * $week) + $year;		
			} else {
				$timestamp = strtotime($key);
			}
			
			$day_id = $this->dateNumber($this->from,$timestamp, $this->period);
			
			for ($i=0;$i<$ncols;$i++) {
				if (isset($val[$i])) {
					$seed_data[$day_id][$i] = $val[$i];
				}
			}		
		}	
		ksort($seed_data);
		
		# now make sure the date column is properly filled
		foreach($seed_data as $key => $value) {
			$value[0] = $this->getFormatDate($this->period,($this->from+(($key)*$this->getSeconds($this->period))));
			$seed_data[$key] = $value;
		}
		
		return $seed_data;
	}

	function DisplayReport() {
		global $db, $qd;
		
		if(empty($this->displaymode)) { $this->displaymode = $this->DefaultDisplay; }
		
		# get the data from the database
		$data = $this->GetReportData();
		
		//$data = $this->ConvertData($data);
		if (!empty($this->addlabel)) {
			$this->addlabel .= " | ";
		}
		$this->addlabel .= _GROUPED_BY . " ".constant($this->period);
		$this->ReportHeader();

		if(empty($data)){
			echoWarning(_NO_DATA_TO_DISPLAY, "margin:5px;");
			return false;
		}
		
		if($this->displaymode == 'table') {
			$this->Table($data);
		} elseif($this->displaymode == 'areachart') {
			$this->StackedAreaChart2($data);

		} elseif($this->displaymode == 'linechart') {
			$this->LineChart($data);
		}
	}

	// function AggregateFixData($data,$np) {
	// 	// we need to get some totals and limit that to the top this->limit for each day
	// 	$totals = [];
	// 	foreach($data as $row) {
	// 		foreach($row as $)
	// 	}
	// }
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		# not using datafiles yet
		return false;		
	}
}
?>