Files
boursecu_server/app/Http/Controllers/Customer/ChatController.php
T
2026-07-30 15:46:11 +03:30

69 lines
1.9 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());
if (!empty($user->chat_room_id)) {
return response()->json([
'message' => 'چت از قبل ساخته شده',
'user' => $user,
]);
}
$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 = 'user_'.$user->id;
$url = 'https://'.$host.'/api/rooms/create';
try {
$response = Http::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);
}
}
}