<?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 Drug extends Model
{
    use HasFactory, SoftDeletes, Blameable;

    protected $fillable = [
        'name',
        'generic_name',
        'code',
        'description',
        'brand_id',
        'mims_class',
        'indication',
        'atc_code',
        'segmentation',
        'type',
        'dosage',
        'remark',
        'selling_unit_id',
        'status',
        'active',
    ];

    public function categories()
    {
        return $this->hasMany(DrugCategories::class, 'drug_id');
    }

    // public function externalIdentifiers()
    // {
    //     return $this->hasMany(DrugExternalIdentifier::class, 'drug_id');
    // }

    public function brand()
    {
        return $this->belongsTo(Brand::class, 'brand_id');
    }

    public function identifiers()
    {
        return $this->morphMany(Identifier::class, 'identifiable');
    }

    public function manufacturers()
    {
        return $this->belongsToMany(Organization::class, 'drug_manufacturers', 'drug_id', 'organization_id');
    }

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