<?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" => "New Visitor",
                        "column-1" => round(intval($data[ 'new' ]), 2),
                    ],
                    [
                        "category" => "Returning Visitor",
                        "column-1" => 100 - round(intval($data[ 'new' ]), 2),
                    ],
                ],
                'browsers'  => $this->renderPartial(
                    '_table',
                    [
                        'data' => $browsers,
                        'name' => 'Browser',
                    ]
                ),
                'cityes'    => $this->renderPartial(
                    '_table',
                    [
                        'data' => $cityes,
                        'name' => 'City',
                    ]
                ),
                'countries' => $this->renderPartial(
                    '_table',
                    [
                        'data' => $countries,
                        'name' => 'Country',
                    ]
                ),
                'sessions'  => (int) $data[ 'sessions' ],
                'users'     => (int) $data[ 'users' ],
                'views'     => (int) $data[ 'views' ],
                'newusers'  => round(intval($data[ 'new' ]), 2),
            ];
        }
        
    }