<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Stats;

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

    public function fetch()
    {
        $stats = new Stats();
        $dateSelector = new StatsDateSelector(false, null);
        $typeSelector = new StatsTypeSelector();
        $this->smarty->assign('filterTypeOptions', $typeSelector->get());
        $this->smarty->assign('filterTypeId', $typeSelector->filterTypeId);

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

        $referers = $stats->getStatsReferer($dateSelector->dateStart, $dateSelector->dateEnd, $typeSelector->filterTypeId, $this->limit, $this->page);

        if (count($referers) > ceil($this->limit / 2)) {
            $splitIndex = ceil($this->limit / 2);
            $this->smarty->assign('hasSplit', true);
        }
        foreach($referers as $i => $referer) {
            if (!empty($splitIndex) && ($i + 1) == $splitIndex) $referers[$i]['isSplit'] = true;
            $referers[$i]['website'] = $referers[$i]['domain'];
            $referers[$i]['website'] = preg_replace('|^[a-z]{3,5}://|i', '', $referers[$i]['website']);
        }

        /* page numbering */
        $totalItems = $stats->getTotalStatsReferer($dateSelector->dateStart, $dateSelector->dateEnd, $typeSelector->filterTypeId);
        $pages = getPageNums($totalItems, $this->page, $this->limit, 0, 4, 4, 0);
        $this->smarty->assign('referers', $referers);
        $this->smarty->assign('pageNums', $pages);
        $this->smarty->assign('page', $this->page);


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

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

    }
}