initializeCache(); } public function handleRequest(): void { try { $cachedData = $this->cache ? $this->cache->get("latest_listen") : null; if ($cachedData) { $this->sendResponse(json_decode($cachedData, true)); return; } $data = $this->makeRequest("GET", "optimized_latest_listen?select=*"); if (!is_array($data) || empty($data[0])) { $this->sendResponse(["message" => "No recent tracks found"], 404); return; } $latestListen = $this->formatLatestListen($data[0]); if ($this->cache) $this->cache->set( "latest_listen", json_encode($latestListen), $this->cacheTTL ); $this->sendResponse($latestListen); } catch (Exception $e) { error_log("LatestListenHandler Error: " . $e->getMessage()); $this->sendErrorResponse( "Internal Server Error: " . $e->getMessage(), 500 ); } } private function formatLatestListen(array $latestListen): array { $emoji = $latestListen["artist_emoji"] ?? ($latestListen["genre_emoji"] ?? "🎧"); $trackName = htmlspecialchars( $latestListen["track_name"] ?? "Unknown Track", ENT_QUOTES, "UTF-8" ); $artistName = htmlspecialchars( $latestListen["artist_name"] ?? "Unknown Artist", ENT_QUOTES, "UTF-8" ); $url = htmlspecialchars($latestListen["url"] ?? "/", ENT_QUOTES, "UTF-8"); return [ "content" => sprintf( '%s %s by %s', $emoji, $trackName, $url, $artistName ), ]; } } $handler = new LatestListenHandler(); $handler->handleRequest();