<?php
/**
 * Google Analytics 4 Realtime API Integration
 * Track active users, device breakdown, traffic per minute
 */

require_once __DIR__ . '/BaseAnalytics.php';

class GoogleAnalytics4API extends SEOAnalyticsBase {

    /**
     * Get realtime active users
     */
    public function getRealtimeUsers() {
        if (!$this->checkRateLimit('ga4_realtime')) {
            return $this->formatResponse(null, 'error', 'Rate limit exceeded');
        }

        $cache_key = 'ga4_realtime_users';
        $cached = $this->getCache($cache_key, 60); // Cache for 60 seconds
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $access_token = $this->getAccessToken($this->getConfig('google_analytics.refresh_token'));
            $property_id = $this->getConfig('google_analytics.property_id');

            $url = "https://analyticsreporting.googleapis.com/v4/properties/{$property_id}:runRealtimeReport";

            $data = [
                'dimensions' => [
                    ['name' => 'deviceCategory'],
                ],
                'metrics' => [
                    ['name' => 'activeUsers'],
                ],
            ];

            $headers = [
                'Authorization: Bearer ' . $access_token,
                'Content-Type: application/json',
            ];

            $response = $this->makeRequest($url, 'POST', $headers, $data);

            if ($response['code'] === 200) {
                $result = $this->processRealtimeData($response['data']);
                $this->setCache($cache_key, $result, 60);
                return $this->formatResponse($result);
            }

            return $this->formatResponse(null, 'error', 'Failed to fetch realtime data');
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Get traffic trends (hourly data)
     */
    public function getTrafficTrends($hours = 24) {
        $cache_key = 'ga4_traffic_trends_' . $hours;
        $cached = $this->getCache($cache_key, 300); // Cache for 5 minutes
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $access_token = $this->getAccessToken($this->getConfig('google_analytics.refresh_token'));
            $property_id = $this->getConfig('google_analytics.property_id');

            $start_date = date('Y-m-d', strtotime("-$hours hours"));
            $end_date = date('Y-m-d');

            $url = "https://analyticsdata.googleapis.com/v1beta/properties/{$property_id}:runReport";

            $data = [
                'dateRanges' => [
                    [
                        'startDate' => $start_date,
                        'endDate' => $end_date,
                    ],
                ],
                'dimensions' => [
                    ['name' => 'dateHourMinute'],
                ],
                'metrics' => [
                    ['name' => 'activeUsers'],
                    ['name' => 'sessions'],
                    ['name' => 'screenPageViews'],
                ],
                'orderBys' => [
                    ['dimension' => ['orderType' => 'ALPHANUMERIC', 'name' => 'dateHourMinute']],
                ],
                'limit' => 1000,
            ];

            $headers = [
                'Authorization: Bearer ' . $access_token,
                'Content-Type: application/json',
            ];

            $response = $this->makeRequest($url, 'POST', $headers, $data);

            if ($response['code'] === 200) {
                $result = $this->processTrafficTrends($response['data']);
                $this->setCache($cache_key, $result, 300);
                return $this->formatResponse($result);
            }

            return $this->formatResponse(null, 'error', 'Failed to fetch traffic trends');
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Get top landing pages
     */
    public function getTopPages($days = 30) {
        $cache_key = 'ga4_top_pages_' . $days;
        $cached = $this->getCache($cache_key);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $access_token = $this->getAccessToken($this->getConfig('google_analytics.refresh_token'));
            $property_id = $this->getConfig('google_analytics.property_id');

            $start_date = date('Y-m-d', strtotime("-$days days"));
            $end_date = date('Y-m-d');

            $url = "https://analyticsdata.googleapis.com/v1beta/properties/{$property_id}:runReport";

            $data = [
                'dateRanges' => [['startDate' => $start_date, 'endDate' => $end_date]],
                'dimensions' => [['name' => 'pagePath']],
                'metrics' => [
                    ['name' => 'screenPageViews'],
                    ['name' => 'sessions'],
                    ['name' => 'engagementRate'],
                ],
                'orderBys' => [['metric' => ['name' => 'screenPageViews'], 'descending' => true]],
                'limit' => 10,
            ];

            $headers = ['Authorization: Bearer ' . $access_token, 'Content-Type: application/json'];
            $response = $this->makeRequest($url, 'POST', $headers, $data);

            if ($response['code'] === 200) {
                $result = $this->processTopPages($response['data']);
                $this->setCache($cache_key, $result);
                return $this->formatResponse($result);
            }

            return $this->formatResponse(null, 'error', 'Failed to fetch top pages');
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Process realtime data
     */
    private function processRealtimeData($data) {
        $result = ['total' => 0, 'by_device' => []];
        
        if (isset($data['rows'])) {
            foreach ($data['rows'] as $row) {
                $device = $row['dimensionValues'][0]['value'] ?? 'unknown';
                $users = intval($row['metricValues'][0]['value'] ?? 0);
                $result['by_device'][$device] = $users;
                $result['total'] += $users;
            }
        }

        return $result;
    }

    /**
     * Process traffic trends
     */
    private function processTrafficTrends($data) {
        $result = [];
        
        if (isset($data['rows'])) {
            foreach ($data['rows'] as $row) {
                $timestamp = $row['dimensionValues'][0]['value'] ?? '';
                $result[] = [
                    'timestamp' => $timestamp,
                    'active_users' => intval($row['metricValues'][0]['value'] ?? 0),
                    'sessions' => intval($row['metricValues'][1]['value'] ?? 0),
                    'pageviews' => intval($row['metricValues'][2]['value'] ?? 0),
                ];
            }
        }

        return $result;
    }

    /**
     * Process top pages
     */
    private function processTopPages($data) {
        $result = [];
        
        if (isset($data['rows'])) {
            foreach ($data['rows'] as $row) {
                $result[] = [
                    'page' => $row['dimensionValues'][0]['value'] ?? '',
                    'pageviews' => intval($row['metricValues'][0]['value'] ?? 0),
                    'sessions' => intval($row['metricValues'][1]['value'] ?? 0),
                    'engagement_rate' => round(floatval($row['metricValues'][2]['value'] ?? 0) * 100, 2) . '%',
                ];
            }
        }

        return $result;
    }

    /**
     * Get access token
     */
    private function getAccessToken($refresh_token) {
        $client_id = $this->getConfig('google_analytics.client_id');
        $client_secret = $this->getConfig('google_analytics.client_secret');

        $data = [
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'refresh_token' => $refresh_token,
            'grant_type' => 'refresh_token',
        ];

        $response = $this->makeRequest('https://oauth2.googleapis.com/token', 'POST', 
            ['Content-Type: application/json'], $data);

        if ($response['code'] === 200 && isset($response['data']['access_token'])) {
            return $response['data']['access_token'];
        }

        throw new Exception('Failed to refresh GA4 token');
    }
}
?>
