<?php
/**
 * Google Search Console API Integration
 * Fetch search performance metrics: clicks, impressions, CTR, position
 */

require_once __DIR__ . '/BaseAnalytics.php';

class GoogleSearchConsoleAPI extends SEOAnalyticsBase {

    /**
     * Get search performance metrics
     */
    public function getSearchPerformance($days = 30, $dimensions = ['query', 'page']) {
        if (!$this->checkRateLimit('gsc')) {
            return $this->formatResponse(null, 'error', 'Rate limit exceeded');
        }

        $cache_key = 'gsc_performance_' . implode('_', $dimensions) . '_' . $days;
        $cached = $this->getCache($cache_key);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        $refresh_token = $this->getConfig('google_search_console.refresh_token');
        if (!$refresh_token) {
            return $this->formatResponse(null, 'error', 'GSC not configured');
        }

        try {
            $access_token = $this->getAccessToken($refresh_token);
            
            $start_date = date('Y-m-d', strtotime("-$days days"));
            $end_date = date('Y-m-d');
            
            $data = [
                'startDate' => $start_date,
                'endDate' => $end_date,
                'dimensions' => $dimensions,
                'rowLimit' => 10,
            ];

            $url = 'https://www.googleapis.com/webmasters/v3/sites/' . 
                   urlencode($this->getConfig('google_search_console.property_url')) . 
                   '/searchAnalytics/query?key=' . getenv('GOOGLE_API_KEY');

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

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

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

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

    /**
     * Get indexing status
     */
    public function getIndexingStatus() {
        $cache_key = 'gsc_indexing_status';
        $cached = $this->getCache($cache_key);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $access_token = $this->getAccessToken($this->getConfig('google_search_console.refresh_token'));
            
            $url = 'https://www.googleapis.com/webmasters/v3/sites/' . 
                   urlencode($this->getConfig('google_search_console.property_url')) . 
                   '/sitemaps?key=' . getenv('GOOGLE_API_KEY');

            $headers = ['Authorization: Bearer ' . $access_token];
            $response = $this->makeRequest($url, 'GET', $headers);

            if ($response['code'] === 200) {
                $result = $response['data'];
                $this->setCache($cache_key, $result, 86400); // Cache for 24 hours
                return $this->formatResponse($result);
            }

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

    /**
     * Process search performance data
     */
    private function processSearchPerformance($raw_data) {
        if (!isset($raw_data['rows'])) {
            return [];
        }

        $processed = [];
        foreach ($raw_data['rows'] as $row) {
            $processed[] = [
                'query' => $row['keys'][0] ?? '',
                'page' => $row['keys'][1] ?? '',
                'clicks' => $row['clicks'] ?? 0,
                'impressions' => $row['impressions'] ?? 0,
                'ctr' => round(($row['ctr'] ?? 0) * 100, 2) . '%',
                'position' => round($row['position'] ?? 0, 2),
            ];
        }

        return $processed;
    }

    /**
     * Refresh access token using refresh token
     */
    private function getAccessToken($refresh_token) {
        $client_id = $this->getConfig('google_search_console.client_id');
        $client_secret = $this->getConfig('google_search_console.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 access token');
    }
}
?>
