<?php
  date_default_timezone_set("America/Denver");
  
  require('inc/sessionStart.php');
  
  $action = "manage";
  
  if(isset($_GET['a'])){
    if($_GET['a'] == "manage"){
	  $action = "manage";
    }
  }
?>

<?php
  $pageTitle = "Administration: Site Analytics";
  $pageDescription = "";
  $pageKeywords = "";
?>

<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/header.php");
?>
	<script async src="//afsshareportal.com/js/moment.min.js"></script>
	<script src="/Kickstrap/js/jquery.h5validate.js"></script>
	<script src="/Kickstrap/js/jquery-ui-1.9.0.custom.min.js"></script>
	<link href="/Kickstrap/css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet">
<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/mainNav.php");
  include($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/gapi.class.php");
  
  //do cURL call to get website information with the analytics id from shareportal
  $url = "https://afsshareportal.com/lookUpFeatures.php?action=getSiteInfoCurl&website_url=" . urlencode(WEB_URL);
	
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, false);
  $result=curl_exec($ch);
  
  $storeInfo = json_decode($result, true);
  $storeInfo = $storeInfo[0];
  curl_close($ch);
  
  
  if(isset($_GET['start']) && isset($_GET['end'])){
	$fromDate = $_GET['start'];
	$toDate = $_GET['end'];
  }else{
	$fromDate = date('Y-m-d', strtotime('-60 days'));
	$toDate = date('Y-m-d');
  }
  
  define('ga_email','420707711539-t58p840c584qt6d51focdlcqv05ah5nh@developer.gserviceaccount.com');
  define('ga_password', $_SERVER['DOCUMENT_ROOT'] . '/admin/inc/Shareportal-Analytics-7aed242c6818.p12');
  $ga = new gapi(ga_email,ga_password);
?>



    
    <section class="container">
      <div id="blankBuffer" class="carousel-buffer"></div>
      <div id="noEditError" class="hideObject">
			<div class="alert alert-error">
				  <a class="close" data-dismiss="alert" href="#">x</a>You can only <span id="noEditErrorText"></span> if you have editing capabilities.
			</div>
	  </div>
	  <section class="container" id="storePortal">
	    <div class="row">
		  <div class="span3 sideNav">
			<?php include('inc/sideNav.php'); ?>
		  </div>
		  
		  <div class="span9 portalContent">
			<div class="contentContain">
			  <div id="analyticsContain">
				<?php
				  $dimensions = array('userDefinedValue');
				  $metrics = array('pageViews', 'pageviewsPerVisit', 'visits', 'visitors');
				  $sort = '';
				  $ga->requestReportData($storeInfo['website_analyticsID'], $dimensions, $metrics, $sort, null, $fromDate, $toDate);
				?>
				<h2>Analytics Overview</h2>
				<div id="dateHolder">
				  <h4><?php echo $fromDate . " - " . $toDate; ?> <span class="btn" id="changeDates" style="margin-left:60px;">Change Dates</span></h4>
				  <table class="hideObject">
					<tr>
					  <td><label for="datepicker_start">Start Date:</label></td>
					  <td  id= "datepicker_start1" class="input-append date datepicker" data-date-format="yyyy-mm-dd" data-date="<?php echo date("Y-m-d"); ?>">
							<input type="text" id="datepicker_start" name="datepicker_start" value="" readonly="readonly" required/>
							<span class="add-on" id=><i class="icon-calendar"></i></span>
					  </td>
					</tr>
					<tr>
					  <td><label for="datepicker_end">End Date:</label></td>
					  <td id= "datepicker_end1" class="input-append date datepicker" data-date-format="yyyy-mm-dd" data-date="<?php echo date("Y-m-d"); ?>">
							<input type="text" id="datepicker_end" name="datepicker_end" value="" readonly="readonly" required/>
							<span class="add-on" id=><i class="icon-calendar"></i></span>
					  </td>
					</tr>
					<tr>
					  <td><p id="newDateSubmit" class="btn">Submit</p></td>
					  <td>&nbsp;</td>
					</tr>
				  </table>
				</div>
				
				<div id="siteStats" class="aSection">
				  <?php
					$returnArray = array();
					$returnArray[] = array("Store Name", "Page Views", "Page Views Per Visit", "Visits", "Unique Visitors");
					
					$returnArray[] = array($storeInfo['store_name'], $ga->getPageViews(), round($ga->getPageViewsPerVisit(),2, PHP_ROUND_HALF_UP), $ga->getVisits(), $ga->getVisitors());
					
					$headings = array_shift($returnArray);
					
					foreach($returnArray as $aSite){
					  //$theMinutes = floor($aSite[5] / 60);
					  //$theSeconds = strlen($aSite[5] % 60) == 1 ? "0" . $aSite[5] % 60 : $aSite[5] % 60;
				  ?>
					<h3>Site Statistics</h3>
					<p>
					  <span><b><?php echo $headings[3]; ?>:</b> <?php echo number_format($aSite[3]); ?></span><br>
					  <span><b><?php echo $headings[1]; ?>:</b> <?php echo number_format($aSite[1]); ?></span><br>
					  <span><b><?php echo $headings[2]; ?>:</b> <?php echo $aSite[2]; ?></span><br>
					  <span><b><?php echo $headings[4]; ?>:</b> <?php echo number_format($aSite[4]); ?></span><br>
					  <!--<span><b><?php echo $headings[5]; ?>:</b> <?php echo $theMinutes; ?>:<?php echo $theSeconds; ?></span><br>-->
					</p>
				  <?php
					}//end foreach($returnArray as $aSite)
				  ?>
				  
				</div>
				
				<div id="pageResults" class="aSection">
				  <table>
					<?php
					  $dimensions = array('pagePath');
					  $metrics = array('uniquePageviews', 'pageViews');
					  $sort = '-Pageviews';
					  $filter = 'pagePath !~ ^/admin && pagePath !~ error';
					  
					  $ga->requestReportData($storeInfo['website_analyticsID'], $dimensions, $metrics, $sort, $filter, $fromDate, $toDate, 1, 100);
					?>
					<h3>Pages Visited</h3>
					<thead>
					  <tr>
						<td>Page Path</td>
						<td>Page Views</td>
					  </tr>
					</thead>
					<tbody>
				  <?php
					foreach($ga->getResults() as $result){
					  if($result->getPageviews() > 1){
				  ?>
					  <tr>
						<td class="pagePath"><?php echo $result->getPagePath(); ?></td>
						<td class="pageCount"><?php echo number_format($result->getPageviews()); ?></td>
					  </tr>
				  <?php
					  }
					}//foreach($ga->getResults() as $result)
				  ?>
					</tbody>
				  </table>
				</div>
				
				<div id="dailyStats" class="aSection">
				  <h3>Daily Statistics</h3>
				  <?php
					$dimensions = array('userDefinedValue', 'date');
					$metrics = array('visits');
					$sort = array('date');
					$maxResults = 1000;
					$ga->requestReportData($storeInfo['website_analyticsID'], $dimensions, $metrics, $sort, null, $fromDate, $toDate, 1, $maxResults);
					
					$dailyData = array();
					
					foreach($ga->getResults() as $result){
					  $theDate = $result->getDate();
					  $useDate = substr($theDate,0,4) . "-" . substr($theDate,4,2) . "-" . substr($theDate,6,2);
					  $dailyData[] = array((strtotime($useDate) * 1000), $result->getVisits());
					}
				  ?>
				  
				  <div id="dailyStatsGraph"></div>
				  
				  <script language="javascript" type="text/javascript" src="/js/jquery.flot.min.js"></script>
				  <script language="javascript" type="text/javascript" src="/js/jquery.flot.time.min.js"></script>
				  <script language="javascript" type="text/javascript" src="/js/jquery.flot.tooltip.min.js"></script>
				  
				  <script>
					var theData = <?php echo json_encode($dailyData); ?>;
					var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
					var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
					//console.log(theData);

					$.plot("#dailyStatsGraph", [theData],{
					  xaxis: {
						mode: "time",
						timeformatter: function(val, axis){
						  var d = new moment(val);
						  return d.utc().date() + "/" + (d.utc().month() + 1);
						}
					  },
					  yaxis: {
						tickDecimals: 0
					  },
					  grid: {
						hoverable: true,
						clickable: true
					  },
					  series: {
						points: {
						  show: true,
						  radius: 3,
						  fill: true
						},
						lines: {
						  show: true
						}
					  },
					  tooltip: true,
					  tooltipOpts: {
						content: function(label, xval, yval, flotItem){
						  var theDate = new moment(flotItem['datapoint'][0]);
						  //theDate.setDate(theDate.getDate()+1);
						  var theDay = theDate.date();
						  var theYear = theDate.format("YYYY");
						  var theMonth = theDate.format("MMMM");
						  var dayOfWeek = theDate.format("dddd");
						  var formattedDate = theMonth + " " + theDay + ", " + theYear;
						  
						  return "<div>" + dayOfWeek + ", " + formattedDate + "<br>Visits: <b>" + flotItem['datapoint'][1] + "</b></div>";
						},                        
						shifts: {
						  x: -60,
						  y: 25
						}
					  }
					});
				  </script>
				</div>
				
				<div id="browserResults" class="aSection">
				  <table>
					<?php
					  $dimensions = array('browser');
					  $metrics = array('sessions');
					  $sort = '-sessions';
					  
					  $ga->requestReportData($storeInfo['website_analyticsID'], $dimensions, $metrics, $sort, null, $fromDate, $toDate, 1, 100);
					?>
					<h3>Browsers Used</h3>
					<thead>
					  <tr>
						<td>Browser</td>
						<td>Visits</td>
					  </tr>
					</thead>
					<tbody>
				  <?php
					foreach($ga->getResults() as $result){
					  if($result->getSessions() > 1){
				  ?>
					  <tr>
						<td class="pagePath"><?php echo $result->getBrowser(); ?></td>
						<td class="pageCount"><?php echo number_format($result->getSessions()); ?></td>
					  </tr>
				  <?php
					  }
					}//foreach($ga->getResults() as $result)
				  ?>
					</tbody>
				  </table>
				</div>
				
				
			  </div> <!-- end #analyticsContain -->
			</div> <!-- end #contentContain -->
		  </div> <!-- end .portalContent -->
	    </div> <!-- end .row -->
	    
      </section>
      
    </section>
      
    
  
  <script>
   
   
	$(document).ready(function() {
	  $("#changeDates").on("click", function(e){
		e.preventDefault();
		$("#dateHolder table").removeClass("hideObject");
	  });
	  
	  $("#newDateSubmit").bind("click", function(){
		var startDay = $("#datepicker_start").val();
		var endDay = $("#datepicker_end").val();
		
		document.location.href = "?start=" + startDay + "&end=" + endDay;
	  });
	  
	  
	  $("#pageResults tbody tr:even, #browserResults tbody tr:even").addClass("oddRowColor");
	  $("#pageResults tbody tr:odd, #browserResults tbody tr:odd").addClass("evenRowColor");
	});
	
	$(document).ready(function(){
	  var nowTemp = new Date();
      var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
	  
	  setTimeout(function(){
		var dateStart = $("#datepicker_start1").datepicker({
		  onRender: function(date){
			//console.log(date.valueOf() < now.valueOf() ? 'disabled' : '');
			//return date.valueOf() < now.valueOf() ? 'disabled' : '';
		  }
		}).on('changeDate', function(ev){
		  if(ev.date.valueOf() > dateEnd.date.valueOf()){
			var newDate = new Date(ev.date);
			newDate.setDate(newDate.getDate() + 1);
			dateEnd.setValue(newDate);
		  }
		  dateStart.hide();
		}).data('datepicker');
		
		var dateEnd = $("#datepicker_end1").datepicker({
		  onRender: function(date){
			//console.log(date.valueOf() + "\n" + now.valueOf());
			return date.valueOf() <= dateStart.date.valueOf() ? 'disabled' : '';
		  }
		}).on('changeDate', function(ev){
		  dateEnd.hide();
		}).data('datepicker');
		
	  }, 1000);
	});
   
      
  </script>
  
<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/footer.php'); ?>
