<?php

namespace App\Models;

use App\Traits\Blameable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CorporateService extends Model
{
    use HasFactory, SoftDeletes, Blameable;

    protected $fillable = [
        'corporate_id',
        'service_code',
        'status',
        'reason'
    ];

    protected $hidden = [
        'created_at',
        'updated_at',
        'deleted_at',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    public function corporate()
    {
        return $this->belongsTo(Corporate::class);
    }

    public function configs()
    {
        return $this->hasMany(CorporateServiceConfig::class, 'corporate_service_id');
    }

    public function service()
    {
        return $this->hasOne(Service::class, 'code', 'service_code');
    }

    public function specialities()
    {
        return $this->belongsToMany(Speciality::class, 'corporate_service_specialities', 'corporate_service_id', 'speciality_id', 'id', 'id')
                    ->withPivot(['active']);
    }

    public function corporateServiceSpecialities()
    {
        return $this->hasMany(CorporateServiceSpeciality::class, 'corporate_service_id');
    }

    public function scopeActive($query) {
        $query->where('status', 'active');
    }

    public function scopeFilter($query, array $filters)
    {
        if (!empty($filters['search'])) {
            $query->where('service_code', 'LIKE', '%'.$filters['search'].'%')
                ->orWhereHas('service', function($service) use ($filters) {
                    $service->where('name', 'LIKE', '%'.$filters['search'].'%');
                });
        }
    }
}
