<?php

$dont_close_session = true;
require_once '../../AccessControl.php';
set_time_limit((10 * 60));


if (isset($session->metadata["current_usage"])) {
	$result = $session->metadata["current_usage"];
	if (isset($_REQUEST['quick'])) {		
		echo json_encode(array( "Status" => "Success", "Data" => $result));
		exit();	
	} else if ((time() - $result["generated"]) < (10 * 86400)) {
		echo json_encode(array( "Status" => "Success", "Data" => $result));
		exit();
	}
}

$from = mktime(0,0,0, date("m"), date("d") - 30 ,date("Y"));
$to = mktime(23,59,59, date("m"), date("d") -1  ,date("Y"));

$total_pageviews = 0;
$total_pages = 0;

$result = array(
	"from_date" => date("d M Y H:i:s", $from),
	"to_date" => date("d M Y H:i:s", $to),
	"pageviews" => 0,
	"totalpages" => 0,
	"profiles" => 0,
	"generated" => time()
);


$query = "SELECT * FROM ". TBL_PROFILES;
$where = "";

if(!$session->isAdmin() && !$session->allProfiles){
	if(empty($session->user_profiles)){
		die( json_encode(array( "Status" => "Success", "Data" => $result)) );
	}

	$profiles = array();
	for ($i = count($session->user_profiles)-1; $i >= 0; $i--) {
		$profiles[] = $db->Quote($session->user_profiles[$i]);
	}	

	$where = " where profilename in (". implode(",", $profiles) .")";
	
}
$r = $db->Execute($query . $where);



$i = 0;
$running_from_command_line=true; // this is to prevent lastused form being updated
while($row = $r->fetchRow()){
	
	$i ++;
	$profile = new SiteProfile($row['profilename']);

	if($profile->sessioncounter == 0){
		# Skip the profile if it never had any data
		continue;
	}

	$report = new $reports['_ALL_TRAFFIC_BY_DAY']["ClassName"]();

	$report->from = $from;
	$report->to = $to;

	$data = $report->GetReportData();
	if(count($data) == 0){
		# Skip the profile if it never had any data
		continue;
	}

	$totalpages = 0;
	$pageviews = 0;
	foreach ($data as $row) {
		$totalpages += $row[2];
		$pageviews += $row[3];
	}

	$total_days = count($data);

	# hmm, below is not really fair, just do actual numbers
	// if($total_days < 30){
	// 	$pageviews = ($pageviews / $total_days) * 30;
	// 	$totalpages = ($totalpages / $total_days) * 30;
	// }

	$total_pages += $totalpages;
	$total_pageviews += $pageviews;

}

$result["pageviews"] = round($total_pageviews);
$result["totalpages"] = round($total_pages);
$result["profiles"] = $i;

# now lets store this so we don't have to recalculate each time
$metadata = $session->metadata;
$metadata["current_usage"] = $result;
$metadata = json_encode($metadata);
$q = "UPDATE ".TBL_USERS." SET metadata = ? WHERE username = ?";
$db->Execute($q, array($metadata, $session->username));
# save it in the user metadata
unset($_SESSION['userinfo']);
session_write_close();

echo json_encode(array( "Status" => "Success", "Data" => $result));
?>