<?php

namespace App\Models;

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

class Requisition extends Model
{
    use HasFactory;
    public function user()
    {
        return $this->belongsTo('App\Models\User', 'creator_user_id');

    }
    public function branch()
    {
        return $this->belongsTo('App\Models\Branch', 'branch_id');

    }
    public function items()
    {
        return $this->hasMany('App\Models\RequisitionItem', 'requisition_id');

    }
    public function requisitionApproves()
    {
        return $this->hasMany('App\Models\RequisitionApprove', 'requisition_id');

    }
    public function requisitionApprove()
    {
        return $this->hasOne('App\Models\RequisitionApprove', 'requisition_id');

    }
    public static function availableRequisitions()
    {
        $requisitions = \App\Models\Requisition::get();
        $available_requisitions = [];
        foreach ($requisitions as $requisition) {
            $quantity = 0;
            foreach ($requisition->requisitionApproves as $requisitionApprove) {
                $quantity += $requisitionApprove->items->sum('quantity');
            }
            if ($requisition->items->sum('quantity') > $quantity) {
                $available_requisitions[] = $requisition;
            }
        }
        return $available_requisitions;
    }
    public function availableItems()
    {
        foreach ($this->items as $key => $item) {
            $this->items[$key]->quantity -= RequisitionApproveItem::where('item_id', $item->item_id)
                ->where('requisition_id', $this->id)
                ->sum('quantity');
        }
        return $this->items;
    }

    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }
}
