<?php
    
    namespace backend\controllers;

    use backend\models\Analytics;
    use common\models\Settings;
    use yii\filters\VerbFilter;
    use yii\web\Controller;
    use yii\web\Response;
    
    class AjaxController extends Controller
    {
        public $enableCsrfValidation = false;
        
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'analytics' => [ 'post' ],
                    ],
                ],
            ];
        }
        
        public function actionAnalytics()
        {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            
            $settings = Settings::getInstance();
            
            $analytics = new Analytics(
                [
                    'viewId' => $settings->analytics_key,
                ]
            );
            $data = $analytics->generateData();
            
            $browsers = $data[ 'table' ][ 0 ];
            arsort($browsers);
            
            $cityes = $data[ 'table' ][ 1 ];
            arsort($cityes);
            
            $countries = $data[ 'table' ][ 2 ];
            arsort($countries);
            
            return [
                'plot'      => $data[ 'plot' ],
                'pie'       => [
                    [
                        "category" => "Новых посетителей",
                        "column-1" => round(intval($data[ 'new' ]), 2),
                    ],
                    [
                        "category" => "Вернувшихся посетителей",
                        "column-1" => 100 - round(intval($data[ 'new' ]), 2),
                    ],
                ],
                'browsers'  => $this->renderPartial(
                    '_table',
                    [
                        'data' => $browsers,
                        'name' => 'Браузер',
                    ]
                ),
                'cityes'    => $this->renderPartial(
                    '_table',
                    [
                        'data' => $cityes,
                        'name' => 'Город',
                    ]
                ),
                'countries' => $this->renderPartial(
                    '_table',
                    [
                        'data' => $countries,
                        'name' => 'Страна',
                    ]
                ),
                'sessions'  => (int) $data[ 'sessions' ],
                'users'     => (int) $data[ 'users' ],
                'views'     => (int) $data[ 'views' ],
                'newusers'  => round(intval($data[ 'new' ]), 2),
            ];
        }
    }