<?php

/**
* @desc This report displays a overview of referrrer conversion.
*/
include_once "top_pages.php";

$reports["_PAGE_TRENDS"] = Array(
	"ClassName" => "PageTrends", 
	"Category" => "_POPULAR_CONTENT", 
	"icon" => "images/icons/32x32/page_trends.png",
	"Options" => "daterangeField,profileselector,trafficsource,search,period,displaymode,limit",
	"Filename" => "page_trends",
	"Distribution" => "Premium",
	"Order" => 3,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false,
	"canAggregate" => false
);

class PageTrends extends TopPages {

	function Settings() {
		$this->DefaultDisplay = "areachart";
		$this->DisplayModes = "linechart,table,areachart";
		$this->help = "";
		$this->remove_outputmodes = array("xml");
		$this->displayReportButtons = false;
		
		$this->chartoptions = array("stacked_graph_style" => "stack", "stacked_showcontrols" => true, "showlegend" => false, "yFormat" => ",2f");
		if (!empty($this->outputmode)) {
			$this->displaymode = "table";
		}
		$this->addlabel .= _GROUPED_BY . " ".constant($this->period);
	}

	function GetReportData() {

		$data = $this->rawGetReportData();

		$data = $this->ConvertData($data);
		return $data;	

	}
	
	function rawGetReportData() {
		global $reports;
		$r = new $reports["_TOP_PAGES"]["ClassName"]();
		$r->dataCollectType = "days";
		$r->createDataFiles($this->from,$this->to);	
		$d = $r->getTrendDataFromFiles($r->DataFiles($this->from,$this->to));
		$data = [];	

		foreach($d as $k => $v){
            $l = 0;
            if (!is_array($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));


                # Define the chosen period / time unit
                if ($this->period == '_DAYS') {
                    $format = "D, m/d/Y";
                    $date = date($format, $timestamp);
                } elseif ($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);
                    }
                }

                $p = explode("##", $val[0]);
                $page = $p[0];

                if (!empty($this->viewData) && $this->viewData == "uv") {
                    $viewed = $val[4];
                } else {
                    if (!empty($this->viewData) && $this->viewData == "pv") {
                        $viewed = $val[2];
                    } else {
                        $viewed = $val[1];
                    }
                }

                if (!isset($data[$page])) {
                    $data[$page] = [];
                }

                if (isset($data[$page][$date])) {
                    $data[$page][$date] = $data[$page][$date] + $viewed;
                } else {
                    $data[$page][$date] = $viewed;
                }
                $l++;
            }

		}
		$temp_d = [];		
		foreach($data as $page => $v){
			$temp_d[$page] = array_sum($v);
		}
		arsort($temp_d);		
		$final = [];
		$i = 0;
		$l = 0;
		foreach($temp_d as $page => $v){
			if($l > $this->limit){
				break;
			}			
			foreach($data[$page] as $date => $viewed){				
				$final[$i][0] = $date; 
				$final[$i][1] = $page; 
				$final[$i][2] = $viewed; 
				$i ++;
			}			
			$l ++;
		}
		return $final;
	}

	function ConvertData($data = "") {
		# transform the data array to a column for each serie
		$data = $this->seriesToColumns($data);
		
		if(empty($data)){
			return $this->EmptyTrendData();
		}
		
		$this->columnDefinitions = [];
		foreach($data['fields'] as $f){
			$this->columnDefinitions[] = array("Label" => $f);
		}
		$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 DisplayCustomForm()
    {
        echo "<div class='form-group'>";
        echo "<label>Data</label>";
        echo "<select id='viewData' class='form-control' name='viewData'>";
        if (isset($this->viewData) == 'v') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='v' $selected>" . _VISITS . "</option>";
        if (isset($this->viewData) == 'uv') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='uv' $selected>" . _UNIQUE_VISITORS . "</option>";
        if (isset($this->viewData) == 'pv') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='pv' $selected>" . _PAGEVIEWS . "</option>";
        echo "</select>";
        echo "</div>";
    }

    function UpdateStats($from = '', $to = '', $print = 2)
    {
        # it's not using datafiles. Collect data from Top Pages
        return false;
    }

    function DisplaySparkline()
    {
        $data = $this->GetReportData();
        $this->Sparkline($data);
    }

}
?>