<?php

namespace App\Jobs;

use App\Components\Functions;
use App\Models\Conversation;
use App\Models\Hostel;
use App\Models\Message;
use App\Models\Room;
use App\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Pusher\Pusher;

class RemoveStaffConversation implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */

    protected $staffId;
    protected $hostelId;
    protected $pusher;

    public function onConnection($connection)
    {
        $this->connection = 'redis';
        return $this;
    }

    public function __construct($staffId, $hostelId)
    {
        //
        $this->staffId = $staffId;
        $this->hostelId = $hostelId;
        $this->pusher = \PusherService::getClient();
        $this->connection =  'redis';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $hostelId = $this->hostelId;
        $staffId = $this->staffId;


        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return;
        }

        dispatch(new RemoveUserConversationV2($staffId, $hostelId, null));
        $rooms = Room::query()->where('hostel_id', $hostelId)->get();
        foreach ($rooms as $room) {

            dispatch_now(new RemoveUserConversationV2($staffId, null, $room->id));
        }

        $hostelConversation = Conversation::where('hostel_id', $hostelId)
            ->whereNull('room_id')
            ->first();

        $this->removeUserConversation($hostelConversation, $staffId, $hostel->owner);

        $roomConversations = Conversation::where('hostel_id', $hostelId)
            ->whereNotNull('room_id')
            ->get();

        foreach ($roomConversations as $roomConversation) {
            $this->removeUserConversation($roomConversation, $staffId, $hostel->owner);
        }
    }

    public function removeUserConversation($conversation, $userId, $userCreate)
    {

        if ($conversation) {
            $nameArr = [];
            $conversationId = $conversation->id;

            $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);

            $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' => $userCreate->id
            ]);

            $conversation->members = implode(',', $userConverIds);
            $conversation->last_message_id = $message->id;
            $conversation->last_message_time = Carbon::now()->toDateTimeString();
            $conversation->save();

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

            foreach ($userConverIds as $userConverId) {

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

            }
        }
    }
}
