<?php

/**
* @desc This report displays a overview of your top keywords
*/
$reports["_CONTENT_INFOGRAPHIC"] = Array(
	"ClassName" => "ContentInfographic", 
	"Category" => "_INFOGRAPHICS", 
	"icon" => "images/icons/32x32/trendsoverview.png",
	"Options" => "daterangeField,profileselector",
	"Filename" => "content_infographic",
	"Distribution" => "Standard",
	"Order" => 2,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"hidden" => true,
	"EmailAlerts" => false,
	"Update" => false
);

class ContentInfographic extends Report {
	var $ndays;
	
	function UpdateStats($from = '', $to = '',$print = 2) {
  		return false;
 	}
 	
	function Settings(){
		if(date("ymd",time()) == date("ymd",$this->to)){
			$this->to = $this->to - 86400;
		}
	
		$this->from = mktime(0,0,0,date("m",$this->to),date("d",$this->to)-6,date("Y",$this->to));
		$this->limit = 10;
		
		$calc = round(($this->to - $this->from) / 86400);
		$this->ndays = $calc;
	}
	
	
	function DisplayReport() {
		global $reports;
		$this->ReportHeader();

		$required_reports = array(
			"_TOP_PAGES",
			"_PAGE_TRENDS",
			"_BOUNCE_RATE",
			"_BROWSER_BREAKDOWN",
			"_ERROR_REPORT",
			"_VISITORS_PER_DAY",
			"_NEW_VS_RETURNING"
		);

		$missing = "";
		foreach($required_reports as $c) {
			if(empty($reports[$c])){
				$missing .= "- ". constant($c) ." -";
			}
		}
		if(!empty($missing) && CheckForSubscriptionsUsage()){
			echoNotice(_MISSING_TO_SEE_COMPLETE_REPORT. ":<br/>$missing<br/><a class='subscription_report' style='cursor:pointer;'>"._OPEN_SUBSCRIPTION_DIALOG."</a>","margin:10px; text-align:center;");
		}
		
		$averages = $this->AvgVisitorsBlockData();
		
		$errors = $this->ErrorsData();
		
		if(empty($reports["_TOP_PAGES"])){
			$pages = [];
			$tpdata = [];
		} else {
			$tp = new $reports["_TOP_PAGES"]["ClassName"]();
			$tp->label = _TOP_PAGES;
			$tp->from = $this->from;
			$tp->to = $this->to;
			$tpdata = $tp->GetReportData();
			
			# Week before this week
			$pages = [];
			$tp->to = $this->from - 1;
			$tp->from = ($tp->to - (86400*7));	
			$i = 0;
			$tp_largest_hit = 0;

			$ptr = new $reports["_PAGE_TRENDS"]["ClassName"]();
			$ptr->displayheader = false;
			$ptr->searchmode = "equals";
			
			if(!empty($tpdata)){
				while($i < 10){
					if($tpdata[$i][2] > $tp_largest_hit){
						$tp_largest_hit = $tpdata[$i][2];
					}
				
					$page  = explode("##",$tpdata[$i][0]);
					$tpdata[$i][0] = $page[0];

					$pages[$tpdata[$i][0]]["hits"] = $tpdata[$i][1];
					$tp->searchmode = "equals";
					$tp->search = $tpdata[$i][0]; 
					$pagedata = $tp->GetReportData();
					
					if(isset($pagedata[0][1])){
						$pages[$tpdata[$i][0]]["diff"] = $pagedata[0][1];
					} else {
						$pages[$tpdata[$i][0]]["diff"] = 0;
					}
										
					$ptr->search = $tpdata[$i][0]; 
					$ptr->from = $tp->from;	
					$ptr->to = $this->to;
					$ptrdata = $ptr->GetReportData();
					//$ptrdata = $ptr->ConvertData($ptrdata);
					$datepoints = [];
					$sparkpoints = [];
					$ii = 0;
					//dump($ptrdata);
					foreach($ptrdata as $k => $v){
						$datepoints[] = "$ii: '{$v[0]}'";
						$sparkpoints[] = $v[$i + 1];
						$ii ++;
					}
					$pages[$tpdata[$i][0]]["sparkpoints"]["date"] = $datepoints;
					$pages[$tpdata[$i][0]]["sparkpoints"]["vals"] = $sparkpoints;
					$i ++;
				}
			}
		}
		
		if(empty($reports["_BOUNCE_RATE"])){
			$bounce = [];
		} else {
			$br = new $reports["_BOUNCE_RATE"]["ClassName"]();
			$br->label = _BOUNCE_RATE;
			$br->from = $this->from;
			$br->to = $this->to;
			$br->displaymode = "pie";
			$br->page = "/";
			$br->fileNameExpension = ".".urlencode($br->page);
			$br->legendlabelstring = "'<span style=\"float:left;\">%t <br> %v</span>'"; 
			$br->legendstyle['container'] = "width: 95%; float: left; margin: 15px 0px 0px 0px;";
			$br->legendstyle['legend'] = "width: 100%; display: block; clear: both;"; 
			$bounce = $br->GetReportData();
			//dump($bounce);
		}
		echo "<div id='printer' class='page' style='width:600px;'>";
		?>		
		<div class="infograph-wrapper content-infograph-wrapper">
			<div class="infograph-row">
				<div class="visitor-block">
					<div class="average-visitors">
						<h1><?php echo $averages["vpd"]; ?></h1>
						<p><?php echo _AVG_VISITORS; ?><br><?php echo _PER_DAY; ?></p>
					</div>
					<div class="returning-new">
						<div class="rotated">
							<span><strong><?php echo $averages["returning"]; ?>%</strong> <?php echo _RETURNING; ?><br><strong><?php echo $averages["new"]; ?>%</strong> <?php echo _NEW; ?></span>
						</div>
					</div>
					<div style="clear:both;"></div>
					<div class="average-visitors-trend">
						<h1><font color="<?php echo $averages["trend"]["color"]; ?>"><?php echo "{$averages["trend"]["data"]}"; ?></font></h1>
						<p>
							<?php echo _COMPARED_TO_LAST_WEEK; ?>
						</p>
					</div>
					<div class="returning-new">				
						<div class="">
							<span>
								<?php echo $averages["trendsmile"]; ?>
								<?php echo $averages["trendarrow"]; ?>
							</span>
						</div>
					</div>
				</div>
				<div class="trend-block">
					<h1><?php echo _TOP_PAGES; ?></h1>
					<div class="infograph-graph" style="height:303px;">
						<?php if(!empty($tp)){
						$bubbledata = [];
						
						foreach($tpdata as $k => $val){
							if($val[2] < ($tp_largest_hit / 10)){
								$bubbledata[$k][0] = "";
							} else {
								$bubbledata[$k][0] = "{$val[2]} ". _VIEWS;
							}
							$bubbledata[$k][1] = $val[1];
							$bubbledata[$k][2] = $val[2];
							$bubbledata[$k][3] = $val[3];
						}
						$tp->BubbleChart($bubbledata,"none","width:auto;","true");
						} ?>
					</div>
				</div>
			</div>
			<div class="infograph-row">
				<div class="page-block">
					<table width="95%" border="0" class="top-table">
					<tr>
						<td style='border:0;'></td>
						<td style='border:0;'></td>
						<td style='border:0;'></td>
						<td style='border:0;'><div class='visitor-explain'><?php echo _VISITS."&nbsp;&nbsp;"; ?></div></td>
						<td style='border:0;'></td>
					</tr>
					<?php
					$i = 0;
					//dump($pages);
					foreach($pages as $k => $v){
						$diff = ($v["hits"] - $v["diff"]);
						if($diff > 0){
							$color = "green";
							$trend = "+{$diff}";
						} else {
							$trend = "{$diff}";
							$color = "red";								
						}
						
						$id = md5(time().$i);
						echo "<tr>";
							echo "<td><div class='page-legend' style='background:{$this->graphcolors[$i]}'></div></td>";
							echo "<td><div class='page-sparkline spark-{$id}'>";
							?>
							<script type='text/javascript'>
							$('.spark-<?php echo $id; ?>').sparkline([<?php echo implode(",",$v["sparkpoints"]['vals']); ?>], { 
								type: 'line'
								,tooltipFormat: '<span style="color: {{color}}">&#9679;</span> {{offset:names}}  ({{y}})'
								,tooltipValueLookups: { names: { <?php echo implode(", ",$v["sparkpoints"]['date']); ?> } }	

								});				
							</script>
							<?php
							echo "</div></td>";
							echo "<td>{$k}</td>";
							echo "<td>{$v["hits"]}</td>";
							echo "<td><div style='color:{$color}; white-space:nowrap;'>({$trend})</div></td>";
						echo "</tr>";
						$i ++;
					}
					?>
					</table>
				</div>
			</div>
			<div class="infograph-row">
				<div class="divider">
					<div class="divider1"></div>
					<div class="divider2"><h1><?php echo _BROWSERS; ?></h1></div>
					<div class="divider3"></div>
				</div>
			</div>
			<div class="infograph-row">
				<div class="browsers">
					<div class="browser-graph" style="height: 300px;"><?php 
						if(!empty($reports["_BROWSER_BREAKDOWN"])){	
							$this->BrowserDonutGraph();	
						}
					?></div>
				</div>
			</div>
			<div class="infograph-row">
				<div class="duration">
					<?php if($this->profile->trackermode !== '1'){ ?>
					<div class="visit-duration">
						<span class="infograph-sub"><?php echo _ERRORS; ?></span>	
						<table width="100%" border="0">
							<tr>
								<td style='border:0;'></td>
								<td style='border:0;'></td>
								<td style='border:0;text-align:right;'><div class='visitor-explain' ><?php echo _VIEWS; ?></div></td>
								<td style='border:0;'></td>
							</tr>
							<?php
							foreach($errors as $k => $v){
								$diff = ($v["hits"] - $v["diff"]);
								if($diff > 0){
									$color = "red";
								} else {
									$color = "green";								
								}
								echo "<tr>";
									echo "<td><div class='error-icon'><img src='images/infographics/{$k}.png' class='error-icon'></div></td>";
									echo "<td><div class='error-number'>{$k} - {$v["desc"]}</div></td>";
									echo "<td><div class='error-amount'>{$v["hits"]}</div></td>";
									echo "<td><div class='error-diff' style='color:{$color};'>({$diff})</div></td>";
								echo "</tr>";
							}
							?>
						</table>
					</div>
					<?php } ?>
					<div class="total-duration" <?php if($this->profile->trackermode == '1'){ echo "style='width:100%;'"; } ?> >
						<span class="infograph-sub"><?php echo "Homepage "._BOUNCE_RATE; ?></span>
						<div class="bounce-graph">
						<?php
						if(!empty($br)){	
							//dump($bounce);
							$br->RingChart($bounce,"south");
						}
						?>
						</div>
					</div>
				</div>
			</div>
			<div class="infograph-row">
				<div class="divider">
					<div class="divider1"></div>
					<div class="divider2"><h1><?php echo _DEVICES; ?></h1></div>
					<div class="divider3"></div>
				</div>
				<?php $this->DeviceData(); ?>
			</div>
		</div>
		<?php
		
	}
	
	function ErrorsData(){
		global $reports;
		$errors = [];
		$errors["404"] = array("hits" => 0, "desc" => "", "diff" => 0);
		$errors["301"] = array("hits" => 0, "desc" => "", "diff" => 0);
		$errors["302"] = array("hits" => 0, "desc" => "", "diff" => 0);
		$errors["206"] = array("hits" => 0, "desc" => "", "diff" => 0);
		$errors["403"] = array("hits" => 0, "desc" => "", "diff" => 0);
		
		if(!empty($reports["_ERROR_REPORT"])){
			$er = new $reports["_ERROR_REPORT"]["ClassName"]();
			$er->label = _ERROR_REPORT;
			$er->from = $this->from;
			$er->to = $this->to;
			$errs = $er->GetReportData();
			foreach($errs as $k => $e){
				$code = explode(" - ",$e[0]);
				$desc = $code[1];
				$code = $code[0];
				if(isset($errors[$code])){
					$errors[$code]["hits"] = $e[1];
					$errors[$code]["diff"] = 0;
					$errors[$code]["desc"] = $desc;
				}
			}
			
			$er->to = $this->from - 1;
			$er->from = ($er->to - (86400*7));
			$errs = $er->GetReportData();
			foreach($errs as $k => $e){
				$code = explode(" - ",$e[0]);
				$desc = $code[1];
				$code = $code[0];
				if(isset($errors[$code])){
					$errors[$code]["diff"] = $e[1];
					$errors[$code]["desc"] = $desc;
				}
			}
		}
		return $errors;
	}
	
	function IsTablet(){
		
	}

	function DeviceData(){
		global $db;

		$query = "
		SELECT 'desktop' as n, COUNT(DISTINCT visitorid) AS visitors FROM {$this->profile->tablename} AS a, {$this->profile->tablename_useragents} as ua 
		WHERE a.useragentid = ua.id AND a.timestamp BETWEEN ". $db->quote($this->from) ." AND ". $db->quote($this->to) ." and ua.is_mobile = 0

		UNION

		SELECT 'tablet' as n, COUNT(DISTINCT visitorid) AS visitors FROM {$this->profile->tablename} AS a, {$this->profile->tablename_useragents} as ua 
		WHERE a.useragentid = ua.id AND a.timestamp BETWEEN ". $db->quote($this->from) ." AND ". $db->quote($this->to) ." and ua.is_mobile = 1 AND ua.useragent LIKE '%Tab%'

		UNION

		SELECT 'mobile' as n, COUNT(DISTINCT visitorid) AS visitors FROM {$this->profile->tablename} AS a, {$this->profile->tablename_useragents} as ua 
		WHERE a.useragentid = ua.id AND a.timestamp BETWEEN ". $db->quote($this->from) ." AND ". $db->quote($this->to) ." and ua.is_mobile = 1 AND ua.useragent NOT LIKE '%Tab%';
		";

		$r = $db->Execute($query);
		$devices = [];
		
		$devices['Total'] = 0;
		$devices['Desktop'] = 0;
		$devices['Tablet'] = 0;
		$devices['Mobile'] = 0;
		while($row = $r->fetchRow()){
			$devices['Total'] = $devices['Total'] +  $row["visitors"];
			switch ($row['n']) {
				case 'desktop':
					$devices['Desktop'] = $devices['Desktop'] +  $row["visitors"];
					break;
				case 'tablet':
					$devices['Tablet'] = $devices['Tablet'] +  $row["visitors"];
					break;
				case 'mobile':
					$devices['Mobile'] = $devices['Mobile'] +  $row["visitors"];
					break;
			}
		}
		
		echo "<div class='devices-wrapper'>";
			if($devices['Total'] == 0){
				$round_desktop = "";
				$round_tablet = "";
				$round_mobile = "";
			} else {
				$round_desktop = round(($devices['Desktop'] / $devices['Total']) * 100)."%";
				$round_tablet = round(($devices['Tablet'] / $devices['Total']) * 100)."%";
				$round_mobile = round(($devices['Mobile'] / $devices['Total']) * 100)."%";
			}
			echo "<div class='device'>";
					
					echo "<p><img src='images/infographics/desktop.png' alt='' />";
					echo "<font style='font-size:32px;line-height:30px;'>".$round_desktop."</font>";
					echo "<font style='margin-top:30px; font-size:16px; color:#333;'>". _DESKTOP ."</font></p>";		
			echo "</div>";			
			echo "<div class='device'>";
					echo "<p><img src='images/infographics/tablet.png' alt='' />";
					echo "<font style='font-size:32px;line-height:30px;'>".$round_tablet."</font>";
					echo "<font style='margin-top:30px; font-size:16px; color:#333;'>". _TABLET ."</font></p>";
			echo "</div>";
			echo "<div class='device'>";
					echo "<p><img src='images/infographics/mobile.png' alt='' />";
					echo "<font style='font-size:32px;line-height:30px;'>".$round_mobile."</font>";
					echo "<font style='margin-top:30px; font-size:16px; color:#333;'>". _MOBILE ."</font></p>";
			echo "</div>";
		echo "</div>";
	}
	
	function BrowserDonutGraph(){
		$component = new BrowserBreakdown();
		$component->label = _BROWSER_BREAKDOWN;
		$component->displayHeader=false;
		$data = $component->ConvertData($component->GetReportData());
		$component->CreateDonut($data);	
	}
	
	function AvgVisitorsBlockData(){
		global $reports;
		$returndata = [];
		
		# Average Visitors Per Day
		$data = [];
		if(!empty($reports["_VISITORS_PER_DAY"])){
			$vpd = new $reports["_VISITORS_PER_DAY"]["ClassName"]();
			$vpd->label = _VISITORS_PER_DAY;
			$vpd->from = $this->from - (86400 * 7);
			$vpd->period = "days";
			$vpd->to = $this->to;	
			$data = $vpd->GetReportData();
		}

		$pageviews = 0;
		$prepageviews = 0;
		$visits = 0;
		$previsits = 0;
		$visitors = 0;
		$previsitors = 0;
		$i = 0;
		
		$ppu = 0;
		$prevppu = 0;
		
		foreach($data as $set){
			if($i < 7){
				$previsitors = $previsitors + $set[1];
				$prepageviews = $prepageviews + $set[2];
				$prevppu = $prevppu + $set[3];
				$previsits = $previsits + $set[4];
			} else {
				$visitors = $visitors + $set[1];
				$pageviews = $pageviews + $set[2];
				$ppu = $ppu + $set[3];
				$visits = $visits + $set[4];
			}
			$i ++;
		}
		
		$days = $this->ndays;
		$diff = round( ($visitors/$days) - ($previsitors/$days) );
		$returndata["trend"]["color"] = ($diff < 0) ? "red" : "green";
		$returndata["trend"]["data"] = ($diff < 0) ? $diff : "+{$diff}";
		
		if($returndata["trend"]["color"] == "red"){
			$returndata["trendarrow"] = "<img src='images/infographics/arrow_red.png' class='infograph-arrow' />";
			$returndata["trendsmile"] = "<img class='infograph-smiley' src='images/icons/smilleys/smilley_39.png' />";
		} else {
			$returndata["trendarrow"] = "<img src='images/infographics/arrow_green.png' class='infograph-arrow' />";
			$returndata["trendsmile"] = "<img class='infograph-smiley' src='images/icons/smilleys/smilley_01.png' />";
		}
		
		$returndata["vpd"] = round($visitors / $this->ndays);
		$returndata["visitspervisitor"]["prev"] =($previsitors == 0)?  0 : number_format(($previsits / $previsitors),2);
		$returndata["visitspervisitor"]["now"] = ($visitors == 0)?  0 : number_format(($visits / $visitors),2);
		$returndata["visitspervisitor"]["color"] = (($returndata["visitspervisitor"]["now"] - $returndata["visitspervisitor"]["prev"] ) < 0) ? "red" : "green";
		
		$ppu = number_format($ppu / $days,2);
		$prevppu = number_format($prevppu / $days,2);
		
		$returndata["pageviewspervisitors"]["prev"] = $prevppu;
		$returndata["pageviewspervisitors"]["now"] = $ppu;
		$returndata["pageviewspervisitors"]["color"] = (($returndata["pageviewspervisitors"]["now"] - $returndata["pageviewspervisitors"]["prev"]) < 0) ? "red" : "green";
		# New VS Returning
		$data = [];
		if(!empty($reports["_NEW_VS_RETURNING"])){
			$newret = New $reports["_NEW_VS_RETURNING"]["ClassName"]();
			$newret->label = _NEW_VS_RETURNING;
			$newret->from = $this->from;
			$newret->period = "days";
			$newret->to = $this->to;	
			$data = $newret->GetReportData();
		}

		$ret = 0;
		foreach($data as $set){
			# Returning
			$r = str_replace("%","",$set[2]);
			$ret = $ret + $r;
		}
		
		$returndata["returning"] = round($ret / $this->ndays);
		$returndata["new"] = 100 - $returndata["returning"];
		return $returndata;
	}
}
?>