<?php

namespace App\Models;

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

class StoreIssueRequisitionItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'store_issue_requisition_id',
        'product_id',
        'raw_material_item_id',
        'product_variation_id',
        'batch_id',
        'quantity',
        'unit',
        'unit_price',
        'total',
        'stock',
    ];

    public function store_issue_requisition()
    {
        return $this->belongsTo(StoreIssueRequisition::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function rawMaterialItem()
    {
        return $this->belongsTo(RawMaterialItem::class);
    }

    public function raw_material_item()
    {
        return $this->belongsTo(RawMaterialItem::class);
    }

    public function product_variation()
    {
        return $this->belongsTo(ProductVariation::class);
    }

    public function batch()
    {
        if ($this->raw_material_item_id) {
            return $this->belongsTo(GrnItemBatch::class, 'batch_id');
        } else {
            return $this->belongsTo(Batch::class);
        }
    }

    public function leftOverNotes()
    {
        return $this->hasMany(LeftOverNoteItem::class, 'sir_item_id');
    }

    public function lonQty($exceptId = 0)
    {
        // dd($exceptId);
        return $this->hasMany(LeftOverNoteItem::class, 'sir_item_id')
            ->when($exceptId > 0, function ($q) use ($exceptId) {
                $q->where('id', '!=', $exceptId);
            })
            ->sum('quantity');
    }
}
