<?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 Illuminate\Support\Str;

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

    protected $table = 'formulariums';

    protected $fillable = [
        'code',
        'name',
        'description',
        'manufacturer',
        'category_name',
        'kategori_obat',
        'uom',
        'general_indication',
        'composition',
        'atc_code',
        'class',
        'bpom_registration',
        'classifications',
        'cat_for',
        'formularium_template_id'
    ];

    public function setCodeAttribute($value)
    {
        $this->attributes['code'] = !empty($value) ? $value : Str::upper(Str::random('6'));
    }

    public function items()
    {
        return $this->belongsToMany(Drug::class, 'formularium_items', 'formularium_id', 'item_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('id', $search)
                    ;
        });
    }
}
