'RP', 7 => 'EC', 8 => 'E', 9 => 'E10+', 10 => 'T', 11 => 'M', 12 => 'AO']; private const PEGI_LABELS = [1 => '3', 2 => '7', 3 => '12', 4 => '16', 5 => '18']; public function __construct() { $this->client = new Client(['timeout' => 10]); $this->clientId = config('services.igdb.client_id'); $this->clientSecret = config('services.igdb.client_secret'); $this->baseUrl = config('services.igdb.base_url', 'https://api.igdb.com/v4'); } /** * Get or refresh the OAuth access token (cached for 55 days). */ protected function getAccessToken(): string { return Cache::remember('igdb_access_token', 60 * 60 * 24 * 55, function () { $response = $this->client->post('https://id.twitch.tv/oauth2/token', [ 'form_params' => [ 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'client_credentials', ], ]); $data = json_decode($response->getBody(), true); return $data['access_token']; }); } /** * Make an authenticated POST request to the IGDB API. */ protected function query(string $endpoint, string $body): array { try { $response = $this->client->post("{$this->baseUrl}/{$endpoint}", [ 'headers' => [ 'Client-ID' => $this->clientId, 'Authorization' => 'Bearer ' . $this->getAccessToken(), 'Accept' => 'application/json', ], 'body' => $body, ]); return json_decode($response->getBody(), true) ?? []; } catch (\Exception $e) { Log::error("IGDB API error [{$endpoint}]: " . $e->getMessage()); return []; } } private function extendedFields(): string { return 'id,name,slug,summary,storyline,cover.image_id,first_release_date, genres.id,genres.name,genres.slug, platforms.id,platforms.name,platforms.slug,platforms.abbreviation, involved_companies.company.id,involved_companies.company.name, involved_companies.company.slug,involved_companies.developer, involved_companies.publisher,involved_companies.porting, screenshots.image_id, rating,rating_count, aggregated_rating,aggregated_rating_count, collection.id,collection.name,collection.slug, game_modes.id,game_modes.name,game_modes.slug, themes.id,themes.name,themes.slug, player_perspectives.id,player_perspectives.name,player_perspectives.slug, videos.id,videos.name,videos.video_id, websites.category,websites.url, age_ratings.category,age_ratings.rating, similar_games'; } /** * Search games by title. */ public function searchGames(string $query, int $limit = 10): array { return $this->query('games', " search \"{$query}\"; fields id,name,slug,summary,cover.image_id,first_release_date, genres.name,genres.slug,platforms.name,platforms.abbreviation, involved_companies.company.name,involved_companies.developer, rating,rating_count; limit {$limit}; "); } /** * Get a single game by IGDB ID with full details. */ public function getGame(int $igdbId): ?array { $results = $this->query('games', " fields {$this->extendedFields()}; where id = {$igdbId}; limit 1; "); return $results[0] ?? null; } /** * Fetch fresh extended data for a set of IGDB IDs (for backfill). */ public function getGamesByIds(array $igdbIds): array { $ids = implode(',', $igdbIds); return $this->query('games', " fields {$this->extendedFields()}; where id = ({$ids}); limit " . count($igdbIds) . "; "); } /** * Get popular games (by rating and rating count). */ public function getPopularGames(int $limit = 20, int $offset = 0): array { return $this->query('games', " fields {$this->extendedFields()}; where rating != null & rating_count > 100 & cover != null; sort rating_count desc; limit {$limit}; offset {$offset}; "); } /** * Get games for backfill — broader filter than getPopularGames. */ public function getPopularGamesForBackfill(int $limit = 500, int $offset = 0, int $minRatings = 5): array { return $this->query('games', " fields {$this->extendedFields()}; where rating != null & rating_count > {$minRatings} & cover != null; sort rating_count desc; limit {$limit}; offset {$offset}; "); } /** * Get recently released games. */ public function getNewReleases(int $limit = 10): array { $timestamp = now()->subMonths(3)->timestamp; $now = now()->timestamp; return $this->query('games', " fields {$this->extendedFields()}; where first_release_date >= {$timestamp} & first_release_date <= {$now} & cover != null; sort first_release_date desc; limit {$limit}; "); } /** * Get games released in a given year. */ public function getGamesByYear(int $year, int $limit = 20, int $offset = 0): array { $from = mktime(0, 0, 0, 1, 1, $year); $to = mktime(23, 59, 59, 12, 31, $year); return $this->query('games', " fields {$this->extendedFields()}; where first_release_date >= {$from} & first_release_date <= {$to} & cover != null; sort rating_count desc; limit {$limit}; offset {$offset}; "); } /** * Get games for a given platform IGDB ID. */ public function getGamesByPlatform(int $platformIgdbId, int $limit = 20, int $offset = 0): array { return $this->query('games', " fields {$this->extendedFields()}; where platforms = [{$platformIgdbId}] & cover != null & rating != null; sort rating_count desc; limit {$limit}; offset {$offset}; "); } /** * Get games by genre. */ public function getGamesByGenre(int $genreIgdbId, int $limit = 20, int $offset = 0): array { return $this->query('games', " fields id,name,slug,summary,cover.image_id,first_release_date, genres.name,genres.slug,platforms.abbreviation, rating,rating_count; where genres = [{$genreIgdbId}] & cover != null & rating != null; sort rating desc; limit {$limit}; offset {$offset}; "); } /** * Sync all extended IGDB data onto a Game model. */ public function syncExtendedData(Game $game, array $data): void { $updates = []; // Collection if (!empty($data['collection'])) { $col = $data['collection']; $collection = Collection::firstOrCreate( ['igdb_id' => $col['id']], ['name' => $col['name'], 'slug' => $col['slug'] ?? \Str::slug($col['name'])] ); $updates['collection_id'] = $collection->id; } // Storyline if (!empty($data['storyline'])) { $updates['storyline'] = $data['storyline']; } // Aggregated rating (critics) if (isset($data['aggregated_rating'])) { $updates['aggregated_rating'] = round($data['aggregated_rating'], 2); } if (isset($data['aggregated_rating_count'])) { $updates['aggregated_rating_count'] = $data['aggregated_rating_count']; } // Age ratings if (!empty($data['age_ratings'])) { foreach ($data['age_ratings'] as $ar) { if (($ar['category'] ?? null) === 1 && isset($ar['rating'])) { $updates['age_rating_esrb'] = self::ESRB_LABELS[$ar['rating']] ?? null; } if (($ar['category'] ?? null) === 2 && isset($ar['rating'])) { $updates['age_rating_pegi'] = self::PEGI_LABELS[$ar['rating']] ?? null; } } } // Similar games — store IGDB IDs for later resolution if (!empty($data['similar_games'])) { $updates['similar_game_igdb_ids'] = array_values( array_filter(array_map(fn($s) => is_array($s) ? ($s['id'] ?? null) : $s, $data['similar_games'])) ); } if (!empty($updates)) { $game->update($updates); } // Game modes if (!empty($data['game_modes'])) { $ids = []; foreach ($data['game_modes'] as $gm) { $model = GameMode::firstOrCreate( ['igdb_id' => $gm['id']], ['name' => $gm['name'], 'slug' => $gm['slug'] ?? \Str::slug($gm['name'])] ); $ids[] = $model->id; } $game->gameModes()->sync($ids); } // Themes if (!empty($data['themes'])) { $ids = []; foreach ($data['themes'] as $t) { $model = Theme::firstOrCreate( ['igdb_id' => $t['id']], ['name' => $t['name'], 'slug' => $t['slug'] ?? \Str::slug($t['name'])] ); $ids[] = $model->id; } $game->themes()->sync($ids); } // Player perspectives if (!empty($data['player_perspectives'])) { $ids = []; foreach ($data['player_perspectives'] as $pp) { $model = PlayerPerspective::firstOrCreate( ['igdb_id' => $pp['id']], ['name' => $pp['name'], 'slug' => $pp['slug'] ?? \Str::slug($pp['name'])] ); $ids[] = $model->id; } $game->playerPerspectives()->sync($ids); } // Videos if (isset($data['videos'])) { GameVideo::where('game_id', $game->id)->delete(); foreach ($data['videos'] as $v) { if (empty($v['video_id'])) continue; GameVideo::create([ 'game_id' => $game->id, 'igdb_id' => $v['id'] ?? null, 'name' => $v['name'] ?? null, 'video_id' => $v['video_id'], ]); } } // Websites if (isset($data['websites'])) { GameWebsite::where('game_id', $game->id)->delete(); foreach ($data['websites'] as $w) { if (empty($w['url'])) continue; GameWebsite::create([ 'game_id' => $game->id, 'category' => $w['category'], 'url' => $w['url'], ]); } } // Involved companies (update existing game_company pivot with richer data) if (!empty($data['involved_companies'])) { $companyPivot = []; foreach ($data['involved_companies'] as $ic) { if (empty($ic['company']['name'])) continue; $company = Company::firstOrCreate( ['igdb_id' => $ic['company']['id']], ['name' => $ic['company']['name'], 'slug' => \Str::slug($ic['company']['name'])] ); $role = $ic['developer'] ? 'developer' : ($ic['publisher'] ? 'publisher' : 'other'); $companyPivot[$company->id] = ['role' => $role]; } if (!empty($companyPivot)) { $game->companies()->sync($companyPivot); } } } /** * Build a full cover image URL from an IGDB image_id. */ public static function coverUrl(string $imageId, string $size = 'cover_big'): string { return "https://images.igdb.com/igdb/image/upload/t_{$size}/{$imageId}.jpg"; } /** * Build a screenshot URL from an IGDB image_id. */ public static function screenshotUrl(string $imageId, string $size = 'screenshot_med'): string { return "https://images.igdb.com/igdb/image/upload/t_{$size}/{$imageId}.jpg"; } }