<?php

/**
 * @desc This report lets you make split test of your pages and gives you an overview of wich one works the best.
 */
$reports["_PAGETIME"] = array(
    "ClassName" => "PageTime",
    "Category" => "_POPULAR_CONTENT",
    "icon" => "images/icons/32x32/alltrafficbyhour.png",
    "Options" => "daterangeField,profileselector,displaymode,human",
    "Filename" => "average_page_time",
    "Distribution" => "Premium",
    "Order" => 8,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 3.0,
    "EmailAlerts" => false,
    "Update" => false,
    "canAggregate" => false
);

class PageTime extends Report
{
    function Settings()
    {
        $this->DefaultDisplay = "linechart";
        $this->DisplayModes = "table,linechart";
        $this->allowDateFormat = false;

        if (empty($this->displaymode)) {
            $this->displaymode = "linechart";
        }
        if (empty($this->page)) {
            $this->page = "/";
        }

        $this->key_col = 0;
        $this->columnDefinitions[0] = array("Label" => _DATE);
        $this->addlabel .= " " . _PAGE . ": " . $this->page;
        $this->fileNameExpension .= urlencode($this->page);

        if ($this->displaymode == 'table') {
            $this->columnDefinitions[] = array("Label" => _PAGE, "search" => true);
            $this->columnDefinitions[] = array("Label" => _TIME_SPENT);
        } else {
            if ($this->displaymode == 'linechart') {
                $this->columnDefinitions[] = array("Label" => _SECONDS);
            } else {
                $this->columnDefinitions[] = array("Label" => _PAGE, "search" => true, "display" => false);
                $this->columnDefinitions[] = array("Label" => _SECONDS);
            }
        }
    }

    function GetDataFromDb()
    {
        global $db;

        if (isset($this->human) && $this->human == 1) {
            $tablename = $this->profile->tablename_merge;
        } else {
            $tablename = $this->profile->tablename;
        }

        // first find the visitorid and timestamp of the request we're interested in.
        $query = "CREATE TEMPORARY TABLE goodtimes ";
        $query .= "SELECT sessionid,min(timestamp) AS timestamp from {$tablename} ";
        $query .= "WHERE (timestamp >=" . $db->Quote($this->from) . " and timestamp <=" . $db->Quote($this->to) . ") ";
        $query .= "AND url='" . getID($this->page, "urls") . "' ";
        $query .= "GROUP BY sessionid";

        // get the visitorid and timestamp of the request that came after the one we're interested in
        $query2 = "INSERT INTO goodtimes ";
        $query2 .= "SELECT sessionid,min(timestamp) AS timestamp from {$tablename} ";
        $query2 .= "WHERE (timestamp >=" . $db->Quote($this->from) . " and timestamp <=" . $db->Quote($this->to) . ") ";
        //$query2 .= "WHERE referrer='" . getID("https://{$this->profile->confdomain}" . $this->page, "referrers") . "' ";
        $query2 .= " ";
        $query2 .= "GROUP BY sessionid, timestamp";

        // now create a tempoary table to hold the difference between the two timestamps
        $query3 = "CREATE TEMPORARY TABLE pagetime ";
        $query3 .= "SELECT (max(timestamp)-min(timestamp)) AS duration, sessionid ";
        $query3 .= "FROM goodtimes GROUP BY sessionid";

        // get rid of the ones that have no time
        $query4 = "DELETE from pagetime WHERE duration=0";


        // now calculate an average duration
        $query5 = "SELECT avg(duration) AS avgduration FROM pagetime";

        //echo $query."<p>".$query2."<p>".$query3."<p>".$query4."<p>".$query5;
        // issue the queries and get the data
        $db->Execute($query);
        $db->Execute($query2);
        $db->Execute($query3);
        $db->Execute($query4);
        $result = $db->Execute($query5);
        $avg_duration = $result->FetchRow();

        // clean up temp tables (so we can do this more than once in a single script)
        $db->Execute("drop temporary table goodtimes");
        $db->Execute("drop temporary table pagetime");


        $data = [];
        $data[0][0] = $this->from;
        $data[0][1] = $this->page;
        $data[0][2] = $avg_duration['avgduration'];

        return $data;
    }

    function displayCustomForm()
    {
        echo "<div class='form-group'>";
        echo "<label for='page'>" . _PAGE . ":</label>";
        echo "<input class='report_option_field form-control' type='text' name='page' id='page' value='" . @$this->page . "' onkeyup=\"popupActionMenu(event, this.value+'@'+this.id+'@'+'page', 'forminput');\" onclick=\"popupActionMenu(event, this.value+'@'+this.id+'@'+'page', 'forminput');\">";
        echo "</div>";
    }

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

    function GetReportData()
    {
        global $db, $get_constant;
        if (isset($this->page)) {
            echoNotice($this->SettingsButton() . _PLEASE_SELECT_PAGE, "margin:5px;");
            return false;
        }

        $this->createDataFiles($this->from, $this->to);
        $d = $this->getDataFromFiles($this->dataFiles($this->from, $this->to));

        $data = [];
        foreach ($d as $k => $v) {
            if (isset($this->outputmode) && $this->outputmode == 'sparkline') {
                $data[$k][0] = $v[0];
            } else {
                $data[$k][0] = LogaDate($this->profile->dateFormat, $v[0]);
            }

            if ($this->displaymode == 'table') {
                $sec = intval($v[2]);
            } else {
                $sec = intval($v[1]);
            }

            $hours = floor($sec / 3600);
            $sec = $sec - ($hours * 3600);
            $min = floor($sec / 60);
            $sec = round($sec - ($min * 60));

            if ($this->displaymode == 'table') {
                $data[$k][1] = $v[1];
                $time = "$hours:$min:$sec";
                $data[$k][2] = $time;
            } else {
                if ($this->displaymode == 'linechart') {
                    $data[$k][1] = round($v[2]);
                } else {
                    $data[$k][1] = round($v[1]);
                }
            }
        }
        return $data;
    }

    function ConvertData($data)
    {
        $new_data = [];
        $i = 0;
        foreach ($data as $k => $v) {
            $new_data[$i][0] = date("D, d/m/Y", (int)$v[0]);
            $new_data[$i][1] = $v[1];
            $i++;
        }
        return $new_data;
    }

    function UpdateStats($from = '', $to = '', $print = 2)
    {
        return false;
    }
}