<?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 Icd extends Model
{
    use HasFactory, SoftDeletes, Blameable;
    
    protected $table = 'icd';

    protected $fillable = [
        'rev',
        'version',
        'code',
        'name',
        'description',
        'parent_code',
        'active',
        'icd_template_id'
    ];

    public $appends = [
        'type',
        // 'active'
    ];

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

    public function getTypeAttribute()
    {
        return 'ICD-'.$this->rev;
    }

    // public function getActiveAttribute()
    // {
    //     return empty($this->deleted_at);
    // }

    public function subCategories()
    {
        return $this->hasMany(Icd::class, 'parent_code', 'code');
    }

    public function category()
    {
        return $this->belongsTo(Icd::class, 'parent_code', 'code');
    }

    public function exclusions()
    {
        return $this->morphMany(Exclusion::class, 'exclusionable');
    }

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

    public function claim_history_care()
    {
        return $this->hasMany(CliamHistoryCare::class, 'main_diagnosis_id', 'id');
    }
    
    public function diagnosis_secondary_claim_history_care()
    {
        return $this->hasMany(DiagnosisSecondaryCliamHistoryCare::class, 'icd_id', 'id');
    }

}
