<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;
use Mnv\Models\Stats;

/**
 * Class StatsVisitorsAdmin
 * @package Mnv\Admin\Controllers
 */
class StatsVisitorsAdmin extends AdminMnv
{

    public function fetch()
    {
        $stats = new Stats();
        $dateSelector = new StatsDateSelector(false, null);
        $typeSelector = new StatsTypeSelector();

        $this->smarty->assign('activeItem', 'visitors');
        $this->smarty->assign('title', lang('stats:visitorsTitle'));

        $domain = $this->request->get('domain','');

        $visitors = $stats->getStatsVisitors($dateSelector->dateStart, $dateSelector->dateEnd, $typeSelector->filterTypeId, $domain, $this->limit, $this->page);
        if (!empty($visitors)) foreach ($visitors as $visitor) {
            $visitor['firstVisitOn'] = langDate(adjustTime($visitor['firstVisitOn'], false, 'd.m.Y H:i'));
            if (!empty($visitor['referer'])) {
                $result = parseReferer($visitor['referer']);
                $visitor['refererUrl'] = $result['refererUrl'];
                if (isset($result['refererWebsite'])) $visitor['refererWebsite'] = $result['refererWebsite'];
            }
            $visitors[$visitor['visitorId']] = $visitor;
        }

        /** page numbering */
        $totalItems = $stats->getTotalStatsVisitors($dateSelector->dateStart, $dateSelector->dateEnd, $typeSelector->filterTypeId, $domain);
        $pages = getPageNums($totalItems, $this->page, $this->limit, 2, 4, 4, 2);

        $this->smarty->assign('filterTypeOptions', $typeSelector->get());
        $this->smarty->assign('filterTypeId', $typeSelector->filterTypeId);
        $this->smarty->assign('visitors', $visitors);
        $this->smarty->assign('pageNums', $pages);
        $this->smarty->assign('totalItems', $totalItems);
        $this->smarty->assign('page', $this->page);



        if ($this->permissions('visitors')) {
            return $this->smarty->fetch('views/stats/visitors.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');
    }

}

