<?php
namespace Crawl\Services;

/**
 * Google Search Console Search Analytics API wrapper.
 */
class GSCService
{
    private const API_BASE = 'https://www.googleapis.com/webmasters/v3';

    private GoogleOAuthService $oauth;

    public function __construct()
    {
        $this->oauth = new GoogleOAuthService();
    }

    // Summary: total clicks, impressions, avg CTR, avg position for last N days
    public function getSummary(int $projectId, string $siteUrl, int $days = 30): array
    {
        $token = $this->oauth->getAccessToken($projectId, 'gsc');
        if (!$token) return ['error' => 'not_connected'];

        $data = $this->query($token, $siteUrl, [
            'startDate'  => date('Y-m-d', strtotime("-{$days} days")),
            'endDate'    => date('Y-m-d'),
            'rowLimit'   => 1,
        ]);

        if (isset($data['error'])) return ['error' => $data['error']['message'] ?? 'API error'];

        $row = $data['rows'][0] ?? [];
        return [
            'clicks'      => (int)($row['clicks']      ?? 0),
            'impressions' => (int)($row['impressions'] ?? 0),
            'ctr'         => round((float)($row['ctr'] ?? 0) * 100, 2),
            'position'    => round((float)($row['position'] ?? 0), 1),
        ];
    }

    // Top queries: query | clicks | impressions | ctr | position
    public function getTopQueries(int $projectId, string $siteUrl, int $days = 30, int $limit = 50): array
    {
        $token = $this->oauth->getAccessToken($projectId, 'gsc');
        if (!$token) return [];

        $data = $this->query($token, $siteUrl, [
            'startDate'  => date('Y-m-d', strtotime("-{$days} days")),
            'endDate'    => date('Y-m-d'),
            'dimensions' => ['query'],
            'rowLimit'   => $limit,
        ]);

        $rows = [];
        foreach ($data['rows'] ?? [] as $row) {
            $rows[] = [
                'query'       => $row['keys'][0] ?? '',
                'clicks'      => (int)$row['clicks'],
                'impressions' => (int)$row['impressions'],
                'ctr'         => round((float)$row['ctr'] * 100, 2),
                'position'    => round((float)$row['position'], 1),
            ];
        }
        return $rows;
    }

    // Per-page performance: URL | clicks | impressions | ctr | position
    public function getPagePerformance(int $projectId, string $siteUrl, int $days = 30, int $limit = 100): array
    {
        $token = $this->oauth->getAccessToken($projectId, 'gsc');
        if (!$token) return [];

        $data = $this->query($token, $siteUrl, [
            'startDate'  => date('Y-m-d', strtotime("-{$days} days")),
            'endDate'    => date('Y-m-d'),
            'dimensions' => ['page'],
            'rowLimit'   => $limit,
        ]);

        $rows = [];
        foreach ($data['rows'] ?? [] as $row) {
            $rows[] = [
                'url'         => $row['keys'][0] ?? '',
                'clicks'      => (int)$row['clicks'],
                'impressions' => (int)$row['impressions'],
                'ctr'         => round((float)$row['ctr'] * 100, 2),
                'position'    => round((float)$row['position'], 1),
            ];
        }
        return $rows;
    }

    private function query(string $token, string $siteUrl, array $payload): array
    {
        $encodedUrl = rawurlencode($siteUrl);
        $url = self::API_BASE . "/sites/{$encodedUrl}/searchAnalytics/query";
        $ctx = stream_context_create(['http' => [
            'method'  => 'POST',
            'header'  => "Authorization: Bearer {$token}\r\nContent-Type: application/json\r\n",
            'content' => json_encode($payload),
            'ignore_errors' => true,
        ]]);
        $body = @file_get_contents($url, false, $ctx);
        return $body ? (json_decode($body, true) ?? []) : ['error' => ['message' => 'No response']];
    }
}
