<?php
    namespace backend\models;
    
    use yii\base\Model;
    
    /**
     * Class Analytics
     *
     * @package backend\models
     */
    class Analytics extends Model
    {
        public $viewId;
        
        /**
         * Preparing and querying data
         *
         * @return \Google_Service_AnalyticsReporting_GetReportsResponse
         */
        private function executeQuery()
        {
            $client = new \Google_Client();
            
            $client->setAuthConfig(\Yii::getAlias('@common/config/Artbox-85b8559147bc.json'));
            $client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
            
            $analytics = new \Google_Service_AnalyticsReporting($client);
            
            $profile_id = $this->viewId;
            
            $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
            $dateRange->setStartDate("30daysAgo");
            $dateRange->setEndDate("today");
            
            /**
             * Setting metrics and dimensions for first query
             */
            $sessions = new \Google_Service_AnalyticsReporting_Metric();
            $sessions->setExpression('ga:sessions');
            $sessions->setAlias('Сессии');
            
            $users = new \Google_Service_AnalyticsReporting_Metric();
            $users->setExpression('ga:users');
            $users->setAlias('Пользователи');
            
            $views = new \Google_Service_AnalyticsReporting_Metric();
            $views->setExpression('ga:pageviews');
            $views->setAlias('Просмотры');
            
            $new_sessions = new \Google_Service_AnalyticsReporting_Metric();
            $new_sessions->setExpression('ga:percentNewSessions');
            $new_sessions->setAlias('Новые сессии');
            
            $dimensions = new \Google_Service_AnalyticsReporting_Dimension();
            $dimensions->setName('ga:date');
            
            $request = new \Google_Service_AnalyticsReporting_ReportRequest();
            $request->setViewId($profile_id);
            $request->setDateRanges($dateRange);
            $request->setMetrics(
                [
                    $sessions,
                    $users,
                    $views,
                    $new_sessions,
                ]
            );
            $request->setDimensions($dimensions);
            
            /**
             * Setting parameters for second query
             */
            $sessions2 = new \Google_Service_AnalyticsReporting_Metric();
            $sessions2->setExpression('ga:sessions');
            $new_sessions->setAlias('Сессии 2');
            
            $browser = new \Google_Service_AnalyticsReporting_Dimension();
            $browser->setName('ga:browser');
            
            $city = new \Google_Service_AnalyticsReporting_Dimension();
            $city->setName('ga:city');
            
            $country = new \Google_Service_AnalyticsReporting_Dimension();
            $country->setName('ga:country');
            
            $request2 = new \Google_Service_AnalyticsReporting_ReportRequest();
            $request2->setViewId($profile_id);
            $request2->setDateRanges($dateRange);
            $request2->setMetrics($sessions2);
            $request2->setDimensions(
                [
                    $browser,
                    $city,
                    $country,
                ]
            );
            
            $ordering = new \Google_Service_AnalyticsReporting_OrderBy();
            $ordering->setFieldName("ga:sessions");
            $ordering->setOrderType("VALUE");
            $ordering->setSortOrder("DESCENDING");
            $request2->setOrderBys($ordering);
            
            $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
            $body->setReportRequests(
                [
                    $request,
                    $request2,
                ]
            );
            $response = $analytics->reports->batchGet($body);
            
            return $response;
        }
        
        /**
         * Generates data for view
         *
         * @return array
         */
        public function generateData()
        {
            $reports = $this->executeQuery();
            $data = [];
            
            /**
             * Generating data for Sessions and users
             */
            $report = $reports[ 0 ];
            $header = $report->getColumnHeader();
            $dimensionHeaders = $header->getDimensions();
            $metricHeaders = $header->getMetricHeader()
                                    ->getMetricHeaderEntries();
            $rows = $report->getData()
                           ->getRows();
            $totals = $report->getData()
                             ->getTotals();
            $total_values = $totals[ 0 ]->getValues();
            
            $data[ 'sessions' ] = $total_values[ 0 ];
            $data[ 'users' ] = $total_values[ 1 ];
            $data[ 'views' ] = $total_values[ 2 ];
            $data[ 'new' ] = $total_values[ 3 ];
            
            for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
                $row = $rows[ $rowIndex ];
                
                $dimensions = $row->getDimensions();
                for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
                    $data[ 'plot' ][ $rowIndex ][ 'day' ] = date('d-m-Y', strtotime($dimensions[ $i ]));
                }
                
                $metrics = $row->getMetrics();
                for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++) {
                    $values = $metrics[ $j ];
                    for ($valueIndex = 0; $valueIndex < count($values->getValues()); $valueIndex++) {
                        if ($valueIndex === 0) {
                            $name = 'sessions';
                        } elseif ($valueIndex === 1) {
                            $name = 'users';
                        } else {
                            continue;
                        }
                        $value = $values->getValues()[ $valueIndex ];
                        $data[ 'plot' ][ $rowIndex ][ $name ] = (int) $value;
                    }
                }
            }
            
            /**
             * Generating data for tabs,
             * with browser, city and country statistics
             */
            $data2 = [];
            
            $report = $reports[ 1 ];
            $header = $report->getColumnHeader();
            //            $dimensionHeaders = $header->getDimensions();
            $metricHeaders = $header->getMetricHeader()
                                    ->getMetricHeaderEntries();
            $rows = $report->getData()
                           ->getRows();
            
            for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
                $row = $rows[ $rowIndex ];
                
                $metrics = $row->getMetrics();
                for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++) {
                    $values = $metrics[ $j ];
                    for ($valueIndex = 0; $valueIndex < count($values->getValues()); $valueIndex++) {
                        $value = $values->getValues()[ $valueIndex ];
                        $currentValue = (int) $value;
                    }
                }
                
                $dimensions = $row->getDimensions();
                foreach ($dimensions as $key => $dimension) {
                    if (empty( $data2[ $key ][ $dimension ] )) {
                        $data2[ $key ][ $dimension ] = $currentValue;
                    } else {
                        $data2[ $key ][ $dimension ] += $currentValue;
                    }
                }
            }
            
            $data[ 'table' ] = $data2;
            
            return $data;
        }
    }