<?php

namespace App\Models;

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

class ObatMasuk extends Model
{
    protected $fillable = [
        'nama_obat',
        'kategori_id',
        'satuan_id',
        'obat_id',
        'sumber_dana',
        'user_id',
        'kode_batch',
        'barcode',
        'stok',
        'harga_beli',
        'harga_jual',
        'tanggal_penerimaan',
        'tanggal_kadaluarsa',
        'no_faktur',
        'no_sbbk',
        'catatan',
    ];

    protected $casts = [
        'tanggal_penerimaan' => 'date',
        'tanggal_kadaluarsa' => 'date',
        'harga_beli' => 'decimal:2',
        'harga_jual' => 'decimal:2',
    ];

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

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

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

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

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

    public function getSisaHariAttribute(): int
    {
        return (int) Carbon::now()->diffInDays($this->tanggal_kadaluarsa, false);
    }

    public function getStatusKadaluarsaAttribute(): string
    {
        $sisaHari = $this->sisa_hari;
        if ($sisaHari <= 30) {
            return 'kritis';
        } elseif ($sisaHari <= 60) {
            return 'waspada';
        } else {
            return 'aman';
        }
    }

    public function getStatusStokAttribute(): string
    {
        return $this->stok > 0 ? 'tersedia' : 'habis';
    }
}
