<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PurchaseItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'purchase_id',
        'item_id',
        'item_type',
        'item_name',
        'quantity',
        'unit_price',
        'total_price',
        'unit',
    ];

    // Relasi
    public function purchase()
    {
        return $this->belongsTo(Purchase::class);
    }

    public function material()
    {
        return $this->belongsTo(Material::class, 'item_id');
    }

    public function sparepart()
    {
        return $this->belongsTo(Sparepart::class, 'item_id');
    }

    public function getItemNameAttribute()
    {
        if ($this->item_type === 'material') {
            return $this->material->name ?? '-';
        } elseif ($this->item_type === 'sparepart') {
            return $this->sparepart->name ?? '-';
        }
        return '-';
    }
}
