Files
boursecu_server/app/Http/Controllers/Customer/ChatController.php
T
2026-07-30 18:06:53 +03:30

109 lines
3.3 KiB
PHP

<?php
namespace App\Http\Controllers\Customer;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Support\Facades\Http;
class ChatController extends Controller
{
public function StartSupportChat()
{
$user = Customer::findOrFail(auth('customer')->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;
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;
}
}
}