<?php

namespace App\Inventory;

use Illuminate\Database\Eloquent\Model;
use App\Inventory\ProjectStock;
use App\Branch;

class Stock extends Model
{
    //

    public function outStock($object)
    {
        return \DB::transaction(function () use ($object)  {

          $curr_stock                 = new Stock;


        $curr_stock->issue_note_id                    = $object['issue_note_id'];
        $curr_stock->out_quantity                     = $object['out_quantity'];
        $curr_stock->date                             = $object['date'];
        $curr_stock->item_id                             = $object['item_id'];
        $curr_stock->branch_id                             = $object['branch_id'];

        $curr_stock->save();

        return with($curr_stock);


        });
    }
        public function inStock($object)
    {
        return \DB::transaction(function () use ($object)  {

        $curr_stock                                   = new Stock;
        $curr_stock->receiving_note_id                = $object['receiving_note_id'];
        $curr_stock->in_quantity                      = $object['in_quantity'];
        $curr_stock->date                             = $object['date'];
        $curr_stock->item_id                          = $object['item_id'];
        $curr_stock->branch_id                        = $object['branch_id'];
        
        $curr_stock->save();

        return with($curr_stock);


        });
    }

    public function getStockbyItem($id)
    {
      return Stock::where('item_id', $id)->get();
    }

    public function getQty($id,$project)
    {
      $in_stock = Stock::where('item_id', $id)->where('branch_id',$project)->where('out_quantity' , null)->sum('in_quantity');
      $out_stock = Stock::where('item_id', $id)->where('branch_id',$project)->where('in_quantity' , null)->sum('out_quantity');

      $in_stock2 = ProjectStock::where('item_id', $id)->where('to_branch_id',$project)->sum('stock_in_qty');
      $out_stock2 = ProjectStock::where('item_id', $id)->where('from_branch_id',$project)->sum('stock_out_qty');



      $in_stock = $in_stock+$in_stock2;
      $out_stock = $out_stock+$out_stock2;
      return $qty = $in_stock-$out_stock;
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class,'branch_id');
    }


}
