<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Obat extends Model
{
    protected $fillable = ['kategori_id', 'nama', 'kode', 'satuan', 'deskripsi'];

    public function kategori(): BelongsTo
    {
        return $this->belongsTo(Kategori::class);
    }

    public function obatMasuks(): HasMany
    {
        return $this->hasMany(ObatMasuk::class);
    }

    public function obatKeluars(): HasMany
    {
        return $this->hasMany(ObatKeluar::class);
    }

    public function getTotalStokAttribute(): int
    {
        $masuk = $this->obatMasuks()->sum('stok');
        $keluar = $this->obatKeluars()->where('status', 'terkirim')->sum('jumlah');
        return $masuk - $keluar;
    }
}
