<?php

/**
 * @desc This report displays a overview of your top cities
 */

//require_once __DIR__.'/../vendor/autoload.php';

$reports["_TOP_CITIES"] = array(
    "ClassName" => "TopCities",
    "Category" => "_LOCATIONS",
    "icon" => "images/icons/32x32/topcities.png",
    "Options" => "daterangeField,profileselector,country,columnSelector,displaymode,limit",
    "Filename" => "top_cities",
    "Distribution" => "Premium",
    "Order" => 3,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 3.0,
    "EmailAlerts" => false,
    "Update" => false
);

class TopCities extends Report
{

    function Settings()
    {
        global $cnames;

        $this->DefaultDisplay = "table";
        $this->DisplayModes = "table,pie";

        $this->columnDefinitions[] = array("Label" => "_CITY");
        $this->columnDefinitions[] = array("Label" => "_UNIQUE_VISITORS");

        if (isset($this->outputmode) && ($this->outputmode == "xml" || $this->outputmode == "json")) {
            $this->columnDefinitions[] = array("Label" => 'longitude', "dataType" => "String");
            $this->columnDefinitions[] = array("Label" => 'latitude', "dataType" => "String");
        }
        if (!empty($this->country)) {
            $this->fileNameExpension = "." . $this->country;
        } else {
            if (!empty($_REQUEST["country"])) {
                $this->fileNameExpension = "." . $_REQUEST["country"];
            } elseif (isset($_REQUEST["country_name"])) {
                # country code unknown check on name..
                $flip = $cnames;
                $flip = array_flip($flip);
                $this->country = $flip[$this->country_name];
                $this->fileNameExpension = "." . $this->country;
            }
        }

        $this->help = _DEFINITIONS_FOR_THIS_REPORT . ':<ul>' . '<li>' . _CITY_DEFINITION . '<li>' . _VISITORS_DEFINITION . '</li></ul><div class=\'indentbody\'>' . _INSTALL_UPDATE_GEO . '</div>';

        if (empty($this->country)) {
            $this->country = "";
        } else {
            $this->addlabel = isset($cnames[$this->country]) . " (" . $this->country . ")";
        }

        $this->sort_order = SORT_DESC;
        $this->sort_key = 1;
    }

    function GetDataFromDb()
    {
        global $db, $gi, $cnames;

        $subq = "select distinct visitorid from {$this->profile->tablename} where timestamp >=" . $db->quote(
                $this->from
            ) . " and timestamp <=" . $db->quote($this->to) . " and country=" . $db->quote($this->country);
        $preq = "select v.ipnumber from ($subq) as a left join {$this->profile->tablename_visitorids} as v on a.visitorid=v.id";

        if (!$gi) {
            return [];
        }

        $loop = $db->Execute($preq);
        $newdata = [];
        while ($loopdata = $loop->FetchRow()) {
            if (is_numeric(substr($loopdata["ipnumber"], -1))) {
                try {
                    $area = $gi->city($loopdata["ipnumber"]);
                } catch (Exception $e) {
                    $area = [];
                }

                if (!empty($area->city->name)) {
                    $city = $area->city->name;
                } else {
                    $city = _UNKNOWN_CITY;
                }

                if (empty($area->raw['location']['longitude']) || empty($area->raw['location']['latitude'])) {
                    break;
                }
                $longitude = $area->raw['location']['longitude'];//$area->longitude;
                $latitude = $area->raw['location']['latitude'];//$area->latitude;

                if ($city == "") {
                    $city = _UNKNOWN;
                }

                $newdata[$city] = $newdata[$city] ?? $newdata[$city] + 1;
                $posdata[$city]['longitude'] = $posdata[$city]['longitude'] ?? $longitude;
                $posdata[$city]['latitude'] = $posdata[$city]['latitude'] ?? $latitude;
            }
        }
        arsort($newdata);

        // now merge it in the stats table format
        $i = 0;
        foreach ($newdata as $key => $val) {
            $data[$i][0] = $key;
            $data[$i][1] = $val;
            $data[$i][2] = $posdata[$key]['longitude'];
            $data[$i][3] = $posdata[$key]['latitude'];
            $i++;
        }

        $query = "data array";

        if (isset($data)) {
            return $data;
        } else {
            $this->columnDefinitions = [];
            $this->columnDefinitions[] = array("Label" => "Notice");
            $this->setupColumnDefinitions();
            return [];
        }
    }


    // function DisplayCustomForm() {
    // 	global $cnames;
    // 	echo "<div class='form-group'>";
    // 		echo "<label for='country'>"._COUNTRY."</label><select class='report_option_field form-control' id='country'>";
    // 		foreach($cnames as $country_code => $countryname) {
    // 			echo "<option"; if(!empty($this->country)) { if($country_code == $this->country) { echo " selected "; } } echo " value='{$country_code}'>{$countryname}</option>";
    // 		}
    // 		echo "</select>";
    // 	echo "</div>";

    // }


    function DisplayReport()
    {
        if (empty($this->country)) {
            echoNotice($this->SettingsButton() . _SELECT . " " . _COUNTRY);
            return;
        } else {
            parent::DisplayReport();
        }
    }

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

