<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PurchaseProduct extends Model
{
    use SoftDeletes;
    protected $fillable = ['purchase_id','product_id','product_unit_id','quotation_id','requisition_id','requisition_product_id','quotation_product_id','supplier_id','price','qty'];

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

    public function product_unit(){
        return $this->belongsTo(ProductUnit::class,'product_unit_id');
    }

    public function purchase(){
        return $this->belongsTo(Purchase::class, 'purchase_id', 'id');
    }

    public function supplier(){
        return $this->belongsTo(Supplier::class, 'supplier_id', 'id');
    }

    public function quotation_product(){
        return $this->belongsTo(QuotationProduct::class, 'quotation_id', 'id');
    }

    public function requisition_product(){
        return $this->belongsTo(NewRequisitionProduct::class, 'requisition_product_id', 'id');
    }

    public function calculate_requisition_qty($product){
       return $product->purchase->requisition->requisition_products->where('product_id',$product->product_id)->first()->qty;
    }
    public function calculate_receivable_qty($product){

        $data_array = array();
        foreach ($product->purchase->goods_in as $data){
            array_push($data_array, $data->id);
        }

        $mr_qty = GoodsinProduct::query()->whereIn('goodsin_id',$data_array)->where('product_id',$product->product_id)->sum('qty');
        return $product->qty - $mr_qty ;
    }




}
