<?php

namespace App\Classes;

use App\Models\Item;
use App\Models\ItemReturnItem;
use App\Models\StockAdjustmentItem;
use App\Models\StockIn;
use App\Models\StockOut;
class AvailableStockCalculation
{
    public static function item_id($id)
    {
        $stock_in = StockIn::where(['item_id' => $id])->sum('quantity');
        $stock_out = StockOut::where(['item_id' => $id])->sum('quantity');
        $item_return = ItemReturnItem::where(['item_id' => $id])->sum('qty');
        $adjustment = StockAdjustmentItem::where(['item_id' => $id])->sum('quantity');
        $available = $stock_in - $stock_out + $item_return -$adjustment;
        if ($available > 0) {
            return $available;
        } else {
            return '0';
        }
    }

    public static function stock_alert()
    {
        $items = Item::with('stockIn','stockOut','itemReturn','itemAdjustment')->get();
        $count_stock_alert = 0;
        foreach($items as $item) {
           $temp_qyt =  $item->stockIn->sum('quantity') - $item->stockOut->sum('quantity') + $item->itemReturn->sum('qty') -  $item->itemAdjustment->sum('quantity');
            if ($temp_qyt <= 15) {
                $count_stock_alert++;
            }
        }
        return $count_stock_alert;
    }
}
