<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class GrnItemBatch extends Model
{
    protected $fillable = [
        'grn_id',
        'grn_item_id',
        'batch',
        'mfg_date',
        'exp_date',
        'unit_price',
        'unit',
        'total_amount',
        'receiving_quantity',
        'supplier_bill_no',
        'sir_issued_qty',
    ];

    public function grn()
    {
        return $this->belongsTo(GoodsReceiving::class, 'grn_id');
    }

    public function grnItem()
    {
        return $this->belongsTo(GoodsReceivingItem::class, 'grn_item_id');
    }

    public function sirQty($exceptId = null)
    {
        return $this->hasMany(StoreIssueRequisitionItem::class, 'batch_id')
            ->whereHas('store_issue_requisition', function ($q) {
                $q->where('is_production', '1');
            })
            ->when($exceptId > 0, function($q) use($exceptId) {
                $q->where('id', '!=', $exceptId);
            })
            ->sum('quantity');
    }
}
