<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Reply extends Model implements HasMedia
{
    use InteractsWithMedia;

    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class, 'replied_by', 'id');
    }

    public function isUserReply()
    {
        return $this->user()->first()->role == 'user';
    }

    public function isRated()
    {
        return $this->rate != null;
    }

    public function scopeOrderByRate($query)
    {
        $query->leftJoin('users', 'users.id', '=', 'replies.replied_by')
            ->selectRaw('users.name, users.id as user_id, sum(replies.rate) as rate')
            ->where('users.role', '<>', 'user')
            ->groupBy('replies.replied_by')
            ->orderBy('rate', 'desc');
    }

    public function ticket()
    {
        return $this->belongsTo(Ticket::class);
    }

    public function reports()
    {
        return $this->hasMany(Report::class);
    }
}
