$msg]; } // Load API key from .env $apiKey = env('SERPAPI_KEY'); if (!$apiKey) { $msg = 'SERPAPI_KEY not found in environment variables'; \Log::error($msg); return ['error' => $msg]; } $endpoint = 'https://serpapi.com/search.json'; $response = Http::get($endpoint, [ 'engine' => 'google_scholar_author', 'author_id' => $profileId, 'api_key' => $apiKey, ]); if (!$response->successful()) { $status = $response->status(); $body = $response->body(); \Log::error('Scholar API request failed', ['status' => $status, 'body' => $body]); return ['error' => 'Scholar API request failed: ' . $status, 'body' => $body]; } $json = $response->json(); // Support multiple possible structures $articles = $json['articles'] ?? $json['publications'] ?? $json['results'] ?? []; if (empty($articles)) { \Log::warning('Scholar API returned no articles', ['profileId' => $profileId, 'response' => $json]); return ['error' => 'No publications returned by Scholar API', 'raw' => $json]; } // ✅ Format and return $formatted = collect($articles) ->map(function ($a) { return [ 'title' => $a['title'] ?? $a['name'] ?? null, 'authors' => $a['authors'] ?? ($a['author'] ?? null), 'journal' => $a['publication'] ?? $a['journal'] ?? null, 'year' => $a['year'] ?? ($a['publication_year'] ?? null), 'link' => $a['link'] ?? $a['citation_link'] ?? null, ]; }) ->toArray(); return ['data' => $formatted]; } catch (\Throwable $e) { \Log::error('ScholarService API error: ' . $e->getMessage()); return []; } } }