<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\JSONParser\JSONFactory;
use Mnv\Core\YaMetrika\Client;
use Mnv\Core\YaMetrika\YaMetrika;
use Mnv\Core\AdminMnv;

use DateTime;

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

    public function fetch()
    {
        $params = [];
        $counterId = '';
        $token     = '';
        $jsonFile = new JSONFactory('JSON');

        $dateSelector = new StatsDateSelector();

        $startDate = new DateTime($dateSelector->dateStart);
        $endDate = new DateTime($dateSelector->dateEnd);

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

//        print_r($yandex);

        if ($this->action == 'save') {

            $this->smarty->assign('activeItem', 'yandex');
            $this->smarty->assign('title', 'Настройка яндекс метрики');

            $jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/yandex.config.json');
            $jsonFile->writer->deleteRow(0);
            $jsonFile->writer->addRow(['counterId' => $yandex['counterId'], 'token' => $yandex['token'], 'code' => $yandex['code']], false);
            $jsonFile->writer->saveFile('yandex', GLOBAL_ROOT . '/includes/yandex.config.json');

            $this->smarty->assign('action', 'setting');

        } else if ($this->action == 'setting') {

            $this->smarty->assign('activeItem', 'yandex');
            $this->smarty->assign('title', 'Настройка яндекс метрика');

            $jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/yandex.config.json');
            if ($getFile = $jsonFile->parser->getField()) {
                foreach ($getFile as $key => $value) {
                    $params['counterId'] = $value['counterId'];
                    $params['token']     = $value['token'];
                    $params['code']      = $value['code'];
                }
            }

            $this->smarty->assign('yandex', $params);

        } else {

            $this->smarty->assign('activeItem', 'yandex');
            $this->smarty->assign('title', 'Яндекс метрика');

            $jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/yandex.config.json');
            try {
                $getFile = $jsonFile->parser->getField();

                if (isset($getFile[0]['counterId'])) $counterId = $getFile[0]['counterId'];
                if (isset($getFile[0]['token'])) $token = $getFile[0]['token'];

//            $token      = 'y0_AgAEA7qhcbEEAAkGuQAAAADaNHZT6j0iANpcSomMh-F7O70EtUA9NE4';
//            $counterId  = '90824259';
                if (!empty($token) && !empty($counterId)) {
                    $client = new Client($token, $counterId);
                    $metrika = new YaMetrika($client);

//                  $visitors = $metrika->getVisitors();
                    $visitors = $metrika->getVisitorsForPeriod($startDate, $endDate);
                    $geoForPeriod = $metrika->getGeoForPeriod($startDate, $endDate);
                    $usersSearchEngine = $metrika->getUsersSearchEngineForPeriod($startDate, $endDate);
                    $browsers = $metrika->getBrowsersForPeriod($startDate, $endDate);
                    $phrases = $metrika->getSearchPhrasesForPeriod($startDate, $endDate);
                    $viewedPages = $metrika->getMostViewedPagesForPeriod($startDate, $endDate);
                    $ages = $metrika->getAgeForPeriod($startDate, $endDate);

//        print_r($visitors->formatData());
//        print_r($browsers->formatData());
//        print_r($viewedPages->formatData());
//        print_r($ageGenders->formatData());
//        print_r($geoForPeriod->formatData());
//        print_r($usersSearchEngine->formatData());
//        print_r($ages->formatData());

                    $this->smarty->assign('visitors', $visitors->formatData());
                    $this->smarty->assign('browsers', $browsers->formatData());
                    $this->smarty->assign('phrases', $phrases->formatData());
                    $this->smarty->assign('viewedPages', $viewedPages->formatData());
//                    $this->smarty->assign('ageGenders', $ageGenders->formatData());
                    $this->smarty->assign('ages', $ages->formatData());
                    $this->smarty->assign('geoForPeriod', $geoForPeriod->formatData());
                    $this->smarty->assign('usersSearchEngine', $usersSearchEngine->formatData());
                } else {
                    $this->messages['token_counter'] = true;
                }
            } catch (\Exception $e) {
                print $e->getMessage();
            }
        }

        $this->smarty->assign('message', $this->messages);

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

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

}

