<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Chat extends Model
{
    use HasFactory;
    protected $guarded = [];

    public function messages()
    {
        return $this->hasMany(Message::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class)->withTrashed();
    }

    public function worker()
    {
        return $this->morphTo()->withTrashed();
    }

    public function chatable()
    {
        return $this->morphTo()->withTrashed();
    }

    public function proposal(){
        if($this->chatable()->getModel() instanceof Project){
            return Proposal::where('project_id',$this->chatable->id)
                ->where('proposalable_id',$this->worker_id)
                ->where('proposalable_type',$this->worker_type)->get()?->first();
        }
        else return null;
    }
    public function serviceOrder(){

        if($this->chatable()->getModel() instanceof ServiceOrder){
            return ServiceOrder::where('service_id',$this->chatable->id)->get()?->first();
        }
        else return null;
    }

    public function setMessagesAsRead(){
        $this->messages()->where('sender_uid','!=',Auth::id())->update(['read_at'=>now()]);
    }
}
