<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Stats;

/**
 * Class StatsBotsAdmin
 * @package Mnv\Admin\Controllers
 */
class StatsBotsAdmin extends AdminMnv
{
    public $botNameLen = 100;

    public function fetch()
    {

        $stats = new Stats();
        $dateSelector = new StatsDateSelector(false, 'botsDateSelector');
        $typeSelector = new StatsTypeSelector();
        $this->smarty->assign('filterTypeOptions', $typeSelector->get());
        $this->smarty->assign('filterTypeId', $typeSelector->filterTypeId);

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

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

        if (!empty($visitors)) foreach ($visitors as $visitorId => $visitor) {

            if (preg_match("/^(.*?)([a-z0-9\-_\.\/!: ]*(".$this->config['bot_id_regexp'].")[a-z0-9\-_\.\/!: ]*)(.*?)$/i", stripHtml($visitor['userAgent']), $matches)) {
                $lengthLeft = ceil(($this->botNameLen - strlen($matches[2])) / 2);
                if($lengthLeft > 0) $visitors[$visitor['visitorId']]['botName'] = strrev(stringTruncate(strrev($matches[1]), $lengthLeft));

                $visitors[$visitor['visitorId']]['botName'] .= '<b>'.$matches[2].'</b>';

                $lengthLeft = $this->botNameLen - strlen($visitors[$visitor['visitorId']]['botName']) + 7;
                if ($lengthLeft > 0) $visitors[$visitor['visitorId']]['botName'] .= stringTruncate($matches[4], $lengthLeft);
            }

            if (preg_match('/^<b>.+<\/b>$/i', $visitors[$visitor['visitorId']]['botName'])) {
                $visitors[$visitor['visitorId']]['botName'] = preg_replace("/([a-z0-9\-_\.]*(".$this->config['bot_id_regexp'].")[a-z0-9\-_\.]*)/i", '<b>$1</b>', stripHtml($visitor['userAgent']), 1);
            }
        }


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

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

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

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