<?php

namespace App\Models;

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

class ServiceUser extends BaseModel
{
    use HasFactory;

    public function roles()
    {
        return $this->hasManyThrough(ServiceRole::class, ServiceRoleUser::class, 's_user_id', 'id', 'id', 'role_id')->orderBy('id', 'asc');
    }

    public function service_roles(){
        return $this->belongsToMany(ServiceRole::class,'service_role_users','s_user_id','role_id')->withTimestamps();
    }

    public function serviceRoleOrders()
    {
        return $this->hasMany(ServiceRoleOrder::class, 'user_id', 'user_id');
    }

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

    public function workWechat()
    {
        return $this->hasOne(Wechat::class, 'user_id', 'user_id')->where('type', 'work');
    }

    public function partner(){
        return $this->hasOne(Partner::class,'user_id','user_id');
    }

    public function coaches(){
        return $this->hasOneThrough(Coach::class,Partner::class,'user_id','partner_id','user_id','id');
    }

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

    public function scopeHasCompanyPartner($query)
    {
        return $query->whereHas('roles', function($query){
            $query->where('service_roles.id', 5);
        });
    }
}
