<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Reappraise extends BaseModel
{
    use HasFactory;

    public function content(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => json_decode($value,true),
        );
    }


    public function serviceRoleOrder()
    {
        return $this->hasOne(ServiceRoleOrder::class, 'id', 'role_order_id');
    }

    public function operateServiceUser()
    {
        return $this->hasOne(ServiceUser::class, 'user_id', 'operate_user_id');
    }

    public function scopeKeyword($query)
    {
        $keyword = request()->keyword;
        if ($keyword) {
            return $query->where(function ($sql) use($keyword) {
                $sql->whereHas('operateServiceUser', function($sql) use($keyword) {
                    $sql->where('name', 'like', "%$keyword%")
                    ->orWhere('mobile', 'like', "%$keyword%");
                })->orWhereHas('serviceRoleOrder.serviceUser', function($sql) use($keyword) {
                    $sql->where('name', 'like', "%$keyword%")
                    ->orWhere('mobile', 'like', "%$keyword%");
                });
            });
        }
        return $keyword;
    }
}
