<?php

namespace App\Traits;

use App\Models\Rating;
use App\Models\Service;
use App\Notifications\ReviewAdded;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait Rateable
{
    public function workRates()
    {
        return $this->morphMany(Rating::class, 'rated');
    }

    public function getAverageRatingAttribute(){

        $rates = $this->rates()->average('rate')??$this->workRates()->average('rate');
        return number_format((float)$rates, 2, '.', '');
    }

    public function addRate(Request $request)
    {
        $data = $request->validate([
            'comment' => 'nullable|max:500',
            'rate' => 'integer|max:5|min:0',
        ]);
        if ($this instanceof Service) {
            $data['rated_id'] = $this->serviceable()->get()->first()->id;
            $data['rated_type'] = get_class($this->serviceable()->getRelated());
        } else {
            $data['rated_id'] = $this->projectable()->get()->first()->id;
            $data['rated_type'] = get_class($this->projectable()->getRelated());
        }
        $data['user_id'] = Auth::user()->id;
        if(count($this->rates()->where('user_id', Auth::user()->id)->get()) > 0) {
            $this->rates()->where('user_id', Auth::user()->id)->first()->update($data);
            $this->rates()->where('user_id', Auth::user()->id)->first()->save();
        } else {
            $rate = $this->rates()->create($data);
            $rate->rated->notify(new ReviewAdded($rate));
        }

        return $this->rates;
    }

    public function rates()
    {
        return $this->morphMany(Rating::class, 'rateable');
    }
   
    public function getRatesAttribute()
    {
        return $this->morphMany(Rating::class, 'rateable')->orderBy('id', 'desc')->take(5)->with('user')->get();
    }

}
