<?php

namespace App\Models;

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

class RawMaterialItem extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'description',
        'code',
        'unit',
        'min_level',
        'max_level',
        'category_id',
        'sub_category_id',
        'party_id',
        'chart_of_account_id',
        'sub_chart_of_account_id',
        'company_id',
        'created_by',
        'updated_by',
        'current_stock',
        'avg_unit_price',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_by = auth()->id();
        });

        static::updating(function ($model) {
            $model->updated_by = auth()->id();
        });
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function party()
    {
        return $this->belongsTo(Party::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function subCategory()
    {
        return $this->belongsTo(SubCategory::class);
    }

    public function chart_of_account()
    {
        return $this->belongsTo(ChartOfAccount::class);
    }

    public function sub_chart_of_account()
    {
        return $this->belongsTo(SubChartOfAccount::class);
    }

    public function orders()
    {
        return $this->hasMany(InvoiceItem::class);
    }

    public function recievers()
    {
        return $this->hasMany(GoodsReceivingItem::class);
    }

    public function balance()
    {
        $balanceData = Stock::currentBalanceForItem(null, $this->id);
        return $balanceData['balance'];
    }
}
