id()); $chatApi = self::Config('chat_api'); $chatApiKey = self::Config('chat_api_key'); if (!$chatApi || !$chatApiKey) { return response()->json([ 'message' => 'تنظیمات گفتگو تنظیم نشده است.', ], 422); } $host = preg_replace('#^https?://#', '', rtrim((string) $chatApi, '/')); $userChatId = !empty($user->chat_user_id) ? (string) $user->chat_user_id : 'user_'.$user->id; app(ChatWebhookService::class)->ensureRegistered(); if (!empty($user->chat_room_id)) { if ($this->chatRoomIsAccessible($host, (string) $chatApiKey, (string) $user->chat_room_id, $userChatId)) { if (empty($user->chat_user_id) || $user->chat_user_id !== $userChatId) { $user->chat_user_id = $userChatId; $user->save(); } return response()->json([ 'message' => 'چت از قبل ساخته شده', 'user' => $user, ]); } // روم در سرویس چت نامعتبر/بدون عضویت است — از نو می‌سازیم $user->chat_room_id = null; $user->chat_user_id = null; $user->save(); } $url = 'https://'.$host.'/api/rooms/create'; try { $response = Http::timeout(12)->post($url, [ 'api_key' => $chatApiKey, 'name' => $user->name, 'type' => 'SUPPORT', 'members' => [ 'admin', $userChatId, ], ]); if (!$response->successful()) { return response()->json([ 'message' => $response->body(), 'url' => $url, ], 422); } $data = $response->json(); $user->chat_room_id = $data['room_id'] ?? null; $user->chat_user_id = $userChatId; $user->save(); return response()->json([ 'message' => 'چت ساخته شد', 'user' => $user, ]); } catch (\Exception $exception) { return response()->json([ 'message' => $exception->getMessage(), ], 422); } } private function chatRoomIsAccessible( string $host, string $apiKey, string $roomId, string $userChatId ): bool { if ($host === '' || $apiKey === '' || $roomId === '' || $userChatId === '') { return false; } try { $response = Http::timeout(8)->acceptJson()->get('https://'.$host.'/api/messages', [ 'api_key' => $apiKey, 'room_id' => $roomId, 'user_id' => $userChatId, 'limit' => 1, 'offset' => 0, ]); return $response->successful(); } catch (\Throwable $e) { return false; } } }