<?php
namespace Crawl\Services;

/**
 * Google Business Profile (formerly My Business) API wrapper.
 * Requires Business Profile API access — additional Google Cloud setup needed.
 */
class GBPService
{
    private const API_BASE = 'https://mybusinessbusinessinformation.googleapis.com/v1';
    private const INSIGHTS_BASE = 'https://businessprofileperformance.googleapis.com/v1';

    private GoogleOAuthService $oauth;

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

    // Business profile metrics: views, searches, direction_requests, calls (last N days)
    public function getMetrics(int $projectId, string $locationName, int $days = 30): array
    {
        $token = $this->oauth->getAccessToken($projectId, 'gbp');
        if (!$token) return ['error' => 'not_connected'];

        $endDate   = new \DateTime();
        $startDate = (new \DateTime())->modify("-{$days} days");

        $url = self::INSIGHTS_BASE . "/{$locationName}:getDailyMetrics?" . http_build_query([
            'dailyRange.start_date.year'  => $startDate->format('Y'),
            'dailyRange.start_date.month' => $startDate->format('n'),
            'dailyRange.start_date.day'   => $startDate->format('j'),
            'dailyRange.end_date.year'    => $endDate->format('Y'),
            'dailyRange.end_date.month'   => $endDate->format('n'),
            'dailyRange.end_date.day'     => $endDate->format('j'),
            'dailyMetric'                 => 'BUSINESS_IMPRESSIONS_MOBILE_MAPS',
        ]);

        $ctx  = stream_context_create(['http' => [
            'header' => "Authorization: Bearer {$token}\r\n",
            'ignore_errors' => true,
        ]]);
        $body = @file_get_contents($url, false, $ctx);
        $data = $body ? json_decode($body, true) : [];

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

        return [
            'impressions_maps'   => $this->sumMetric($data),
            'location_name'      => $locationName,
            'period_days'        => $days,
        ];
    }

    private function sumMetric(array $data): int
    {
        $total = 0;
        foreach ($data['timeSeries']['datedValues'] ?? [] as $dv) {
            $total += (int)($dv['value'] ?? 0);
        }
        return $total;
    }
}
