<?php

namespace App\Http\Livewire;

use App\Events\MessageEvent;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Message extends Component
{
    public $message;
    public $messageContent;
    public $singleMessageShow = false;
    public $allMessages = [];

    protected $listeners = [
        "echo-private:AllowMessage,AllowMessageEvent" => 'allowMessageAllUser',
    ];


    public function render()
    {
        $this->allMessages = \App\Models\Message::with('user')
                                                ->select('message', 'user_id','created_at')
                                                ->where('user_id',auth()->id())
                                                ->orwhere('is_show',1)
                                                ->orderBy('id','asc')
                                                ->get();

        return view('livewire.message');
    }

    public function resetForm()
    {
        $this->message='';
    }

    public function SendMessage()
    {
        $validatedData = $this->validate([
            'message' => 'required|min:3',
        ]);

        $data               =   new \App\Models\Message();
        $data->message      =   $this->message;
        $data->user_id      =   auth()->id();
        $data->receiver_id  =   6;
        $data->save();

        $this->resetForm();
        $this->emit('scroll');
        broadcast( new MessageEvent($data));
    }

//    public function getUser()
//    {
//        $this->allMessages = Message::where('user_id',auth()->id())
//                                ->orderBy('id','desc')
//                                ->get();
//    }

    public function allowMessageAllUser()
    {
        $this->allMessages = \App\Models\Message::with('user')
            ->select('message', 'user_id','created_at')
            ->where('user_id',auth()->id())
            ->orwhere('is_show',1)
            ->orderBy('id','asc')
            ->get();
    }

}
