<?php

namespace App\Jobs;

use App\Models_v2\Conversation;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $message;
    protected $toUser;
    protected $fromUser;

    public function __construct($message, $toUser, $fromUser = null)
    {
        //
        $this->message = $message;
        $this->toUser = $toUser;
        $this->fromUser = $fromUser;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $idbot = 7204;
        if (!empty($this->fromUser)) {
            $idbot = $this->fromUser;
        }
        $message = $this->message;
        $users = [
            $idbot, $this->toUser
        ];

        $conversation = Conversation::query()
            ->where('members', json_encode($users))
            ->first();
        if (!$conversation) {
            $conversation = Conversation::create([
                'name' => '',
            ]);
        } else {
            if ($conversation->status == Conversation::ARCHIVED) {
                $conversation->status = null;
                $conversation->save();
            }
        }

        $conversation->users()->sync($users);
        sort($users);
        $conversation->members = json_encode($users);
        $conversation->save();


        dispatch(new SendMessageV2($conversation->id, $message, $idbot))->onConnection('redis');

    }
}
