<?php


if(!defined('APP_INCLUDE')){ die('invalid inclusion'); }
set_time_limit(240);

Class Globalstats{
	var $json;


	function Json(){
		$this->json = true;
		return json_encode($this->GetData());
	}

	function Report(){
		$this->json = false;
		$data = $this->GetData();
		$reportClass = new DataVisualization();
		echo "<div id='content' style='width:1024px;'>";
			echo "<div class='dialog'>";
				echo "<div class='dialog-header'><label class=\"dialog-label\" rel=\"_ALL_TIME_ALL_PROFILES\">"._ALL_TIME_ALL_PROFILES."</label></div>";
				echo "<div class='dialog-content'>";
					$reportClass->label=_ALL_TIME_ALL_PROFILES;
					$reportClass->help=_ALL_TIME_ALL_PROFILES_HELP;
					$reportClass->from=0;
					$reportClass->to=time();
					$reportClass->columnDefinitions[] = array("Label" => "_PROFILENAME", "totalRow" => "none");
					$reportClass->columnDefinitions[] = array("Label" => "_USERNAME", "totalRow" => "none");
					$reportClass->columnDefinitions[] = array("Label" => "_VISITS", "totalRow" => "none");
					$reportClass->columnDefinitions[] = array("Label" => "_AVG_VISITS_PER_DAY", "bchart" => true, "totalRow" => "none");
					$reportClass->columnDefinitions[] = array("Label" => "_FROM", "totalRow" => "none");
					$reportClass->columnDefinitions[] = array("Label" => "_DATE_TO","totalRow" => "none");
					$reportClass->setupColumnDefinitions();
					
					$reportClass->Table($data);
				echo "</div>";
			echo "</div>";
			echo "<hr noshade size=1 style=\"margin-top:25px;margin-bottom:25px;\">";
		echo "</div>";
	}

	function GetUsers(){
		global $db;
		$data = [];
		# Get all users;
		$q = $db->Execute("SELECT username,profiles from ". TBL_USERS ." where isAdmin !=1");
		while($row = $q->fetchRow()){
			$ps = explode(",", $row['profiles']);
			foreach ($ps as $profile) {
				if(!empty($profile)){
					$data[$profile][] = $row['username'];
				}
			}
		}
		return $data;
	}

	function GetData(){
		global $validUserRequired, $session, $db;

		$users = $this->GetUsers();

		# Get profiles Query
		$lq = "Select profileid,profilename,tablename,lastused,sessioncounter,stats from ".TBL_PROFILES;

		if ($this->json === false) {
			# If we're limiting the visible profiles, then put a filter on to only pull those records.
			if ( $validUserRequired && !$session->isAdmin() && !$session->allProfiles ) {
			    // Can't use implode here because we need to escape the entries.
			    $validprofiles = "";
			    for ($i = count($session->user_profiles)-1; $i >= 0; $i--) {
			        if ($validprofiles != "") { $validprofiles .= ","; }
			        $validprofiles .= $db->Quote($session->user_profiles[$i]);
			    }
			    $lq .= " where profilename in (". $validprofiles.")";
			}		
		}		

		$q = $db->Execute($lq);

		$global_stats = [];
		$i = 0;

		while($row = $q->fetchRow()){

			$pname = $row["profilename"];
			$visitors = 0;

            $stats = json_decode($row["stats"], true);
            //dump($stats);
            $visits = $row["sessioncounter"];
            $from = $stats["firstRequestTimeEver"];
            $to = $stats["max_db_timestamp"];
            $last_update_finished = $stats["last_update_finished"];

            $range = intval($to) - intval($from);
            $days = round($range / 86400);
            if ($days < 1) {
                $days = 1;
            }

            # Default array fill
            if ($this->json === true) {
                $global_stats[$i][0] = $pname;
            } else {
                $global_stats[$i][0] = "<a href='index.php?conf={$pname}'>{$pname}</a>";
            }

            if (!isset($users[$pname][0])) {
                $users[$pname][0] = "none";
            }

            if (isset($this->version) < 6) {
                if (isset($users[$pname][0])) {
                    $global_stats[$i][1] = $users[$pname][0]; #try getting the user for the profile
                }
                $global_stats[$i][2] = $visits; # visits
                $global_stats[$i][3] = round(
                    ($global_stats[$i][2] == 0) ? 0 : ($global_stats[$i][2] / $days)
                ); # visits avg p d
                $global_stats[$i][4] = (!$from) ? "0000-00-00" : date('Y-m-d', $from);
                $global_stats[$i][5] = (!$to) ? "0000-00-00" : date('Y-m-d', $to);
                $data = DataSort($global_stats, 2);
            } else {
                $global_stats[$i][] = $row["tablename"];
                if (isset($users[$pname][0])) {
                    $global_stats[$i][] = $users[$pname][0]; #try getting the user for the profile
                }
                $global_stats[$i][] = $visits; # visits
                $global_stats[$i][] = round(($visits == 0) ? 0 : ($visits / $days)); # visits avg p d
                $global_stats[$i][] = (!$from) ? "0000-00-00" : date('Y-m-d', $from);
                $global_stats[$i][] = (!$to) ? "0000-00-00" : date('Y-m-d', $to);
                $global_stats[$i][] = (!$last_update_finished) ? "0000-00-00" : date('Y-m-d', $last_update_finished);
                $data = DataSort($global_stats, 3);
            }

            $i++;
		}
		if (empty($data)) {
			$data = [];
		}
		return $data;
	}
}
?>