<?php 

namespace App\Services;
use App\Events\PurchaseIndicator;

class AccessoryCalculation
{
	public function orderQuantity($availableQuantity, $weeklyDemand, $leadTime)
	{
		$demandQuantity = (6 * $weeklyDemand ) + ($leadTime * $weeklyDemand) - $availableQuantity;

		if(($demandQuantity) < 0) {
			return 0;
		} else {
			return $demandQuantity;
		}
	}

	public function purchaseIndicator($availableQuantity, $weeklyDemand, $leadTime)
	{
		if($this->orderQuantity($availableQuantity, $weeklyDemand, $leadTime) > 0) {
			return true;
		}

		return false;
	}

	public function updateCalculations($accessory)
	{
		$orderQuantity = $this->orderQuantity($accessory->available_quantity, $accessory->weekly_demand, $accessory->lead_time);
		$purchaseIndicator = $this->purchaseIndicator($accessory->available_quantity, $accessory->weekly_demand, $accessory->lead_time);

		if($accessory->purchase_indicator == 0 && $purchaseIndicator == 1) {
			event(new PurchaseIndicator($accessory));
		}

		$data = [
            'order_quantity' => $orderQuantity,
            'purchase_indicator' => $purchaseIndicator,
        ];

		$accessory->update($data);

		return $data;
	}
}