<?php

namespace App\Models;

use App\Traits\Blameable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Altek\Accountant\Contracts\Recordable;

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

    protected $fillable = [
        'corporate_id',
        'service_code',
        'type',
        'exclusionable_id',
        'exclusionable_type',
        'active',
        'reason'
    ];
    
    protected $hidden = [
        'created_at',
        'updated_at',
        'deleted_at',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    public function rules()
    {
        return $this->hasMany(ExclusionRules::class, 'exclusion_id');
    }

    public function exclusionable()
    {
        return $this->morphTo();
    }

    public function scopeFilter($query, Array $filters)
    {
        $query->when($filters['search'] ?? false, function ($query, $search) {
            return $query
                    ->whereHasMorph('exclusionable', [Icd::class], function ($query) use ($search) {
                        $query->where('code', 'like', "%" . $search . "%")
                            ->orWhere('name', 'like', "%" . $search . "%");
                    })
                    ;
        });
    }
}
