<?php

$reports["_UTM_TRENDS"] = array(
    "ClassName" => "UtmTrends",
    "Category" => "_ADVERTISING",
    "Options" => "daterangeField,profileselector,displaymode,search,limit,columnSelector,human",
    "Filename" => "utm_trends",
    "Distribution" => "Premium",
    "Order" => 2,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 3.0,
    "EmailAlerts" => true
);

class UtmTrends extends Report
{

    function Settings()
    {
        global $cnames;
        $this->DefaultDisplay = "areachart";
        $this->DisplayModes = "table,linechart,areachart";
        $this->help = "";
        $this->displayReportButtons = false;
        $this->remove_outputmodes = array("xml");
        if (empty($this->period)) {
            $this->period = '_DAYS';
        }
        $this->chartoptions = array(
            "stacked_graph_style" => "stack",
            "stacked_showcontrols" => true,
            "showlegend" => true
        );

        if (isset($_REQUEST["country_name"])) {
            # country code unknown check on name..
            $flip = $cnames;
            $flip = array_flip($flip);
            $this->country = $flip[$_REQUEST["country_name"]];
        }

        if (!empty($_REQUEST["country"])) {
            $this->country = $_REQUEST["country"];
        }
        if (!empty($this->country)) {
            $this->addlabel = $cnames[$this->country];
        }
        $this->sort = false;

        // this is for the aggregation framework
        if (isset($this->limit)) {
            $this->limit_per_day = $this->limit;
        } else {
            $this->limit_per_day = 10;
        }

        if (empty($this->viewData)) {
            $this->viewData = "_UTM_CAMPAIGNS";
        }

        $this->addlabel .= constant($this->viewData);
        $this->help = _UTM_DESC;
    }

    function DisplayReport()
    {
        global $db, $qd;

        if (empty($this->displaymode)) {
            $this->displaymode = $this->DefaultDisplay;
        }

        # get the data from the database
        $data = $this->GetReportData();

        //$data = $this->ConvertData($data);
        if (!empty($this->addlabel)) {
            $this->addlabel .= " | ";
        }
        $this->addlabel .= _GROUPED_BY . " " . constant($this->period);
        $this->ReportHeader();

        if (empty($data)) {
            echoWarning(_NO_DATA_TO_DISPLAY, "margin:5px;");
            return false;
        }

        if ($this->displaymode == 'table') {
            $this->Table($data);
        } elseif ($this->displaymode == 'areachart') {
            $this->StackedAreaChart2($data);
        } elseif ($this->displaymode == 'linechart') {
            $this->LineChart($data);
        }
    }

    function GetReportData()
    {
        $data = $this->rawGetReportData();

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

    function rawGetReportData()
    {
        global $reports;
        $r = new $reports[$this->viewData]["ClassName"]();
        # Reset to default report settings
        if (!empty($this->country)) {
            $r->country = $this->country;
            $r->Settings();
        }

        $r->dataCollectType = "days";
        $r->createDataFiles($this->from, $this->to);
        $d = $r->getTrendDataFromFiles($r->dataFiles($this->from, $this->to));
        //dump($d);
        $data = [];
        foreach ($d as $k => $v) {
            $l = 0;
            if (empty($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));
                $browser = $val[0];
                $visits = $val[1];

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

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

        $temp_d = [];
        foreach ($data as $browser => $v) {
            $temp_d[$browser] = array_sum($v);
        }
        arsort($temp_d);

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

    function ConvertData($data = "")
    {
        //if(empty($data)) { $data = $this->GetReportData(); }

        # transform the data array to a column for each serie
        $data = $this->seriesToColumns($data);
        if (!$data) {
            return $this->EmptyTrendData();
        }

        foreach ($data['fields'] as $key => $countrycode) { // Convert country codes to countries
            if (isset($cnames[$countrycode])) {
                $data['fields'][$key] = $cnames[$countrycode];
                $this->columnDefinitions[] = array("Label" => $cnames[$countrycode]);
            } else {
                $this->columnDefinitions[] = array("Label" => $countrycode);
            }
        }
        $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) == '_UTM_CAMPAIGNS') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='_UTM_CAMPAIGNS' $selected>" . _UTM_CAMPAIGNS . "</option>";
        if (isset($this->viewData) == '_UTM_SOURCES') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='_UTM_SOURCES' $selected>" . _UTM_SOURCES . "</option>";
        if (isset($this->viewData) == '_UTM_MEDIUM') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='_UTM_MEDIUM' $selected>" . _UTM_MEDIUM . "</option>";
        if (isset($this->viewData) == '_UTM_TERM') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='_UTM_TERM' $selected>" . _UTM_TERM . "</option>";
        if (isset($this->viewData) == '_UTM_CONTENT') {
            $selected = 'selected';
        } else {
            $selected = "";
        }
        echo "<option value='_UTM_CONTENT' $selected>" . _UTM_CONTENT . "</option>";
        echo "</select>";
        echo "</div>";
    }

    function UpdateStats($from = '', $to = '', $print = 2)
    {
        # not using datafiles yet
        return false;
    }
}

?>