<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use App\Models\Setting;
class GoogleReviewsService {
public function fetchReviews(string $placeId): array {
$apiKey = Setting::get('google_maps_api_key') ?? config('services.google.maps_api_key');
if (!$apiKey) throw new \Exception('Google Maps API key not configured in Site Settings.');
$response = Http::timeout(15)->get('https://maps.googleapis.com/maps/api/place/details/json', [
'place_id' => $placeId,
'fields' => 'reviews',
'key' => $apiKey,
]);
if (!$response->ok()) throw new \Exception('Google Places API request failed: ' . $response->status());
$data = $response->json();
if (($data['status'] ?? '') !== 'OK') throw new \Exception('Google Places API error: ' . ($data['status'] ?? 'Unknown'));
$reviews = $data['result']['reviews'] ?? [];
return collect($reviews)
->filter(fn($r) => ($r['rating'] ?? 0) >= 4)
->map(fn($r) => [
'source' => 'google_review',
'client_name' => $r['author_name'],
'quote' => $r['text'],
'rating' => (int) $r['rating'],
'photo' => $r['profile_photo_url'] ?? null,
'google_review_id' => md5($r['author_name'] . ($r['time'] ?? '')),
'status' => 'draft',
])
->values()
->toArray();
}
public function importToDrafts(string $placeId): int {
$reviews = $this->fetchReviews($placeId);
$imported = 0;
foreach ($reviews as $review) {
if (!\App\Models\Testimonial::where('google_review_id', $review['google_review_id'])->exists()) {
\App\Models\Testimonial::create($review);
$imported++;
}
}
return $imported;
}
}