<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Jobs\CreateRoomConservation;
use App\Jobs\SendNotificationMessage;
use App\Models\Contract;
use App\Models\Conversation;
use App\Models\Hostel;
use App\Models\Message;
use App\Models\Room;
use App\User;
use Carbon\Carbon;
use Hashids\Hashids;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Pusher\Pusher;
use App\Models\RenterRoom;

class MessageController extends BaseController
{
    protected $pusher;

    //


    public function __construct()
    {
        parent::__construct();
       $this->pusher = \PusherService::getClient();

    }

    /**
     * @api {get} /contacts Lấy danh bạ
     * @apiName contacts
     * @apiGroup Message
     * @apiDescription Api Lấy danh bạ
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} name
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getContacts(Request $request)
    {
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $name = $request->input('name');

        $retValRenter = [];
        $retValStaff = [];
        $contactsStaffs = [];
        $hostels = [];

        if ($this->user->type == User::OWNER) {

            $hostels = Hostel::where('owner_id', $this->user->id)->pluck('id')->toArray();

            $contactsStaffs = User::where('staff_owner_id', $this->user->id);

            if (!empty($name)) {
                $contactsStaffs = $contactsStaffs->where(function ($q) use ($name) {
                    $q->orWhere('name', 'LIKE', '%' . $name . '%');
                    $q->orWhere('first_name', 'LIKE', '%' . $name . '%');
                    $q->orWhere('last_name', 'LIKE', '%' . $name . '%');
                });
            }

            $contactsStaffs = $contactsStaffs->get();
        } else if ($this->user->type == User::STAFF) {

            $ownerId = $this->user->staff_owner_id;

            $hostels = \DB::table('staff_hostels')
                ->where('user_id', $this->user->id)
                ->pluck('hostel_id')
                ->toArray();

            $contactsStaffs = User::where(function ($q) use ($ownerId) {
                $q->where('staff_owner_id', $ownerId);
                $q->where('id', '<>', $this->user->id);
            })
                ->orWhere('id', $ownerId);

            if (!empty($name)) {
                $contactsStaffs = $contactsStaffs->where(function ($q) use ($name) {
                    $q->orWhere('name', 'LIKE', '%' . $name . '%');
                    $q->orWhere('first_name', 'LIKE', '%' . $name . '%');
                    $q->orWhere('last_name', 'LIKE', '%' . $name . '%');
                });
            }

            $contactsStaffs = $contactsStaffs->get();

        } else if ($this->user->type == User::RENTER) {
            $currentRent = RenterRoom::where('user_id', $this->user->id)->has('hostel')->first();

            if ($currentRent) {
                $hostel = $currentRent->hostel;
                if ($hostel) {
                    $ownerId = $hostel->owner_id;
                    $owner = User::find($ownerId);
                    if ($owner) {
                        $hostels = Hostel::where('id', $hostel->id)->pluck('id')->toArray();
                    } else {
                        $hostels = [];
                    }

                    $staffHostel = \DB::table('staff_hostels')
                        ->where('hostel_id', $hostel->id)
                        ->pluck('user_id')->toArray();

                    $contactsStaffs = User::whereIn('id', $staffHostel)
                        ->orWhere('id', $ownerId);

                    if (!empty($name)) {
                        $contactsStaffs = $contactsStaffs->where(function ($q) use ($name) {
                            $q->orWhere('name', 'LIKE', '%' . $name . '%');
                            $q->orWhere('first_name', 'LIKE', '%' . $name . '%');
                            $q->orWhere('last_name', 'LIKE', '%' . $name . '%');
                        });
                    }

                    $contactsStaffs = $contactsStaffs->get();
                }
            }
        }
        $contactsRenters = User::select(\DB::raw('users.*, renter_rooms.room_id, renter_rooms.hostel_id'))
            ->join('renter_rooms', 'users.id', '=', 'renter_rooms.user_id')
            ->join('rooms', 'rooms.id', '=', 'renter_rooms.room_id')
            ->whereIn('renter_rooms.hostel_id', $hostels)
            ->where('users.id', '<>', $this->user->id)
            ->whereNull('renter_rooms.deleted_at')
            ->groupBy('users.id')
            ->orderBy('rooms.name')
            ->limit($limit)
            ->offset($offset);

        if (!empty($name)) {
            $contactsRenters = $contactsRenters->where(function ($q) use ($name) {
                $q->orWhere('users.name', 'LIKE', '%' . $name . '%');
                $q->orWhere('users.first_name', 'LIKE', '%' . $name . '%');
                $q->orWhere('users.last_name', 'LIKE', '%' . $name . '%');
                $q->orWhere('rooms.name', 'LIKE', '%'.$name.'%');
            });
        }

        $contactsRenters = $contactsRenters->get();


        foreach ($contactsStaffs as $contactsStaff) {

            $retValStaff[] = [
                'id' => $contactsStaff->id,
                'name' => empty($contactsStaff->name) ? $contactsStaff->first_name . ' ' . $contactsStaff->last_name : $contactsStaff->name,
                'image' => $contactsStaff->image,
                'type' => $contactsStaff->type,
                'phone' => $contactsStaff->phone,
                'hostel' => null,
                'room' => null,
            ];
        }

        foreach ($contactsRenters as $contactsRenter) {

            $roomId = $contactsRenter->room_id;

            $room = null;
            $hostel = null;

            $roomItem = Room::find($roomId);

            if ($roomItem) {
                $room = [
                    'name' => $roomItem->name,
                    'id' => $roomItem->id,
                ];

                if ($roomItem->hostel) {
                    $hostel = [
                        'name' => $roomItem->hostel->name,
                        'id' => $roomItem->hostel->id,
                    ];
                }
            }

            $retValRenter[] = [
                'id' => $contactsRenter->id,
                'name' => empty($contactsRenter->name) ? $contactsRenter->first_name . ' ' . $contactsRenter->last_name : $contactsRenter->name,
                'image' => $contactsRenter->image,
                'phone' => $contactsRenter->phone,
                'room' => $room,
                'hostel' => $hostel,
                'type' => $contactsRenter->type,

            ];
        }

        return response([
            'status' => 1,
            'data' => [
                'employee' => $retValStaff,
                'renter' => $retValRenter
            ]
        ]);
    }


    /**
     * @api {post} /create Tạo cuộc hội thoại
     * @apiName create
     * @apiGroup Chat
     * @apiDescription Api tạo cuộc hội thoại
     * @apiParam {String} user_ids dạng user_ids[] = 1
     * @apiParam {String} name
     * @apiParam {String} image
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function createConversation(Request $request)
    {
        $userIds = $request->input('user_ids');
        $name = $request->input('name');
        $image = $request->file('image');

        $userIds = array_unique($userIds);

        if (count($userIds) < 2) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (empty($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!is_array($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        sort($userIds);
        $members = implode(',', $userIds);
        $check = Conversation::where('members', $members)->whereNull('room_id')->whereNull('hostel_id')->first();
        if ($check) {
            $conversationId = $check->id;
            $conversation = Conversation::find($conversationId);

            if (!$conversation) {
                $conversation = $this->createConversationModel($image, $name, $userIds);
            }

        } else {

            $conversation = $this->createConversationModel($image, $name, $userIds);
        }

        if ($conversation == false) {
            return response([
                'status' => 0,
                'message' => 'Bạn không có quyền lập group chat'
            ]);
        }

        $participants = [];
        foreach ($userIds as $userId) {
            $user = User::find($userId);
            $participants[] = [
                'id' => $user->id,
                'name' => empty($user->name) ? $user->first_name . ' ' . $user->last_name : $user->name,
                'image' => $user->image,
                'phone' => $user->phone
            ];
        }

        $conversationName = $conversation->name;
        $conversationImage = $conversation->image;

        if (count($userIds) == 2) {
            foreach ($userIds as $userId) {
                if ($userId != $this->user->id) {
                    $user = User::find($userId);
                    if ($user) {
                        $conversationName = $user->name_text;
                        $conversationImage = $user->image;
                    }
                }
            }
        }

        if (str_contains($conversationImage, '/files/')) {
            $conversationImage = '/files/' . str_replace('/files/', '', $conversationImage);
        } else {
            $conversationImage = '/files/' . $conversationImage;
        }

        $retVal = [
            'info' => [
                'id' => $conversation->id,
                'name' => $conversationName,
                'image' => $conversationImage,
            ],
            'participants' => $participants
        ];

        return response([
            'status' => 1,
            'data' => $retVal
        ]);

    }


    /**
     * @api {post} /send-message Gửi tin nhắn
     * @apiName send-message
     * @apiGroup Chat
     * @apiDescription Api gửi tin nhắn
     * @apiParam {String} conversation_id
     * @apiParam {String} content
     * @apiParam {String} image
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function sendMessage(Request $request)
    {
        $content = $request->input('content');
        $conversationId = $request->input('conversation_id');
        $image = $request->file('image');
        $uiid = $request->input('ui_id');
        $userId = $this->user->id;

        $type = Message::TYPE_TEXT;

        if (!empty($image) && $image->isValid()) {
            $content = '/files/' . Functions::uploadImage($image);
            $type = Message::TYPE_IMAGE;
        }


        $message = Message::create([
            'content' => $content,
            'conversation_id' => $conversationId,
            'type' => $type,
            'from' => $this->user->id
        ]);

        $conversation = Conversation::find($conversationId);


        if ($conversation) {

            if ($conversation->allow_chat == 2) {
                $checkIfAdmin = \DB::table('user_conversations')->where('user_id', $userId)->where('conversation_id', $conversationId)
                    ->where('is_admin', 1)->count();
                if ($checkIfAdmin == 0) {
                    return response([
                        'status' => 0,
                        'message' => 'Bạn không có quyền nhắn tin tại cuộc hội thoại này'
                    ]);
                }
            }

            $conversation->last_message = $content;
            $conversation->last_message_id = $message->id;
            $conversation->last_message_from = $this->user->id;
            $conversation->last_message_time = Carbon::now()->toDateTimeString();
            $conversation->save();
        }

        $userIds = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->pluck('user_id')
            ->toArray();

        $userIds = array_unique($userIds);

        $message->uuid = $uiid;

        $message->user_from = [
            'id' => $this->user->id,
            'name' => $this->user->name_text,
            'phone' => $this->user->phone,
            'image' => $this->user->image
        ];

        $messageArr = $message->toArray();
        $content = $message->content;

        $channelName = 'presence-read-conversation-' . $conversationId;
        $usersChannel = $this->pusher->get('/channels/' . $channelName . '/users');
        $userOnlineArr = [];
        if (isset($usersChannel['result'])) {
            if (isset($usersChannel['result']['users'])) {
                foreach ($usersChannel['result']['users'] as $item) {
                    $userIdOnline = $item['id'];
                    $userOnlineArr[] = $userIdOnline;
                }
            }
        }

        $conversationLastMessage = $conversation->last_message;
        $info = Functions::getNameImageConversation($conversation->id, $conversation->image, $conversation->name, $conversation->hostel_id,
            $this->user->id);
        $conversationName = $info['name'];
        $conversationImage = $info['image'];

        foreach ($userIds as $userId) {

            $q = \DB::table('user_conversations')
                ->where('conversation_id', $conversationId)
                ->where('user_id', $userId);

            if (in_array($userId, $userOnlineArr)) {
                $q->update([
                    'is_read_last_message' => 1
                ]);
            } else {
                $q->update([
                    'is_read_last_message' => 0
                ]);
            }

            if ($message->type == Message::TYPE_IMAGE || $message->type == Message::TYPE_SYSTEM) {
                if ($userId == $this->user->id) {
                    if ($message->type == Message::TYPE_IMAGE) {
                        $content = 'Bạn đã gửi một ảnh';
                    } else {
                        $content = 'Bạn ' . $content;
                    }
                } else {
                    $fromUser = $message->fromUser;
                    if ($fromUser) {
                        if ($message->type == Message::TYPE_IMAGE) {
                            $content = $fromUser->name_text . ' đã gửi một ảnh';
                        } else {
                            $content = $fromUser->name_text . ' '. $content;
                        }
                    }
                }

            }
            $messageArr['conversation_last_message'] = $conversationLastMessage;
            $messageArr['conversation_name'] = $conversationName;
            $messageArr['conversation_image'] = $conversationImage;
            $this->pusher->trigger('chat-' . $userId, 'new-message', $messageArr);
            dispatch(new SendNotificationMessage($userId, $messageArr));
        }

        return response([
            'status' => 1,
            'data' => $message
        ]);
    }

    public function authPresence(Request $request)
    {
        return $this->pusher->presence_auth($request->input('channel_name'),
            $request->input('socket_id'), $this->user->id, [
                'id' => $this->user->id,
                'name' => $this->user->name_text
            ]);
    }

    /**
     * @api {post} /count-unread-conversation Đếm số hội thoại chưa đọc
     * @apiName count-unread-conversation
     * @apiGroup Chat
     * @apiDescription Api Đếm số hội thoại chưa đọc
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function countUnReadConversation()
    {
        $userId = $this->user->id;
        $cnt = \DB::table('user_conversations')
            ->join('conversations', 'user_conversations.conversation_id', '=', 'conversations.id')
            ->where('user_conversations.user_id', $userId)
            ->whereNotNull('conversations.last_message_id')
            ->where('user_conversations.is_read_last_message', 0)
            ->whereNull('conversations.deleted_at');

        if ($this->user->type == User::RENTER) {
            $cnt = $cnt->where('conversations.is_visible', true);

            $owner = $this->user->owner_info;



            if (!empty($owner)) {
                if (!$owner->allow_renter_view_hostel_group) {

                    $cnt = $cnt->where(function ($q) {
                        $q->orwhere(function($q2) {
                            $q2->orWhereNull('conversations.room_id');
                            $q2->orWhereNotNull('conversations.room_id');
                        });
                        $q->where(function($q2) {
                            $q2->whereNull('conversations.hostel_id');

                        });

                        $q->orwhere(function($q2) {
                            $q2->WhereNotNull('conversations.room_id');
                            $q2->WhereNotNull('conversations.hostel_id');
                        });

                    });
                }

                if (!$owner->allow_renter_view_room_group) {

                    $cnt = $cnt->where(function ($q) {
                        $q->orwhere(function($q2) {
                            $q2->orWhereNull('conversations.hostel_id');
                            $q2->orWhereNotNull('conversations.hostel_id');
                        });
                        $q->where(function($q2) {
                            $q2->whereNull('conversations.room_id');
                        });

                        $q->orwhere(function($q2) {
                            $q2->WhereNull('conversations.room_id');
                            $q2->WhereNull('conversations.hostel_id');
                        });
                    });
                }
            }
        }


        $cnt = $cnt->count();
         //  dd($cnt);

        return response([
            'status' => 1,
            'data' => $cnt
        ]);
    }

    /**
     * @api {post} /add-user-conversation Thêm người vào cuộc hội thoại
     * @apiName add-user-conversation
     * @apiGroup Chat
     * @apiDescription Api Thêm người vào cuộc hội thoại
     * @apiParam {integer} conversation_id
     * @apiParam {String} user_ids dạng user_ids[]
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function addUserToConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $userIds = $request->input('user_ids');

        $conversation = Conversation::find($conversationId);

        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (empty($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!is_array($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $cnt = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->count();

        if ($cnt <= 2) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $userIds = array_unique($userIds);

        try {
            \DB::beginTransaction();
            $nameArr = [];
            foreach ($userIds as $userId) {
                $check = \DB::table('user_conversations')
                    ->where('user_id', $userId)
                    ->where('conversation_id', $conversationId)
                    ->count();
                if ($check == 0) {
                    $user = User::find($userId);
                    if ($user) {
                        $nameArr[] = $user->name_text;
                    }


                    \DB::table('user_conversations')
                        ->insert([
                            'user_id' => $userId,
                            'conversation_id' => $conversationId
                        ]);
                }
            }

            $userConverIds = \DB::table('user_conversations')
                ->where('conversation_id', $conversationId)
                ->pluck('user_id')
                ->toArray();

            sort($userConverIds);
            $conversation->members = implode(',', $userConverIds);
            $conversation->save();


            $message = Message::create([
                'content' => ' đã thêm ' . implode(',', $nameArr) . ' vào cuộc hội thoại',
                'conversation_id' => $conversation->id,
                'type' => Message::TYPE_SYSTEM,
                'from' => $this->user->id
            ]);

            \DB::commit();

            foreach ($userConverIds as $userConverId) {

                $messageArr = $message->toArray();
                if ($userConverId == $this->user->id) {
                    $messageArr['content'] = 'Bạn ' . $messageArr['content'];
                } else {
                    $messageArr['content'] = $this->user->name_text .' '. $messageArr['content'];
                }
                $this->pusher->trigger('chat-' . $userConverId, 'new-message', $messageArr);

            }
        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 1,
                'message' => 'Có lỗi xảy ra, vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);

    }

    /**
     * @api {post} /remove-user-conversation Xóa người khỏi cuộc hội thoại
     * @apiName remove-user-conversation
     * @apiGroup Chat
     * @apiDescription Api Xóa người khỏi cuộc hội thoại
     * @apiParam {integer} conversation_id
     * @apiParam {String} user_ids dạng user_ids[]
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function removeUserToConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $userIds = $request->input('user_ids');

        $conversation = Conversation::find($conversationId);

        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (empty($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!is_array($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $cnt = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->count();

        if ($cnt <= 2) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $userIds = array_unique($userIds);
        $nameArr = [];
        try {
            \DB::beginTransaction();
            foreach ($userIds as $userId) {
                $check = \DB::table('user_conversations')
                    ->where('user_id', $userId)
                    ->where('conversation_id', $conversationId)
                    ->count();

                if ($check > 0) {

                    $user = User::find($userId);
                    if ($user) {
                        $nameArr[] = $user->name_text;
                    }

                    \DB::table('user_conversations')
                        ->where('user_id', $userId)
                        ->where('conversation_id', $conversationId)
                        ->delete();
                }
            }

            $userConverIds = \DB::table('user_conversations')
                ->where('conversation_id', $conversationId)
                ->pluck('user_id')
                ->toArray();

            sort($userConverIds);
            $conversation->members = implode(',', $userConverIds);
            $conversation->save();

            $message = Message::create([
                'content' => ' đã xóa ' . implode(',', $nameArr) . ' khỏi cuộc hội thoại',
                'conversation_id' => $conversation->id,
                'type' => Message::TYPE_SYSTEM,
                'from' => $this->user->id
            ]);

            $conversationLastMessage = implode(',', $nameArr) . ' được xóa khỏi cuộc hội thoại';
            $info = Functions::getNameImageConversation($conversation->id, $conversation->image, $conversation->name,
                $conversation->hostel_id, $this->user->id);
            $conversationName = $info['name'];
            $conversationImage = $info['image'];

            foreach ($userConverIds as $userConverId) {

                $messageArr = $message->toArray();
                if ($userConverId == $this->user->id) {
                    $messageArr['content'] = 'Bạn ' . $messageArr['content'];
                } else {
                    $messageArr['content'] = $this->user->name_text .' '. $messageArr['content'];
                }

                $messageArr['conversation_last_message'] = $conversationLastMessage;
                $messageArr['conversation_name'] = $conversationName;
                $messageArr['conversation_image'] = $conversationImage;

                $this->pusher->trigger('chat-' . $userConverId, 'new-message', $messageArr);

            }

            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);

    }

    /**
     * @api {post} /update-conversation Cập nhật cuộc hội thoại
     * @apiName update-conversation
     * @apiGroup Chat
     * @apiDescription Api Cập nhật cuộc hội thoại
     * @apiParam {integer} conversation_id
     * @apiParam {String} name
     * @apiParam {String} image
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function updateConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $name = $request->input('name');
        $image = $request->file('image');

        $conversation = Conversation::find($conversationId);

        $content = null;
        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!empty($name)) {
            $content = ' đã đổi tên nhóm thành ' . $name;
            $conversation->name = $name;
        }

        if (!empty($image) && $image->isValid()) {
            $image = Functions::uploadImage($image);
            $conversation->image = $image;
            $content = ' đã cập nhật ảnh đại diện nhóm';
        }

        $message = Message::create([
            'content' => $content,
            'conversation_id' => $conversation->id,
            'type' => Message::TYPE_SYSTEM,
            'from' => $this->user->id
        ]);


        $conversation->save();

        $userIds = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->pluck('user_id')
            ->toArray();

        $conversationLastMessage = 'Thông tin nhóm đã được thay đổi';
        $info = Functions::getNameImageConversation($conversation->id, $conversation->image, $conversation->name,
            $conversation->hostel_id, $this->user->id);
        $conversationName = $info['name'];
        $conversationImage = $info['image'];


        foreach ($userIds as $userId) {

            $messageArr = $message->toArray();
            if ($userId == $this->user->id) {
                $messageArr['content'] = 'Bạn ' . $messageArr['content'];
            } else {
                $messageArr['content'] = $this->user->name_text . ' ' . $messageArr['content'];
            }
            $messageArr['conversation_last_message'] = $conversationLastMessage;
            $messageArr['conversation_name'] = $conversationName;
            $messageArr['conversation_image'] = $conversationImage;
            $this->pusher->trigger('chat-' . $userId, 'new-message', $messageArr);

        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);

    }

    /**
     * @api {post} /leave-conversation Rời cuộc hội thoại
     * @apiName leave-conversation
     * @apiGroup Chat
     * @apiDescription Api rời cuộc hội thoại
     * @apiParam {integer} conversation_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function leaveConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $userId = $this->user->id;

        $conversation = Conversation::find($conversationId);

        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        try {
            \DB::beginTransaction();

            $check = \DB::table('user_conversations')
                ->where('user_id', $userId)
                ->where('conversation_id', $conversationId)
                ->count();

            $cnt = \DB::table('user_conversations')
                ->where('conversation_id', $conversationId)
                ->count();

            if ($cnt <= 2) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu không hợp lệ'
                ]);
            }

            if ($check > 0) {

                \DB::table('user_conversations')
                    ->where('user_id', $userId)
                    ->where('conversation_id', $conversationId)
                    ->delete();
            }


            $userConverIds = \DB::table('user_conversations')
                ->where('conversation_id', $conversationId)
                ->pluck('user_id')
                ->toArray();

            sort($userConverIds);
            $conversation->members = implode(',', $userConverIds);
            $conversation->save();

            $message = Message::create([
                'content' => ' đã rời cuộc hội thoại',
                'conversation_id' => $conversation->id,
                'type' => Message::TYPE_SYSTEM,
                'from' => $this->user->id
            ]);

            $conversationLastMessage = $this->user->name_text . ' đã rời cuộc hội thoại';
            $info = Functions::getNameImageConversation($conversation->id, $conversation->image, $conversation->name,
                $conversation->hostel_id, $this->user->id);
            $conversationName = $info['name'];
            $conversationImage = $info['image'];

            foreach ($userConverIds as $userConverId) {

                $messageArr = $message->toArray();
                if ($userConverId == $this->user->id) {
                    $messageArr['content'] = 'Bạn ' . $messageArr['content'];
                } else {
                    $messageArr['content'] = $this->user->name_text . ' ' . $messageArr['content'];
                }

                $messageArr['conversation_last_message'] = $conversationLastMessage;
                $messageArr['conversation_name'] = $conversationName;
                $messageArr['conversation_image'] = $conversationImage;

                $this->pusher->trigger('chat-' . $userId, 'new-message', $messageArr);

            }

            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }


    /**
     * @api {post} /get-message Lấy tin nhắn
     * @apiName get-message
     * @apiGroup Chat
     * @apiDescription Api Lấy tin nhắn
     * @apiParam {integer} conversation_id
     * @apiParam {String} limit
     * @apiParam {String} last_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getMessage(Request $request)
    {
        $limit = $request->input('limit', 10);
        $lastId = $request->input('last_id');
        $conversationId = $request->input('conversation_id');

        $conversation = Conversation::find($conversationId);

        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $conversation->last_message_is_read = true;
        $conversation->save();

        $messages = Message::where('conversation_id', $conversationId)
            ->limit($limit)
            ->orderBy('id', 'desc');

        if (!empty($lastId)) {
            $messages = $messages->where('id', '<', $lastId);
        }

        $messages = $messages->get();


        foreach ($messages as $message) {

            $from = $message->from;
            $userFrom = User::withTrashed()->find($from);

            if ($userFrom) {

                $message->user_from = [
                    'id' => $userFrom->id,
                    'name' => $userFrom->name_text,
                    'image' => $userFrom->image,
                    'phone' => $userFrom->phone,
                ];

                if ($message->type == Message::TYPE_SYSTEM) {

                    if ($userFrom) {
                        if ($userFrom->id == $this->user->id) {
                            $message->content = 'Bạn ' . $message->content;
                        } else {
                            $message->content = $userFrom->name_text . ' ' . $message->content;
                        }
                    }
                }
            }
        }


        \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->where('user_id', $this->user->id)
            ->update([
                'is_read_last_message' => true
            ]);


        return response([
            'status' => 1,
            'data' => $messages
        ]);

    }

    /**
     * @api {post} /update-conversation-setting Cập nhật thông số cuộc hội thoại
     * @apiName update-conversation-setting
     * @apiGroup Chat
     * @apiDescription Api  Cập nhật thông số cuộc hội thoại
     *
     * @apiParam {String} is_visible Có được hiển thị hay ko (chỉ khóa với renter)
     * @apiParam {String} allow_chat Có cho chat hay ko (khóa với cả admin) 1 là tất cả mn, 2 là chỉ admin
     * @apiParam {String} conversation_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function updateSettingConversation(Request $request)
    {
        $isVisible = $request->input('is_visible');
        $allowChat = $request->input('allow_chat');
        $conversationId = $request->input('conversation_id');
        $userId = $this->user->id;

        $conversation = Conversation::find($conversationId);
        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $check = \DB::table('user_conversations')
            ->where('user_id', $userId)
            ->where('conversation_id', $conversationId)
            ->first();

        if (!$check) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $isAdmin = $check->is_admin;

        if ($isAdmin == 0) {
            return response([
                'status' => 0,
                'message' => 'Bạn không có quyền cập nhật'
            ]);
        }

        if (!is_null($isVisible)) {
            $conversation->is_visible = $isVisible;
        }

        if (!empty($allowChat)) {
            $conversation->allow_chat = $allowChat;
        }

        $conversation->save();

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {get} /get-conversations Lấy danh sách hội thoại
     * @apiName get-conversations
     * @apiGroup Chat
     * @apiDescription Api Lấy danh sách hội thoại
     *
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} name
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getConversations(Request $request)
    {
        $limit = $request->input('limit', 100);
        $offset = $request->input('offset', 0);
        $name = $request->input('name');

        $items = Conversation::select(\DB::raw('conversations.*'))
            ->join('user_conversations', 'user_conversations.conversation_id', '=', 'conversations.id')
            ->where('user_conversations.user_id', $this->user->id)
            ->orderBy('last_message_time', 'desc')
            ->whereNotNull('conversations.last_message_id')
            ->whereNull('conversations.deleted_at')
            ->limit($limit)
            ->offset($offset);

        if ($this->user->type == User::RENTER) {

            $owner = $this->user->owner_info;



            if (!empty($owner)) {
                if (!$owner->allow_renter_view_hostel_group) {

                    $items = $items->where(function ($q) {
                        $q->orwhere(function($q2) {
                            $q2->orWhereNull('conversations.room_id');
                            $q2->orWhereNotNull('conversations.room_id');
                        });
                        $q->where(function($q2) {
                            $q2->whereNull('conversations.hostel_id');

                        });

                        $q->orwhere(function($q2) {
                            $q2->WhereNotNull('conversations.room_id');
                            $q2->WhereNotNull('conversations.hostel_id');
                        });

                    });
                }

                if (!$owner->allow_renter_view_room_group) {

                    $items = $items->where(function ($q) {
                        $q->orwhere(function($q2) {
                            $q2->orWhereNull('conversations.hostel_id');
                            $q2->orWhereNotNull('conversations.hostel_id');
                        });
                        $q->where(function($q2) {
                            $q2->whereNull('conversations.room_id');
                        });

                        $q->orwhere(function($q2) {
                            $q2->WhereNull('conversations.room_id');
                            $q2->WhereNull('conversations.hostel_id');
                        });
                    });
                }
            }

            $items = $items->where('is_visible', true);
        }

        if (!empty($name)) {
            $items = $items->where(function ($q) use ($name) {
                $q->orWhere('name', 'LIKE', '%' . $name . '%');
                $q->orWhere('member_names', 'LIKE', '%' . $name . '%');
            });
        }

        //dd($items->toSql());
        $items = $items->get();

        $retVal = [];
        foreach ($items as $item) {
            $participants = [];
            $lastMessageArr = null;

            $userIds = \DB::table('user_conversations')
                ->where('conversation_id', $item->id)
                ->pluck('user_id')->toArray();


            foreach ($userIds as $userId) {
                $user = User::find($userId);
                if ($user) {
                    $participants[] = [
                        'id' => $user->id,
                        'name' => empty($user->name) ? $user->first_name . ' ' . $user->last_name : $user->name,
                        'image' => $user->image,
                        'phone' => $user->phone
                    ];
                }
            }

            $conversationName = $item->name;
            $conversationImage = $item->image;

            if (count($userIds) == 2) {
                if (empty($conversationName)) {
                    foreach ($userIds as $userId) {
                        if ($userId != $this->user->id) {
                            $user = User::find($userId);
                            if ($user) {
                                $conversationName = $user->name_text;
                                $conversationImage = $user->image;
                            }
                        }
                    }
                }
            }

            if (str_contains($conversationImage, '/files/')) {
                $conversationImage = '/files/' . str_replace('/files/', '', $conversationImage);
            } else {
                if (!str_contains($conversationImage, '/frontend3/')) {
                    $conversationImage = '/files/' . $conversationImage;
                }
            }


            $lastMessage = $item->lastMessageItem;

            if ($lastMessage) {
                $content = $lastMessage->content;
                if ($lastMessage->type == Message::TYPE_IMAGE || $lastMessage->type == Message::TYPE_SYSTEM) {
                    if ($lastMessage->from == $this->user->id) {
                        if ($lastMessage->type == Message::TYPE_IMAGE) {
                            $content = 'Bạn đã gửi một ảnh';
                        } else {
                            $content = 'Bạn ' . $content;
                        }
                    } else {
                        $fromUser = $lastMessage->fromUser;
                        if ($fromUser) {
                            if ($lastMessage->type == Message::TYPE_IMAGE) {
                                $content = $fromUser->name_text . ' đã gửi một ảnh';
                            } else {
                                $content = $fromUser->name_text . ' '. $content;
                            }
                        }
                    }
                }

                $isRead = false;

                $checkIsRead = \DB::table('user_conversations')
                    ->where('user_id', $this->user->id)
                    ->where('conversation_id', $item->id)
                    ->first();

                if ($checkIsRead) {
                    $isRead = $checkIsRead->is_read_last_message;
                }

                $lastMessageArr = [
                    'content' => strip_tags($content),
                    'created_at' => $lastMessage->created_at->format('d/m/Y H:i:s'),
                    'is_read' => $isRead
                ];
            }

            $canDelete = true;
            if (!empty($item->hostel_id) || !empty($item->room_id)) {
                $canDelete = false;
            }

            $canReply = true;
            if (str_contains($item->members, '7204')) {
                $canReply = false;
            }

            $isGroup = false;

            if (count($userIds) > 2) {
                $isGroup = true;
            } else if (count($userIds) == 2) {
                if (!empty($item->hostel_id)) {
                    $isGroup = true;
                }
            }

            $retVal[] = [
                'info' => [
                    'id' => $item->id,
                    'name' => $conversationName,
                    'image' => $conversationImage,
                    'is_group' => $isGroup,
                    'can_reply' => $canReply,
                    'can_delete' => $canDelete,
                    'is_visible' => $item->is_visible,
                    'allow_chat' => $item->allow_chat
                ],
                'participants' => $participants,
                'last_message' => $lastMessageArr
            ];
        }

        return response([
            'status' => 1,
            'data' => $retVal
        ]);
    }

    /**
     * @api {post} /delete-message Xóa tin nhắn
     * @apiName delete-message
     * @apiGroup Chat
     * @apiDescription Api Xóa tin nhắn
     *
     * @apiParam {String} id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function deleteMessage( Request $request ) {
        $id     = $request->input( 'id' );
        $userId = $this->user->id;

        $message = Message::find( $id );
        if ( ! $message ) {
            return response( [
                'status'  => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ] );
        }

        if ( $message->from != $userId ) {
            return response( [
                'status'  => 0,
                'message' => 'Chỉ được xóa tin nhắn do mình gửi'
            ] );
        }

        $conversationId = $message->conversation_id;
        $conversation   = Conversation::find( $conversationId );
        if ( $conversation ) {
            if ( $conversation->last_message_id == $message->id ) {
                $newLastMessage = Message::where( 'conversation_id', $conversationId )
                    ->where( 'id', '<>', $message->id )
                    ->orderBy( 'id', 'desc' )
                    ->first();
                if ( $newLastMessage ) {
                    $conversation->last_message_id = $newLastMessage->id;
                    $conversation->last_message    = $newLastMessage->content;
                    $conversation->save();
                }
            }
        }

        $message->delete();

        return response( [
            'status'  => 1,
            'message' => 'Success'
        ] );

    }

    /**
     * @api {post} /set-admin Set admin conversation
     * @apiName set-admin
     * @apiGroup Chat
     * @apiDescription Api Set admin conversation
     *
     * @apiParam {String} conversation_id
     * @apiParam {String} user_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function setAdminConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $conversation = Conversation::find($conversationId);
        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $userId = $request->input('user_id');

        $cnt = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->where('user_id', $userId)
            ->count();
        if ($cnt == 0) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->where('user_id', $userId)
            ->update([
                'is_admin' => 1
            ]);

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {post} /remove-admin Xóa admin conversation
     * @apiName remove-admin
     * @apiGroup Chat
     * @apiDescription Api Xóa admin conversation
     *
     * @apiParam {String} conversation_id
     * @apiParam {String} user_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function removeAdminConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $conversation = Conversation::find($conversationId);
        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $userId = $request->input('user_id');

        $cnt = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->where('user_id', $userId)
            ->count();
        if ($cnt == 0) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $numberAdmin = \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->where('is_admin', 1)
            ->count();

        if ($numberAdmin == 1) {
            return response([
                'status' => 0,
                'message' => 'Không thể xóa admin cuối cùng'
            ]);
        }

        \DB::table('user_conversations')
            ->where('conversation_id', $conversationId)
            ->where('user_id', $userId)
            ->update([
                'is_admin' => 0
            ]);

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {get} /get-conversation Lấy chi tiết hội thoại
     * @apiName get-conversation
     * @apiGroup Chat
     * @apiDescription Api Lấy chi tiết hội thoại
     *
     * @apiParam {String} conversation_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getConversation(Request $request)
    {
        $conversationId = $request->input('conversation_id');
        $roomId = $request->input('room_id');

        if (!empty($conversationId)) {
            $item = Conversation::find($conversationId);

        } else {
            $item = Conversation::where('room_id', $roomId)->first();
            if (!$item) {
                $item = Functions::createRoomConversation($roomId, $this->user->id);
            }
        }

        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $participants = [];
        $lastMessageArr = null;

        $userIds = \DB::table('user_conversations')
            ->where('conversation_id', $item->id)
            ->pluck('user_id')->toArray();

        $userAdmins = \DB::table('user_conversations')
            ->where('conversation_id', $item->id)
            ->pluck('is_admin')->toArray();


        foreach ($userIds as $key => $userId) {
            $user = User::find($userId);
            if ($user) {

                $isAdmin = false;
                if (isset($userAdmins[$key])) {
                    if ($userAdmins[$key] == 1) {
                        $isAdmin = true;
                    }
                }
                $participants[] = [

                    'id' => $user->id,
                    'name' => empty($user->name) ? $user->first_name . ' ' . $user->last_name : $user->name,
                    'image' => $user->image,
                    'phone' => $user->phone,
                    'is_admin' => $isAdmin
                ];
            }
        }

        $conversationName = $item->name;
        $conversationImage = $item->image;

        if (count($userIds) == 2) {
            if (empty($item->hostel_id)) {
                foreach ($userIds as $userId) {
                    if ($userId != $this->user->id) {
                        $user = User::find($userId);
                        if ($user) {
                            $conversationName = $user->name_text;
                            $conversationImage = $user->image;
                        }
                    }
                }
            }
        }

        if (str_contains($conversationImage, '/files/')) {
            $conversationImage = '/files/' . str_replace('/files/', '', $conversationImage);
        } else {
            if (!str_contains($conversationImage, '/frontend3/')) {
                $conversationImage = '/files/' . $conversationImage;
            }
        }


        $lastMessage = $item->lastMessageItem;

        if ($lastMessage) {
            $content = $lastMessage->content;
            if ($lastMessage->type == Message::TYPE_IMAGE || $lastMessage->type == Message::TYPE_SYSTEM) {
                if ($lastMessage->from == $this->user->id) {
                    if ($lastMessage->type == Message::TYPE_IMAGE) {
                        $content = 'Bạn đã gửi một ảnh';
                    } else {
                        $content = 'Bạn ' . $content;
                    }
                } else {
                    $fromUser = $lastMessage->fromUser;
                    if ($fromUser) {
                        if ($lastMessage->type == Message::TYPE_IMAGE) {
                            $content = $fromUser->name_text . ' đã gửi một ảnh';
                        } else {
                            $content = $fromUser->name_text . ' '. $content;
                        }
                    }
                }
            }


            $lastMessageArr = [
                'content' => $content,
                'created_at' => $lastMessage->created_at->format('d/m/Y H:i:s'),
                'is_read' => $item->last_message_is_read
            ];
        }

        $canDelete = true;
        if (!empty($item->hostel_id) || !empty($item->room_id)) {
            $canDelete = false;
        }

        $canReply = true;
        if (str_contains($item->members, '7204')) {
            $canReply = false;
        }

        $isGroup = false;

        if (count($userIds) > 2) {
            $isGroup = true;
        } else if (count($userIds) == 2) {
            if (!empty($item->hostel_id)) {
                $isGroup = true;
            }
        }
        $retVal = [
            'info' => [
                'id' => $item->id,
                'name' => $conversationName,
                'image' => $conversationImage,
                'can_delete' => $canDelete,
                'can_reply' => $canReply,
                'is_group' => $isGroup,
                'is_visible' => $item->is_visible,
                'allow_chat' => $item->allow_chat
            ],
            'participants' => $participants,
            'last_message' => $lastMessageArr
        ];

        return response([
            'status' => 1,
            'message' => 'Thành công',
            'data' => $retVal
        ]);

    }


    public function createConversationModel($image, $name, $userIds)
    {
        if (count($userIds) > 2) {
            if ($this->user->type == User::RENTER) {
                $currentRenterRoom = RenterRoom::where('user_id', $this->user->id)
                    ->first();
                if ($currentRenterRoom) {
                    if ($currentRenterRoom->hostel) {
                        if ($currentRenterRoom->hostel->owner) {
                            if (!$currentRenterRoom->hostel->owner->allow_renter_make_group) {
                                return false;
                            }
                        }
                    }
                }
            }
        }

        $imageSaved = null;

        if (!empty($image) && $image->isValid()) {
            $imageSaved = Functions::uploadImage($image);
        }

        if (count($userIds) == 2) {
            $name = null;
            $imageSaved = null;
        }


        $channelName = Str::random() . time() . uniqid();

        sort($userIds);

        $conversation = Conversation::create([
            'name' => $name,
            'image' => $imageSaved,
            'channel' => $channelName,
            'members' => implode(',', $userIds),
            'user_id' => $this->user->id
        ]);

        $userIdSync = [];

        foreach ($userIds as $userId) {
            if ($userId == $this->user->id) {
                $userIdSync[$userId] = [
                    'is_admin' => true
                ];
            } else {
                $userIdSync[$userId] = [
                    'is_admin' => false
                ];
            }
        }

        $conversation->users()->sync($userIdSync);

        if (count($userIds) > 2) {
            $message = Message::create([
                'content' => ' đã tạo cuộc hội thoại',
                'conversation_id' => $conversation->id,
                'type' => Message::TYPE_SYSTEM,
                'from' => $this->user->id
            ]);

            foreach ($userIds as $userId) {

                $messageArr = $message->toArray();
                if ($userId == $this->user->id) {
                    $messageArr['content'] = 'Bạn ' . $messageArr['content'];
                } else {
                    $messageArr['content'] = $this->user->name_text . ' ' . $messageArr['content'];
                }
                $this->pusher->trigger('chat-' . $userId, 'new-message', $messageArr);

            }

            if ($conversation) {
                $conversation->last_message = $message->content;
                $conversation->last_message_id = $message->id;
                $conversation->last_message_from = $this->user->id;
                $conversation->last_message_time = Carbon::now()->toDateTimeString();
                $conversation->save();
            }
        }

        Functions::updateMemberName($conversation->id);

        return $conversation;
    }
}
