<?php

namespace RxConnexionBundle\Service;

use Doctrine\ORM\EntityManager;
use RxConnexionBundle\Entity\HealthFacilityEntity;
use RxConnexionBundle\Entity\InventoryEntity;
use RxConnexionBundle\Entity\InventorySerialNoEntity;
use RxConnexionBundle\Entity\ItemAveCostEntity;
use RxConnexionBundle\Entity\ItemEntity;
use RxConnexionBundle\Entity\MaterialRequisitionItemEntity;
use RxConnexionBundle\Entity\PurchaseOrderBreakdownItemEntity;
use RxConnexionBundle\Entity\PurchaseOrderItemEntity;
use RxConnexionBundle\Entity\TransferInventoryItemEntity;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;

Class ItemService {

    private $em;
    private $container;

    public function __construct(EntityManager $em, ContainerInterface $container) {
        $this->em = $em;
        $this->container = $container;
    }

	public function computeAverageCostByBranch(ItemEntity $item, HealthFacilityEntity $healthFacility)
	{
		/**@var ItemAveCostEntity $aveCost*/
		/**@var MaterialRequisitionItemEntity $materialRequisitionItem*/
		/**@var PurchaseOrderItemEntity $purchaseOrderItem*/
		/**@var PurchaseOrderBreakdownItemEntity $purchaseOrderBreakdownItem*/
		/**@var InventoryEntity $inventory*/
		/**@var InventorySerialNoEntity $inventorySerialNo*/
		/**@var TransferInventoryItemEntity $transferInventoryItem*/

		$itemAveCost = null;
		foreach ($item->getItemAveCost() as $aveCost) {
			if($aveCost->getHealthFacility() === $healthFacility) {
				$itemAveCost = $aveCost;
				break;
			}
		}

		if(is_null($itemAveCost)) {
			$itemAveCost = new ItemAveCostEntity();
			$itemAveCost->setItem($item);
			$itemAveCost->setHealthFacility($healthFacility);
			$this->em->persist($itemAveCost);
			$item->addItemAveCode($itemAveCost);
		}

		$totalQty = 0;
		$totalSum = 0;
		$oneYearAgo = (new \DateTime())->modify('-1 year');

		$this->em->refresh($item);

		if($item->getIsItemised()) {

			/** TODO: REFRESH NOT WORKING ON DELETE */
			$inventory = $item->getFirstInventoryByBranchIdAndStatus($healthFacility->getId(), InventoryEntity::STATUS_STOCK_ON_HAND);

			if($inventory) {
				foreach ($inventory->getAvailableInventorySerialNos() as $inventorySerialNo) {
					$qty = 1;
					$price = $inventorySerialNo->getCost();
					$totalQty += $qty;
					$totalSum += ($qty * $price);
				}
			}
		} else {

			$healthFacilityIds = [$healthFacility->getId()];
			foreach ($item->getTransferInventoryItems() as $transferInventoryItem) {
				if($transferInventoryItem->getTransferInventory()->getBranchTo() === $healthFacility && $transferInventoryItem->getQuantityReceived() > 0) {
					$healthFacilityIds[] = $transferInventoryItem->getTransferInventory()->getBranchFrom()->getId();
				}
			}
			//die(var_dump($healthFacilityIds));
			foreach ($item->getMaterialRequisitionItems() as $materialRequisitionItem) {
				if (in_array($materialRequisitionItem->getMaterialRequisition()->getHealthFacility()->getId(), $healthFacilityIds)
					&& $oneYearAgo < $materialRequisitionItem->getMaterialRequisition()->getRequestDate()) {
					foreach ($materialRequisitionItem->getPurchaseOrderItems() as $purchaseOrderItem) {
						foreach ($purchaseOrderItem->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
							if($purchaseOrderBreakdownItem->getQuantityReceived() > 0) {
								$qty = $purchaseOrderBreakdownItem->getQuantityReceived() ? : 0;
								$price = $materialRequisitionItem->getPrice();
								$totalQty += $qty;
								$totalSum += ($qty * $price);
							}
						}
					}
				}
			}
		}
		//die(var_dump($totalQty, $totalSum, $inventory->getId()));
		$averageCost = $totalQty > 0 ? ($totalSum / $totalQty) : 0;
		$itemAveCost->setAveCost($averageCost);


		$this->em->flush();

	}


}