<?php

namespace App\Models;

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

class ItemConversion extends Model
{
    use HasFactory;

    protected $table = 'm_item_conversions';

    protected $fillable = [
        'raw_material_id',
        'uom_utuh',
        'uom_pakai',
        'conversion_factor',
        'notes',
        'is_active',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'conversion_factor' => 'decimal:2',
        'is_active' => 'boolean',
        'delete_flag' => 'boolean',
    ];

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function modificator()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    // Relationship with raw material
    public function rawMaterial()
    {
        return $this->belongsTo(RawMaterial::class, 'raw_material_id');
    }

    // Scope for active conversions
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('delete_flag', false);
    }

    // Calculate converted quantity from utuh to pakai
    public function convertUtuhToPakai($utuhQty)
    {
        return $utuhQty * $this->conversion_factor;
    }

    // Calculate converted quantity from pakai to utuh
    public function convertPakaiToUtuh($pakaiQty)
    {
        if ($this->conversion_factor <= 0) {
            return 0;
        }
        return $pakaiQty / $this->conversion_factor;
    }

    // Get conversion display text
    public function getConversionDisplayAttribute()
    {
        return "1 {$this->uom_utuh} = {$this->conversion_factor} {$this->uom_pakai}";
    }
}