<?php

namespace RxConnexionBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ObjectManager;
use RxConnexionBundle\Entity\InventorySerialNoEntity;
use RxConnexionBundle\Entity\TransferInventoryDeliveryItemTransferInventoryItemInvSerialNoEntity;
use RxConnexionBundle\Entity\TransferInventoryDeliveryTransInvItemInvSerialNoEntity;
use RxConnexionBundle\Entity\TransferInventoryItemDeliveryInventorySerialNoEntity;
use RxConnexionBundle\Entity\TransferInventoryItemInventorySerialNoEntity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Entity\InventoryEntity;
use RxConnexionBundle\Entity\ItemEntity;
//use RxConnexionBundle\Entity\ProjectManagementEntity;
//use RxConnexionBundle\Entity\ProjectManagementTransferInventoryEntity;
//use RxConnexionBundle\Entity\StatusApprovalUserEntity;
//use RxConnexionBundle\Entity\TransferInventoryItemDefaultEntity;
//use RxConnexionBundle\Entity\UserNotifEntity;

use RxConnexionBundle\Entity\TransferInventoryEntity;
//use RxConnexionBundle\Entity\TransferInventoryMatReqEntity;
use RxConnexionBundle\Form\TransferInventoryForm;

use RxConnexionBundle\Entity\TransferInventoryDeliveryEntity;
use RxConnexionBundle\Entity\TransferInventoryDeliveryItemEntity;
use RxConnexionBundle\Form\TransferInventoryDeliveryForm;

use RxConnexionBundle\Entity\TransferInventoryItemEntity;
use RxConnexionBundle\Form\TransferInventoryItemForm;

use RxConnexionBundle\Entity\TransferInventoryItemDeliveryEntity;
use RxConnexionBundle\Form\TransferInventoryItemDeliveryForm;

use RxConnexionBundle\Entity\TransferInventoryStatusEntity;

/**
 * @Route("/admin/transfer_inventory")
 */
class TransferInventoryController extends Controller
{
    /**
     * @Route("", name="transfer_inventory")
     */
    public function indexAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory'))) return $authService->redirectToHome();

        return $this->render('@RxConnexion/TransferInventory/index.html.twig', array(
            'title' => 'Transfer Inventory',
            'page_title' => 'Transfer Inventory',
            'javascripts' => array('rxconnexion/admin/js/transferInventory/transferInventory.js?v=1.0.4'),
            'status' => $request->query->get('status')
        ));
    }

    /**
     * @Route("/ajax_list", name="transfer_inventory_ajax_list")
     */
    public function ajax_listAction(Request $request) {

        $get = $request->query->all();

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:TransferInventoryEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}",
     *      defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "transfer_inventory_form"
     * )
     */
    public function formAction($action, $id, Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory New', 'Admin Transfer Inventory Update'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $get = $request->query->all();

        $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($id));
        if (!$transferInventory) {
            $transferInventory = new TransferInventoryEntity();
        }


//        $projectManagement_id = isset($get['pm']) ? $get['pm'] : 0;
//        $projectManagement_type = isset($get['ty']) ? $get['ty'] : '';
        $referencedTransferInventory_id = isset($get['rti']) ? $get['rti'] : 0;
//        $projectManagement = $em->getRepository('RxConnexionBundle:ProjectManagementEntity')->find(base64_decode($projectManagement_id));
//        $branch_projectEvents = $em->getRepository('RxConnexionBundle:BranchEntity')->findOneBy(array('description' => 'Project/Events'));
//        $branch_rccCenter = $em->getRepository('RxConnexionBundle:BranchEntity')->findOneBy(array('description' => 'RCC Center'));
        $referencedTransferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($referencedTransferInventory_id));

        $formOptions = array(
            'action'                => $action,
//            'user_branchIds'        => $this->get('session')->get('userData')['branchIds'],
//            'user_departmentIds'    => $this->get('session')->get('userData')['departmentIds'],
        );
        $form = $this->createForm(TransferInventoryForm::class, $transferInventory, $formOptions);

        if($request->getMethod() === 'POST') {

            $transferInventory_form = $request->get($form->getName());
            $other_form = $request->get('otherForm');
            $result = $this->processForm($transferInventory_form, $other_form, $transferInventory, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('transfer_inventory'), 302);
                } else if($result['redirect'] === 'item') {
                    return $this->redirect($this->generateUrl('transfer_inventory_item', array(
                        'transferInventory_id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('transfer_inventory_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('transfer_inventory_form'), 302);
                }
            } else {
                $form->submit($transferInventory_form, false);
            }
        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' Transfer Inventory ';

        return $this->render('@RxConnexion/TransferInventory/form.html.twig', array(
            'title'                 => $title,
            'page_title'            => $title,
            'form'                  => $form->createView(),
            'stylesheets'           => array('rxconnexion/admin/css/transferInventory/transferInventory_form.css?v=1.0.0'),
            'javascripts'           => array('rxconnexion/admin/js/transferInventory/transferInventory_form.js?v=1.0.2'),
            'action'                => $action,
            'id'                    => $id,
            'transferInventory'     => $transferInventory,
//            'projectManagement'     => $projectManagement,
//            'projectManagement_type'=> $projectManagement_type,
//            'branch_projectEvents'  => $branch_projectEvents,
            'referencedTransferInventory' => $referencedTransferInventory,
//            'branch_rccCenter'      => $branch_rccCenter,
        ));
    }

    private function processForm($transferInventory_form, $other_form,TransferInventoryEntity $transferInventory, $form, Request $request) {

        $em = $this->getDoctrine()->getManager();

        $errors = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->validate($transferInventory_form);

        if(!count($errors)) {

            switch($transferInventory_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $branchFrom = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($transferInventory_form['branchFrom']);
                        $branchTo = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($transferInventory_form['branchFrom']);
                        $locationFrom = $em->getRepository('RxConnexionBundle:LocationEntity')->find($transferInventory_form['locationFrom']);
                        $locationTo = $em->getRepository('RxConnexionBundle:LocationEntity')->find($transferInventory_form['locationTo']);
                        $transferInventory->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $_COOKIE['userId']));
                        $em->persist($transferInventory);
                        $em->flush();

                        $transferInventory->setTransferNo('SRS-' . $branchFrom->getId() . '-' . $branchTo->getId() . '-' . sprintf('%006d', $transferInventory->getId()));

                        $em->persist($transferInventory);
                        $em->flush();

//                        $newAT = new AuditTrailEntity(
//                            'Device',
//                            $em->getClassMetadata(DeviceEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $device;
//                        $newAT->parseDetails();
//                        $em->persist($newAT);
//                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Saved.');

                        $result['redirect'] = 'item';
                        $result['id'] = $transferInventory->getId();


                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'u': // update

//                    $newAT = new AuditTrailEntity(
//                        'Device',
//                        $em->getClassMetadata(DeviceEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_UPDATE
//                    );
//                    $newAT->entity = $device;
//                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

//                        $newAT->parseDetails();
//                        $em->persist($newAT);

                        $branchFrom = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($transferInventory_form['branchFrom']);
                        $branchTo = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($transferInventory_form['branchFrom']);
                        $locationFrom = $em->getRepository('RxConnexionBundle:LocationEntity')->find($transferInventory_form['locationFrom']);
                        $locationTo = $em->getRepository('RxConnexionBundle:LocationEntity')->find($transferInventory_form['locationTo']);
                        $transferInventory->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $_COOKIE['userId']));
                        $em->persist($transferInventory);
                        $em->flush();

                        $transferInventory->setTransferNo('SRS-' . $branchFrom->getId() . '-' . $branchTo->getId() . '-' . sprintf('%006d', $transferInventory->getId()));

                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');

	                    $result['redirect'] = 'item';
	                    $result['id'] = $transferInventory->getId();

                    } else {

                        $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
                        $result['redirect'] = 'form with error';
                    }

                    break;

                case 'd': // delete

                    $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find($transferInventory_form['id']);
                    $em->remove($transferInventory);

                    $em->flush();

                    $this->get('session')->getFlashBag()->set('success_messages', 'Record successfully deleted.');

                    $result['redirect'] = 'index';

                    break;
            }

            $result['success'] = true;

        } else {

            foreach($errors as $error) {
                $this->get('session')->getFlashBag()->add('error_messages', $error);
            }

            $result['success'] = false;
        }

        return $result;
    }

    private function processOtherForm(ObjectManager $em, TransferInventoryEntity $transferInventory, $other_form) {

        $mrIds = array();

        if(isset($other_form['mrs'])) {
            foreach($other_form['mrs'] as $mr_form) {
                $mrIds[] = $mr_form['id'];
                if(!$transferInventory->getHasMatReqById($mr_form['id'])) {
                    $newTransferInventoryMatReq = new TransferInventoryMatReqEntity();
                    $newTransferInventoryMatReq->setTransferInventory($transferInventory);
                    $newTransferInventoryMatReq->setMaterialRequisition($em->getReference('RxConnexionBundle:MaterialRequisitionEntity', $mr_form['id']));
                    $em->persist($newTransferInventoryMatReq);
                }
            }
        }

        $transferInventoryMatReqs = $transferInventory->getTransferInventoryMatReqs();
        if($transferInventoryMatReqs->count()) {
            foreach($transferInventoryMatReqs as $transferInventoryMatReq) {
                if(!in_array($transferInventoryMatReq->getMaterialRequisition()->getId(), $mrIds)) {
                    $em->remove($transferInventoryMatReq);
                }
            }
        }

        $em->flush();

        return true;
    }

    /**
     * @Route(
     *      "/status_approval",
     *      name = "transfer_inventory_status_approval"
     * )
     */
    public function status_approvalAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();

        if($request->getMethod() === 'POST') {

            $em = $this->getDoctrine()->getManager();
            $transferInventory_id = $request->get('transferInventory_id');
            $action = $request->get('action');
            $notes = $request->get('notes');
            $user = $authService->getUser();

            $transferInventory = new TransferInventoryEntity();
            $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));

            /*$newAT = new AuditTrailEntity();
            $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
            $newAT->entity = $transferInventory;
            $newAT->setRefTable('transfer_inventory');
            $newAT->parseInformation('Status Approval', $action);
            $em->persist($newAT);
            $em->flush();*/

            if($action === 'approve') {

                foreach($transferInventory->getTransferInventoryStatuses() as $transferInventoryStatus) {
                    if($transferInventoryStatus->getBatchNo() === $transferInventory->getApprovalBatchNo() && $transferInventoryStatus->getApprovalDescription() === 'Pending'){
                        $transferInventoryStatus->setApprovalDescription('Approved');
                        $transferInventoryStatus->setNote($notes);
                        $transferInventoryStatus->setUser($user);
                        break;
                    }
                }

                $em->flush();

                $statusApprovalPendingApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Transfer Inventory Pending Approval'));
                $statusApprovalPendingFinalApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Transfer Inventory Pending Final Approval'));

                $approvalCount = 0;

                foreach($transferInventory->getTransferInventoryStatuses() as $transferInventoryStatus) {
                    if($transferInventoryStatus->getBatchNo() === $transferInventory->getApprovalBatchNo() && $transferInventoryStatus->getApprovalDescription() === 'Approved'){
                        $approvalCount++;
                    }
                }

                if($transferInventory->getStatus() === "Pending Approval") {
                    if($statusApprovalPendingApproval->getLevel() === $approvalCount && $statusApprovalPendingFinalApproval && $statusApprovalPendingFinalApproval->getLevel() > 0) {

                        $transferInventory->setApprovalBatchNo($transferInventory->getApprovalBatchNo() + 1);
                        $transferInventory->setStatus('Pending Final Approval');

                        for($i = $statusApprovalPendingApproval->getLevel(); $i > 0; $i--) {

                            $newTransferInventoryStatus = new TransferInventoryStatusEntity();
                            $newTransferInventoryStatus->setTransferInventory($transferInventory);
                            $newTransferInventoryStatus->setStatus('Pending Final Approval');
                            $newTransferInventoryStatus->setBatchNo($transferInventory->getApprovalBatchNo());
                            $em->persist($newTransferInventoryStatus);
                        }

                        $em->flush();

                        $canApproveByUser = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->countForApprovalByUser($this->get('session')->get('userData'), $transferInventory->getStatus(), $transferInventory->getId());
                        if($canApproveByUser){
                            $transferInventory->setStatus('Approved');

                            $newUserNotif = new UserNotifEntity();
                            $newUserNotif->setUser($transferInventory->getUser());
                            $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                            $newUserNotif->setRef('transfer_inventory');
                            $newUserNotif->setRefId($transferInventory->getId());
                            $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been approved.');
                            $em->persist($newUserNotif);

                            if($transferInventory->getBranchFrom()->getId() !== $transferInventory->getBranchTo()->getId()){
                                $em->flush();
                            } else {
                                $transferInventoryDelivery = new TransferInventoryDeliveryEntity();
                                $transferInventoryDelivery->setDrDate(date('m/d/Y'));
                                $transferInventoryDelivery->setDrNo(0);
                                $transferInventoryDelivery->setTransferInventory($transferInventory);
                                $transferInventoryDelivery->setNote('System');
                                $em->persist($transferInventoryDelivery);

                                $em->flush();
                                $other_form = array();

                                $branchId = $transferInventory->getBranchFrom()->getId();
                                foreach($transferInventory->getTransferInventoryItems() as $tii){
                                    //$tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemId($tii->getId()) : null;
                                    //$tidiQty = $tidi ? $tidi->getQuantity() : 0;
                                    $qtyForDelivery = $tii->getQuantity() - $tii->getQuantityDelivered();
                                    $item = $tii->getItem();
                                    $itemDesc = $item->getDescriptionandunitandsize();
                                    //$inv = $item->getFirstInventoryByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                                    //$invQty = $inv ? $inv->getQuantity() + $tidiQty : 0;
                                    $invs = $item->getInventoriesByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                                    foreach($invs as $inv){
                                        $tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemIdAndInvId($tii->getId(), $inv->getId()) : null;

                                        $other_form['items'][] = array(
                                            'id' => $tidi ? $tidi->getId() : null ,
                                            'tii' => $tii->getId(),
                                            'inventoryId' => $inv ? $inv->getId() : null,
                                            'qtyOnStock' => $inv ? $inv->getQuantity() : 0,
                                            'qtyForDelivery' => $qtyForDelivery,
                                            'itemDesc' => $itemDesc,
                                            'qty' => $tidi ? $tidi->getQuantity() : 0 ,
                                            'isValid' => 1,
                                        );
                                    }

                                }

                                $this->delivery_form_actionContinue($em, $transferInventoryDelivery, $other_form);
                                $em->refresh($transferInventoryDelivery);
                                $inventoryService = $this->get('rx_connexion.inventoryService');
                                $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                                    'action' => 'New',
                                    'transferInventoryDelivery' => $transferInventoryDelivery
                                ));
                            }
                        } else {
                            $newUserNotif = new UserNotifEntity();
                            $newUserNotif->setUser($transferInventory->getUser());
                            $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                            $newUserNotif->setRef('transfer_inventory');
                            $newUserNotif->setRefId($transferInventory->getId());
                            $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been sent for final approval.');
                            $em->persist($newUserNotif);
                        }


                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record successfully sent for approval.');

                    } else if($statusApprovalPendingApproval->getLevel() === $approvalCount) {

                        $transferInventory->setStatus('Approved');

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($transferInventory->getUser());
                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                        $newUserNotif->setRef('transfer_inventory');
                        $newUserNotif->setRefId($transferInventory->getId());
                        $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been approved.');
                        $em->persist($newUserNotif);

                        if($transferInventory->getBranchFrom()->getId() !== $transferInventory->getBranchTo()->getId()){
                            $em->flush();
                        } else {
                            $transferInventoryDelivery = new TransferInventoryDeliveryEntity();
                            $transferInventoryDelivery->setDrDate(date('m/d/Y'));
                            $transferInventoryDelivery->setDrNo(0);
                            $transferInventoryDelivery->setTransferInventory($transferInventory);
                            $transferInventoryDelivery->setNote('System');
                            $em->persist($transferInventoryDelivery);

                            $em->flush();
                            $other_form = array();

                            $branchId = $transferInventory->getBranchFrom()->getId();
                            foreach($transferInventory->getTransferInventoryItems() as $tii){
                                //$tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemId($tii->getId()) : null;
                                //$tidiQty = $tidi ? $tidi->getQuantity() : 0;
                                $qtyForDelivery = $tii->getQuantity() - $tii->getQuantityDelivered();
                                $item = $tii->getItem();
                                $itemDesc = $item->getDescriptionandunitandsize();
                                //$inv = $item->getFirstInventoryByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                                //$invQty = $inv ? $inv->getQuantity() + $tidiQty : 0;
                                $invs = $item->getInventoriesByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                                foreach($invs as $inv){
                                    $tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemIdAndInvId($tii->getId(), $inv->getId()) : null;

                                    $other_form['items'][] = array(
                                        'id' => $tidi ? $tidi->getId() : null,
                                        'tii' => $tii->getId(),
                                        'inventoryId' => $inv ? $inv->getId() : null,
                                        'qtyOnStock' => $inv ? $inv->getQuantity() : 0,
                                        'qtyForDelivery' => $qtyForDelivery,
                                        'itemDesc' => $itemDesc,
                                        'qty' => $tidi ? $tidi->getQuantity() : 0 ,
                                        'isValid' => 1,
                                    );
                                }

                            }

                            $this->delivery_form_actionContinue($em, $transferInventoryDelivery, $other_form);
                            $em->refresh($transferInventoryDelivery);
                            $inventoryService = $this->get('rxconnexion.inventoryService');
                            $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                                'action' => 'New',
                                'transferInventoryDelivery' => $transferInventoryDelivery
                            ));
                        }

                    }

                } else if ($statusApprovalPendingFinalApproval->getLevel() === $approvalCount){
                    $transferInventory->setStatus('Approved');

                    $newUserNotif = new UserNotifEntity();
                    $newUserNotif->setUser($transferInventory->getUser());
                    $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                    $newUserNotif->setRef('transfer_inventory');
                    $newUserNotif->setRefId($transferInventory->getId());
                    $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been approved.');
                    $em->persist($newUserNotif);

                    if($transferInventory->getBranchFrom()->getId() !== $transferInventory->getBranchTo()->getId()) {
                        $em->flush();
                    } else {
                        $transferInventoryDelivery = new TransferInventoryDeliveryEntity();
                        $transferInventoryDelivery->setDrDate(date('m/d/Y'));
                        $transferInventoryDelivery->setDrNo(0);
                        $transferInventoryDelivery->setTransferInventory($transferInventory);
                        $transferInventoryDelivery->setNote('System');
                        $em->persist($transferInventoryDelivery);

                        //$em->flush();
                        $other_form = array();

                        $branchId = $transferInventory->getBranchFrom()->getId();
                        foreach($transferInventory->getTransferInventoryItems() as $tii){
                            //$tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemId($tii->getId()) : null;
                            //$tidiQty = $tidi ? $tidi->getQuantity() : 0;
                            $qtyForDelivery = $tii->getQuantity() - $tii->getQuantityDelivered();
                            $item = $tii->getItem();
                            $itemDesc = $item->getDescriptionandunitandsize();
                            //$inv = $item->getFirstInventoryByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                            //$invQty = $inv ? $inv->getQuantity() + $tidiQty : 0;
                            $invs = $item->getInventoriesByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                            foreach($invs as $inv){
                                $tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemIdAndInvId($tii->getId(), $inv->getId()) : null;
                                $other_form['items'][] = array(
                                    'id' => $tidi ? $tidi->getId() : null,
                                    'tii' => $tii->getId(),
                                    'inventoryId' => $inv ? $inv->getId() : null,
                                    'qtyOnStock' => $inv ? $inv->getQuantity() : 0,
                                    'qtyForDelivery' => $qtyForDelivery,
                                    'itemDesc' => $itemDesc,
                                    'qty' => $tidi ? $tidi->getQuantity() : 0 ,
                                    'isValid' => 1,
                                );
                            }

                        }

                        $this->delivery_form_actionContinue($em, $transferInventoryDelivery, $other_form);
                        $em->refresh($transferInventoryDelivery);
                        $inventoryService = $this->get('rx_connexion.inventoryService');
                        $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                            'action' => 'New',
                            'transferInventoryDelivery' => $transferInventoryDelivery
                        ));
                    }
                }



                $this->get('session')->getFlashBag()->set('success_messages', 'Request Successfully Approved.');

            } else {

                $transferInventory->setStatus('Rejected');

                foreach($transferInventory->getTransferInventoryStatuses() as $transferInventoryStatus) {
                    if($transferInventoryStatus->getBatchNo() === $transferInventory->getApprovalBatchNo() && $transferInventoryStatus->getApprovalDescription() === 'Pending'){
                        $transferInventoryStatus->setApprovalDescription('Rejected');
                        $transferInventoryStatus->setNote($notes);
                        $transferInventoryStatus->setUser($user);
                        break;
                    }
                }

                // $em->flush();

                foreach($transferInventory->getTransferInventoryStatuses() as $transferInventoryStatus) {
                    if($transferInventoryStatus->getBatchNo() === $transferInventory->getApprovalBatchNo() && $transferInventoryStatus->getApprovalDescription() === 'Pending'){
                        $transferInventoryStatus->setApprovalDescription('Cancelled');
                    }
                }

                $newUserNotif = new UserNotifEntity();
                $newUserNotif->setUser($transferInventory->getUser());
                $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                $newUserNotif->setRef('transfer_inventory');
                $newUserNotif->setRefId($transferInventory->getId());
                $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been rejected.');
                $em->persist($newUserNotif);

                $em->flush();

                $this->get('session')->getFlashBag()->set('success_messages', 'Request Successfully Rejected.');
            }

            return $this->redirect($this->generateUrl('transfer_inventory_item', array(
                'transferInventory_id' => $transferInventory_id
            )), 302);

        } else {

            $this->get('session')->getFlashBag()->set('error_messages', 'You have made an invalid request.');
            return $this->redirect($this->generateUrl('admin'), 302);
        }
    }

    /**
     * @Route("/send", name="transfer_inventory_send")
     */
    public function sendAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) $result['errorMessages'][] = 'You have not logged in. Please reload the page.';
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item Send'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {
            $forms = $request->get('form');
            $transferInventoryItems = array();
            if($forms){
                array_shift($forms);
                foreach ($forms as $invForm){
                    $invDetails = explode('-', $invForm['name']);
                    $transferInventoryItems[$invDetails[0]][$invDetails[1]] = $invForm['value'];
                }
            }
            $em = $this->getDoctrine()->getManager();
            $transferInventory_id = $request->get('transferInventory_id');
            $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));

//            $newAT = new AuditTrailEntity();
//            $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//            $newAT->entity = $transferInventory;
//            $newAT->setRefTable('transfer_inventory');
//            $newAT->parseInformation('Send');
//            $em->persist($newAT);

//            $statusApprovalPendingApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Transfer Inventory Pending Approval'));
//            $statusApprovalPendingFinalApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Transfer Inventory Pending Final Approval'));

            /* IF THIS IS PERTINENT TO PROJECT/EVENT, DO NOT UNDERGO APPROVAL */
//            if(($transferInventory->getLocationTo() && $transferInventory->getLocationTo()->getProjectManagement()) || ($transferInventory->getLocationFrom() && $transferInventory->getLocationFrom()->getProjectManagement())) {
            //if(($transferInventory->getLocationTo() && $transferInventory->getLocationTo()) || ($transferInventory->getLocationFrom() && $transferInventory->getLocationFrom())) {
                $transferInventory->setStatus('Approved');

//                $userIdsToNotify = array();
//                /**@var StatusApprovalUserEntity $approvalUser*/
//                foreach($statusApprovalPendingApproval->getStatusApprovalUsers() as $approvalUser) {
//                    if($approvalUser->getDepartment()->getId() == $transferInventory->getDepartment()->getId()){
//                        if(!in_array($approvalUser->getUser()->getId(), $userIdsToNotify)){
//                            $userIdsToNotify[] = $approvalUser->getUser()->getId();
//                        }
//                    }
//                }
//
//                foreach($statusApprovalPendingFinalApproval->getStatusApprovalUsers() as $approvalUser) {
//                    if($approvalUser->getDepartment()->getId() == $transferInventory->getDepartment()->getId()){
//                        if(!in_array($approvalUser->getUser()->getId(), $userIdsToNotify)){
//                            $userIdsToNotify[] = $approvalUser->getUser()->getId();
//                        }
//                    }
//                }



//                $notifDetail = 'New ingress for project request has been submitted - SRS No. ' . $transferInventory->getTransferNo();
//                if($transferInventory->getRelatedProject()){
//                    $notifDetail = 'New ingress for project ' .ucfirst($transferInventory->getRelatedProject()->getDescription()). ' has been submitted - SRS No. ' . $transferInventory->getTransferNo();
//                }
//
//                foreach($userIdsToNotify as $item){
//                    $newUserNotif = new UserNotifEntity();
//                    $newUserNotif->setUser($em->getReference('RxConnexionBundle:UserEntity', $item));
//                    $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//                    $newUserNotif->setRef('transfer_inventory');
//                    $newUserNotif->setRefId($transferInventory->getId());
//                    $newUserNotif->setDetail($notifDetail);
//                    $em->persist($newUserNotif);
//                }


                if($transferInventory->getBranchFrom()->getId() !== $transferInventory->getBranchTo()->getId()){

                    if(count($transferInventoryItems)){
                        foreach ($transferInventoryItems as $key => $transferInventoryItem){
                            $tii = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find($key);
                            $tii->setQuantity($transferInventoryItem['qty']);
                            $tii->setQuantityRequested($transferInventoryItem['qtyReq']);
                            $tii->setNote($transferInventoryItem['note']);
                            $tii->setIsConsumable(isset($transferInventoryItem['consumable']) ? 1 : 0);
                        }
                    }
                    $em->flush();
                } else {
                    $transferInventoryDelivery = new TransferInventoryDeliveryEntity();
                    $transferInventoryDelivery->setDrDate(date('m/d/Y'));
                    $transferInventoryDelivery->setDrNo(0);
                    $transferInventoryDelivery->setTransferInventory($transferInventory);
                    $transferInventoryDelivery->setNote('System');
                    $em->persist($transferInventoryDelivery);

                    $em->flush();
                    $other_form = array();
                    $branchId = $transferInventory->getBranchFrom()->getId();
                    foreach($transferInventory->getTransferInventoryItems() as $tii){
                        //$tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemId($tii->getId()) : null;
                        //$tidiQty = $tidi ? $tidi->getQuantity() : 0;
                        if(count($transferInventoryItems)){
                            foreach ($transferInventoryItems as $key => $transferInventoryItem){
                                if($tii->getId() == $key){
                                    $tii->setQuantity($transferInventoryItem['qty']);
                                    $tii->setQuantityRequested($transferInventoryItem['qtyReq']);
                                    $tii->setNote($transferInventoryItem['note']);
                                    $tii->setIsConsumable(isset($transferInventoryItem['consumable']) ? 1 : 0);
                                    $em->flush();
                                }
                            }
                        }
                        $qtyForDelivery = $tii->getQuantity() - $tii->getQuantityDelivered();
                        $item = $tii->getItem();
//                        $itemDesc = $item->getDescriptionandunitandsize();
                        $itemDesc = $item->getDescription();
                        //$inv = $item->getFirstInventoryByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                        //$invQty = $inv ? $inv->getQuantity() + $tidiQty : 0;
                        $invs = $item->getInventoriesByBranchIdAndStatus($branchId, InventoryEntity::STATUS_STOCK_ON_HAND);
                        foreach($invs as $inv){
                            $tidi = $transferInventoryDelivery ? $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemIdAndInvId($tii->getId(), $inv->getId()) : null;

                            $other_form['items'][] = array(
                                'id' => $tidi ? $tidi->getId() : null,
                                'tii' => $tii->getId(),
                                'inventoryId' => $inv ? $inv->getId() : null,
                                'qtyOnStock' => $inv ? $inv->getQuantity() : 0,
                                'qtyForDelivery' => $qtyForDelivery,
                                'itemDesc' => $itemDesc,
                                'qty' => $tidi ? $tidi->getQuantity() : 0 ,
                                'isValid' => 1,
                            );
                        }

                    }

                    $this->delivery_form_actionContinue($em, $transferInventoryDelivery, $other_form);
                    $em->refresh($transferInventoryDelivery);
                    $inventoryService = $this->get('rx_connexion.inventoryService');
                    $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                        'action' => 'New',
                        'transferInventoryDelivery' => $transferInventoryDelivery
                    ));

//                    $this->get('session')->getFlashBag()->set('success_messages', 'Request Successfully Approved.');
                    $this->get('session')->getFlashBag()->set('success_messages', 'Record successfully sent for receiving.');
                }

            //}

            //else {
//                if ($statusApprovalPendingApproval && $statusApprovalPendingApproval->getLevel() > 0) {
//
//                    $transferInventory->setApprovalBatchNo($transferInventory->getApprovalBatchNo() + 1);
//                    $transferInventory->setStatus('Pending Approval');
//
//                    for ($i = $statusApprovalPendingApproval->getLevel(); $i > 0; $i--) {
//
//                        $newTransferInventoryStatus = new TransferInventoryStatusEntity();
//                        $newTransferInventoryStatus->setTransferInventory($transferInventory);
//                        $newTransferInventoryStatus->setStatus('Pending Approval');
//                        $newTransferInventoryStatus->setBatchNo($transferInventory->getApprovalBatchNo());
//                        $em->persist($newTransferInventoryStatus);
//                    }
//
//                    $newUserNotif = new UserNotifEntity();
//                    $newUserNotif->setUser($transferInventory->getUser());
//                    $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//                    $newUserNotif->setRef('transfer_inventory');
//                    $newUserNotif->setRefId($transferInventory->getId());
//                    $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been sent for approval.');
//                    $em->persist($newUserNotif);
//
//                    $em->flush();
//
//                    $this->get('session')->getFlashBag()->set('success_messages', 'Record successfully sent for approval.');
//
//                } else {
//
//
//                    if ($statusApprovalPendingFinalApproval && $statusApprovalPendingFinalApproval->getLevel() > 0) {
//
//                        $transferInventory->setApprovalBatchNo($transferInventory->getApprovalBatchNo() + 1);
//                        $transferInventory->setStatus('Pending Final Approval');
//
//                        for ($i = $statusApprovalPendingFinalApproval->getLevel(); $i > 0; $i--) {
//
//                            $newTransferInventoryStatus = new TransferInventoryStatusEntity();
//                            $newTransferInventoryStatus->setTransferInventory($transferInventory);
//                            $newTransferInventoryStatus->setStatus('Pending Approval');
//                            $newTransferInventoryStatus->setBatchNo($transferInventory->getApprovalBatchNo());
//                            $em->persist($newTransferInventoryStatus);
//                        }
//
//                        $newUserNotif = new UserNotifEntity();
//                        $newUserNotif->setUser($transferInventory->getUser());
//                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//                        $newUserNotif->setRef('transfer_inventory');
//                        $newUserNotif->setRefId($transferInventory->getId());
//                        $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been sent for final approval.');
//                        $em->persist($newUserNotif);
//
//                        $em->flush();
//
//                        $this->get('session')->getFlashBag()->set('success_messages', 'Record successfully sent for approval.');
//                    } else {
//
//                        $transferInventory->setStatus('Approved');
//
//                        $newUserNotif = new UserNotifEntity();
//                        $newUserNotif->setUser($transferInventory->getUser());
//                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//                        $newUserNotif->setRef('transfer_inventory');
//                        $newUserNotif->setRefId($transferInventory->getId());
//                        $newUserNotif->setDetail('SRS No. ' . $transferInventory->getTransferNo() . ' has been approved.');
//                        $em->persist($newUserNotif);
//
//                        $em->flush();
//
//                        /*$inventoryService = $this->get('rxconnexion.inventoryService');
//                        $inventoryService->recordMovement('Inventory Transfer Inventory Send', array(
//                            'transferInventory' => $transferInventory
//                        ));*/
//
//                        $this->get('session')->getFlashBag()->set('success_messages', 'Record successfully sent for receiving.');
//                    }
//                }
            //}
            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/print/{id}",
     *      name = "transfer_inventory_print"
     * )
     */
    public function printAction($id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Print'))) return $authService->redirectToHome();

        $transferInventory = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($id));

        $facade = $this->get('knp_snappy.pdf');
        $response = new Response();
        $this->render('@RxConnexion/TransferInventory/print.pdf.twig', array(
            'transferInventory' => $transferInventory
        ), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);

        $filePath = __DIR__ . '/../../../web/tmp/transfer-inventory-print-' . time() . '.pdf';
        file_put_contents($filePath, $content);

        // Start of stream download

        $file = $filePath;

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="SRS No. ' . $transferInventory->getTransferNo() . '.pdf"');

        $handle = fopen($file, 'rb');
        $chunkSize = 1024*1024;

        if($handle !== false) {

            while (!feof($handle)) {
                $buffer = fread($handle, $chunkSize);
                echo $buffer;
                ob_flush();
                flush();
            }

            fclose($handle);
        }

        unlink($filePath);

        exit();
    }

    /**
     * @Route(
     *      "/item/index/{transferInventory_id}",
     *      name = "transfer_inventory_item"
     * )
     */
    public function itemAction($transferInventory_id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $userData = $this->get('session')->get('userData');

        /**@var TransferInventoryEntity $transferInventory*/
        $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));
        $defaultItemDetails = $em->getRepository('RxConnexionBundle:TransferInventoryItemDefaultEntity')->getAllActiveDetailByDate($transferInventory->getTransferDateAsString());

        $canApproveByUser = false; #$em->getRepository('RxConnexionBundle:TransferInventoryEntity')->countForApprovalByUser($this->get('session')->get('userData'), $transferInventory->getStatus(), $transferInventory->getId());

        $itemIdQtys = array();
        if($transferInventory->getTransferInventoryItems()->count()){
            /**@var TransferInventoryItemEntity $transferInventoryItem*/
            foreach ($transferInventory->getTransferInventoryItems() as $transferInventoryItem){
                $itemIdQtys[$transferInventoryItem->getItem()->getId()] = array(
                    'itemQty' => $transferInventoryItem->getQuantity(),
                    'itemIsConsumable' => $transferInventoryItem->getIsConsumable(),
                    'itemNote' => $transferInventoryItem->getNote(),
                    'serialNos' => $transferInventoryItem->getInventorySerialNos(),
                );
            }
        }else{
            if(count($defaultItemDetails) && (($transferInventory->getLocationTo() && $transferInventory->getLocationTo()) || ($transferInventory->getLocationFrom() && $transferInventory->getLocationFrom()))){
                foreach ($defaultItemDetails as $defaultItemDetail){
                    $transferInventoryItem = new TransferInventoryItemEntity();
                    $transferInventoryItem->setQuantity($defaultItemDetail['quantity']);
                    $transferInventoryItem->setQuantityRequested($defaultItemDetail['quantity']);
                    $transferInventoryItem->setIsConsumable($defaultItemDetail['is_consumable']);
                    $transferInventoryItem->setNote($defaultItemDetail['note']);
                    $transferInventoryItem->setItem($em->getReference(ItemEntity::class, $defaultItemDetail['item_id']));
                    $transferInventoryItem->setTransferInventory($transferInventory);
                    $em->persist($transferInventoryItem);
                    $itemIdQtys[$defaultItemDetail['item_id']] = array(
                        'itemQty' => $defaultItemDetail['quantity'],
                        'itemIsConsumable' => $defaultItemDetail['is_consumable'],
                        'itemNote' => $defaultItemDetail['note']
                    );
                }
                $em->flush();
            }
        }
        return $this->render('@RxConnexion/TransferInventory/item.html.twig', array(
            'title' => 'Transfer Supplies Items',
            'page_title' => 'Transfer Supplies Items',
            'javascripts' => array('rxconnexion/admin/js/transferInventory/transferInventoryItem.js?v=1.1.4'),
            'stylesheets' => array('rxconnexion/admin/css/transferInventory/transferInventoryItem.css?v=1.0.2'),
            'transferInventory_id' => $transferInventory_id,
            'transferInventory' => $transferInventory,
            'itemCategories' => $em->getRepository('RxConnexionBundle:ItemCategoryEntity')->findBy(array(), array('description' => 'ASC')),
            'canApproveByUser' => $canApproveByUser,
//            'statusApproval' => $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Transfer Inventory ' . $transferInventory->getStatus())),
            'itemIdQtys' => $itemIdQtys,
            'userIsReceivingBranch' => $userData['type'] == 'Super Admin' ? false : in_array($transferInventory->getBranchTo()->getId(), $userData['branches']),
        ));
    }

    /**
     * @Route("/item/ajax_list", name="transfer_inventory_item_ajax_list")
     */
    public function item_ajax_listAction(Request $request) {

        $get = $request->query->all();

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/form", name="transfer_inventory_item_form")
     */
    public function item_formAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) $result['errorMessages'][] = 'You have not logged in. Please reload the page.';
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item New', 'Admin Transfer Inventory Item Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {

            $result['success'] = true;
            $em = $this->getDoctrine()->getManager();
            $transferInventory_id = $request->query->get('transferInventory_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));

            $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find(base64_decode($id));
            if (!$transferInventoryItem) {
                $transferInventoryItem = new TransferInventoryItemEntity();
            }

            $formOptions = array('action' => $action);
            $form = $this->createForm(TransferInventoryItemForm::class, $transferInventoryItem, $formOptions);

            $title = ($action === 'n' ? 'New' : 'Update') . ' Item';

            $result['html'] = $this->renderView('@RxConnexion/TransferInventory/item_form.html.twig', array(
                'page_title' => $title,
                'form' => $form->createView(),
                'action' => $action,
                'id' => $id
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/form_action", name="transfer_inventory_item_form_action")
     */
    public function item_form_actionAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) $result['errorMessages'][] = 'You have not logged in. Please reload the page.';
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item New', 'Admin Transfer Inventory Item Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {

            $em = $this->getDoctrine()->getManager();
            $transferInventoryItem_form = $request->get('transferInventoryItem');

            $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find($transferInventoryItem_form['transferInventory_id']);
            $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find($transferInventoryItem_form['id']);

            if (!$transferInventoryItem) {
                $transferInventoryItem = new TransferInventoryItemEntity();
            }

            $formOptions = array('action' => $transferInventoryItem_form['action']);
            $form = $this->createForm(TransferInventoryItemForm::class, $transferInventoryItem, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->validate($transferInventoryItem_form);

            if(!count($errors)) {
                switch($transferInventoryItem_form['action']) {

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $inventory = $em->getRepository('RxConnexionBundle:InventoryEntity')->find($transferInventoryItem_form['inventory_id']);

                            $transferInventoryItem->setInventory($inventory);
                            $transferInventoryItem->setTransferInventory($transferInventory);
                            $em->persist($transferInventoryItem);
                            $em->flush();

//                            $newAT = new AuditTrailEntity();
//                            $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                            $newAT->entity = $transferInventoryItem;
//                            $newAT->setRefTable('transfer_inventory_item');
//                            $newAT->parseInformation('New');
                            $em->persist($newAT);
                            $em->flush();

                            $result['successMessages'] = array('Record Successfully Saved.');
                        }

                        break;

                    case 'u': // update

//                        $transferInventoryItem_obj = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find($transferInventoryItem_form['id']);

//                        $newAT = new AuditTrailEntity();
//                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                        $newAT->entity = $transferInventoryItem_obj;
//                        $newAT->setRefTable('transfer_inventory_item');
//                        $newAT->parseOriginalDetails();

//                        $inventory = $em->getRepository('RxConnexionBundle:InventoryEntity')->find($transferInventoryItem_form['inventory_id']);

//                        $transferInventoryItem_obj->setInventory($inventory);
//                        $transferInventoryItem_obj->setQuantity($transferInventoryItem_form['quantity']);

//                        $newAT->parseInformation('Update');
//                        $em->persist($newAT);

                        $em->flush();

                        $result['successMessages'] = array('Record Successfully Updated.');

                        break;

                    case 'd': // delete

//                        $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find($transferInventoryItem_form['id']);
                        $em->remove($transferInventoryItem);

//                        $newAT = new AuditTrailEntity();
//                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                        $newAT->entity = $transferInventoryItem;
//                        $newAT->setRefTable('transfer_inventory_item');
//                        $newAT->parseInformation('Delete');
//                        $em->persist($newAT);

                        $em->flush();

                        $result['successMessages'] = array('Record Successfully Deleted.');

                        break;
                }

                $result['success'] = true;

            } else {

                foreach($errors as $error) {
                    $result['errorMessages'][] = $error;
                }
            }
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/do_add", name="transfer_inventory_item_do_add")
     */
    public function item_do_addAction(Request $request) {

        $result['success'] = false;

        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedIn()) {

            $transferInventory_id = $request->get('transferInventory_id');
            $item_id = $request->get('id');
            $quantity = $request->get('quantity');
            $note = $request->get('note');
            $consumable = $request->get('consumable');
            $serialNos = $request->get('serialNos');

            if($quantity > 0) {

                $em = $this->getDoctrine()->getManager();
                $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));
                $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find(base64_decode($item_id));
                /**@var TransferInventoryItemEntity $transferInventoryItem*/
                /**@var ItemEntity $item_obj*/
                /**@var TransferInventoryEntity $transferInventory*/
                $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->findOneBy(array(
                    'item' => $item,
                    'transferInventory' => $transferInventory
                ));

                $item_obj = $em->getRepository('RxConnexionBundle:ItemEntity')->find(base64_decode($item_id));
	            if($item_obj->getIsItemised() && is_null($serialNos)) {
		            $result['messages'] = 'Please add serial no.';
		            goto ReturnArea;
	            }

                if($transferInventoryItem) {
                    //$transferInventoryItem->setQuantityRequested($quantity);
                    $transferInventoryItem->setQuantity($quantity);
                    $transferInventoryItem->setNote($note);
                    $transferInventoryItem->setIsConsumable($consumable == 'true');

                    /**@var TransferInventoryItemInventorySerialNoEntity $transferInventoryItemInventorySerialNo*/
                    foreach ($transferInventoryItem->getTransferInventoryItemInventorySerialNos() as $transferInventoryItemInventorySerialNo) {
                        if (!in_array($transferInventoryItemInventorySerialNo->getInventorySerialNo()->getId(), $serialNos)) {
                            $em->remove($transferInventoryItemInventorySerialNo);
                            $transferInventoryItem->removeTransferInventoryItemInventorySerialNo($transferInventoryItemInventorySerialNo);
                        }
                    }

                    if(!is_null($serialNos)) {
	                    foreach ($serialNos as $serialNo) {
	                    	if(!empty($serialNo)) {
			                    if (!in_array($serialNo, $transferInventoryItem->getInventorySerialNoIds())) {
				                    $tiiisn = new TransferInventoryItemInventorySerialNoEntity();
				                    $tiiisn->setTransferInventoryItem($transferInventoryItem);
				                    $tiiisn->setInventorySerialNo($em->getRepository(InventorySerialNoEntity::class)->find($serialNo));
				                    $transferInventoryItem->addTransferInventoryItemInventorySerialNo($tiiisn);
				                    $em->persist($tiiisn);
			                    }
		                    }
	                    }
                    }


                } else {
                    $transferInventoryItem = new TransferInventoryItemEntity();
                    $transferInventoryItem->setTransferInventory($transferInventory);
                    $transferInventoryItem->setItem($item_obj);
                    //$transferInventoryItem->setQuantityRequested($quantity);
                    $transferInventoryItem->setQuantity($quantity);
                    $transferInventoryItem->setNote($note);
                    $transferInventoryItem->setIsConsumable($consumable == 'true');
	                if(!is_null($serialNos)) {
		                foreach ($serialNos as $serialNo) {
		                	if(!empty($serialNo)) {
				                $tiiisn = new TransferInventoryItemInventorySerialNoEntity();
				                $tiiisn->setTransferInventoryItem($transferInventoryItem);
				                $tiiisn->setInventorySerialNo($em->getRepository(InventorySerialNoEntity::class)->find($serialNo));
				                $transferInventoryItem->addTransferInventoryItemInventorySerialNo($tiiisn);
				                $em->persist($tiiisn);
			                }
		                }
	                }

                    $em->persist($transferInventoryItem);
                }

                $em->flush();

                $result['success'] = true;

            } else {

                $result['messages'] = 'Please enter quantity.';
            }

        }

        ReturnArea:
        return new JsonResponse($result);
    }

    /**
     * @Route("/item/do_remove", name="transfer_inventory_item_do_remove")
     */
    public function item_do_removeAction(Request $request) {

        $result['success'] = false;

        $authService = $this->get('rx_connexion.authService');
        if($authService->isLoggedIn()) {

            $id = $request->get('id');
            $em = $this->getDoctrine()->getManager();
            $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find(base64_decode($id));

            $em->remove($transferInventoryItem);
            $em->flush();

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/delivery/ajax_list", name="transfer_inventory_delivery_ajax_list")
     */
    public function delivery_ajax_listAction(Request $request) {

        $get = $request->query->all();

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:TransferInventoryDeliveryEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/delivery/form", name="transfer_inventory_delivery_form")
     */
    public function delivery_formAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) $result['errorMessages'][] = 'You have not logged in. Please reload the page.';
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Delivery New', 'Admin Transfer Inventory Delivery Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {

            $result['success'] = true;
            $em = $this->getDoctrine()->getManager();
            $transferInventory_id = $request->query->get('transferInventory_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));
            $transferInventoryDelivery = $em->getRepository('RxConnexionBundle:TransferInventoryDeliveryEntity')->find(base64_decode($id));
            if(!$transferInventoryDelivery) {
                $transferInventoryDelivery = new TransferInventoryDeliveryEntity();
            }

            $formOptions = array(
                'action' => $action,
                'transferInventory_id' => $transferInventory_id
            );
            $form = $this->createForm(TransferInventoryDeliveryForm::class, $transferInventoryDelivery, $formOptions);

            $title = ($action === 'n' ? 'New' : 'Update') . ' Delivery';

            $result['html'] = $this->renderView('@RxConnexion/TransferInventory/delivery_form.html.twig', array(
                'page_title' => $title,
                'form' => $form->createView(),
                'action' => $action,
                'id' => $id,
                'transferInventory' => $transferInventory,
                'transferInventoryDelivery' => $transferInventoryDelivery
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/delivery/form_action", name="transfer_inventory_delivery_form_action")
     */
    public function delivery_form_actionAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) $result['errorMessages'][] = 'You have not logged in. Please reload the page.';
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Delivery New', 'Admin Transfer Inventory Delivery Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {

            $em = $this->getDoctrine()->getManager();
            $transferInventoryDelivery_form = $request->get('transferInventoryDelivery');
            $other_form = $request->get('otherForm');
            //$transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find($transferInventoryDelivery_form['transferInventory_id']);
            $transferInventoryDelivery = $em->getRepository('RxConnexionBundle:TransferInventoryDeliveryEntity')->find($transferInventoryDelivery_form['id']);
            if(!$transferInventoryDelivery) {
                $transferInventoryDelivery = new TransferInventoryDeliveryEntity();
            }

            $formOptions = array(
                'action' => $transferInventoryDelivery_form['action'],
                'transferInventory_id' => $transferInventoryDelivery_form['transferInventory']
            );

            $form = $this->createForm(TransferInventoryDeliveryForm::class, $transferInventoryDelivery, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:TransferInventoryDeliveryEntity')->validate($transferInventoryDelivery_form, $other_form);

            if(!count($errors)) {

                $inventoryService = $this->get('rx_connexion.inventoryService');

                switch($transferInventoryDelivery_form['action']) {

                    case 'n': // new

                        $form->handleRequest($request);

                        if($form->isValid()) {
                            /**@var TransferInventoryDeliveryEntity $transferInventoryDelivery*/
                            $transferInventoryDelivery_id = $em->getRepository(TransferInventoryDeliveryEntity::class)->nativeInsert($transferInventoryDelivery_form);
                            $transferInventoryDelivery = $em->getRepository(TransferInventoryDeliveryEntity::class)->find($transferInventoryDelivery_id);
                            //$em->persist($transferInventoryDelivery);

                            //$em->flush();

                            // TODO: Audit trail
                            /*$newAT = new AuditTrailEntity();
                            $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                            $newAT->entity = $transferInventoryDelivery;
                            $newAT->setRefTable('transfer_inventory_delivery');
                            $newAT->parseInformation('New');
                            $em->persist($newAT);
                            $em->flush();*/

                            $this->delivery_form_actionContinue($em, $transferInventoryDelivery, $other_form);

                            $em->refresh($transferInventoryDelivery);
                            $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                                'action' => 'New',
                                'transferInventoryDelivery' => $transferInventoryDelivery
                            ));

                            $result['successMessages'] = array('Record successfully saved.');
                            $result['success'] = true;

                        } else {
                            $result['errorMessages'] = array('Something went wrong, please try again. If problem persist please contact the administrator.');
                        }

                        break;

                    case 'u': // update

                        //$transferInventoryDelivery_obj = $em->getRepository('RxConnexionBundle:TransferInventoryDeliveryEntity')->find($transferInventoryDelivery_form['id']);

                        /*$newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $transferInventoryDelivery_obj;
                        $newAT->setRefTable('transfer_inventory_delivery');
                        $newAT->parseOriginalDetails();*/

                        $form->handleRequest($request);

                        if($form->isValid()) {

                            //$inventory = $em->getRepository('RxConnexionBundle:InventoryEntity')->find($transferInventoryDelivery_form['inventory_id']);

                            //$transferInventoryDelivery_obj->setInventory($inventory);
                            //$transferInventoryDelivery_obj->setQuantity($transferInventoryDelivery_form['quantity']);

                            //$newAT->parseInformation('Update');
                            //$em->persist($newAT);

                            //$em->flush();

                            $this->delivery_form_actionContinue($em, $transferInventoryDelivery, $other_form);

                            $em->refresh($transferInventoryDelivery);
                            $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                                'action' => 'Update',
                                'transferInventoryDelivery' => $transferInventoryDelivery
                            ));

                            $result['successMessages'] = array('Record successfully updated.');
                            $result['success'] = true;

                        } else {
                            $result['errorMessages'] = array('Something went wrong, please try again. If problem persist please contact the administrator.');
                        }

                        break;

                    case 'd': // delete

                        $inventoryService->recordMovement('Inventory Transfer Inventory Delivery', array(
                            'action' => 'Delete',
                            'transferInventoryDelivery' => $transferInventoryDelivery
                        ));

                        $transferInventory = $transferInventoryDelivery->getTransferInventory();
                        //$transferInventoryDelivery = $em->getRepository('RxConnexionBundle:TransferInventoryDeliveryEntity')->find($transferInventoryDelivery_form['id']);
                        $em->remove($transferInventoryDelivery);

                        /*$newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $transferInventoryDelivery;
                        $newAT->setRefTable('transfer_inventory_delivery');
                        $newAT->parseInformation('Delete');
                        $em->persist($newAT);*/

                        $em->flush();

                        foreach($transferInventory->getTransferInventoryItems() as $transferInventoryItem) {
                            $transferInventoryItem->updateQuantityDelivered();
                        }
                        $em->flush();

                        $result['successMessages'] = array('Record successfully deleted.');
                        $result['success'] = true;

                        break;
                }

            } else {

                foreach($errors as $error) {
                    $result['errorMessages'][] = $error;
                }
            }
        }

        return new JsonResponse($result);
    }

    private function delivery_form_actionContinue(ObjectManager $em, TransferInventoryDeliveryEntity $transferInventoryDelivery, $other_form) {

        if(isset($other_form['items']) && count($other_form['items']) > 0){
            foreach($other_form['items'] as $itemForm) {
                //$transferInventoryDeliveryItem = $transferInventoryDelivery->getTransferInventoryDeliveryItemByTranInvItemId($itemForm['id']);
                $transferInventoryDeliveryItem = null;
                if($itemForm['id']){
                    $transferInventoryDeliveryItem = $em->getRepository('RxConnexionBundle:TransferInventoryDeliveryItemEntity')->find($itemForm['id']);
                }


                if(!isset($itemForm['isValid'])) {
                    if($transferInventoryDeliveryItem) {
                        $em->remove($transferInventoryDeliveryItem);
                    }
                } else {
                    if(!$transferInventoryDeliveryItem) {
                        $transferInventoryDeliveryItem = new TransferInventoryDeliveryItemEntity();
                        $transferInventoryDeliveryItem->setTransferInventoryDelivery($transferInventoryDelivery);
                        $transferInventoryDeliveryItem->setTransferInventoryItem($em->getReference('RxConnexionBundle:TransferInventoryItemEntity', $itemForm['tii']));
                        $transferInventoryDeliveryItem->setInventory($em->getReference('RxConnexionBundle:InventoryEntity', $itemForm['inventoryId']));
                        $em->persist($transferInventoryDeliveryItem);
	                    $transferInventoryDelivery->addTransferInventoryDeliveryItem($transferInventoryDeliveryItem);
                    }
                    $transferInventoryDeliveryItem->setQuantity($itemForm['qty']);


	                // SERIAL NO
	                if(isset($itemForm['inventorySerialNo'])) {

		                $transferInventoryItemInventorySerialNos = new ArrayCollection();
		                foreach ($itemForm['inventorySerialNo'] as $isn) {
			                if(!empty($isn)) {
				                $transferInventoryItemInventorySerialNos->add($em->getRepository(TransferInventoryItemInventorySerialNoEntity::class)->find($isn));
			                }
		                }

		                $transferInventoryDeliveryItem->cascadePersistRemoveTransferInventoryDeliveryItemTransferInventoryItemInvSerialNos_byTransferInventoryItemInvSerialNos($transferInventoryItemInventorySerialNos, $em);

	                }
                }
            }
        }

        $em->flush();

        foreach($transferInventoryDelivery->getTransferInventory()->getTransferInventoryItems() as $transferInventoryItem) {
            $transferInventoryItem->updateQuantityDelivered();
        }
        $em->flush();

        return true;
    }

    /**
     * @Route("/item/delivery/ajax_list", name="transfer_inventory_item_delivery_ajax_list")
     */
    public function item_delivery_ajax_listAction(Request $request) {

        $get = $request->query->all();

        $result = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => array()
        );

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/delivery/form_all", name="transfer_inventory_item_delivery_form_all")
     */
    public function item_delivery_form_allAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item Receive'))) return $authService->redirectToHome();

        if(!count($result['errorMessages'])) {

            $result['success'] = true;
            $em = $this->getDoctrine()->getManager();
            $transferInventory_id = $request->query->get('transferInventory_id');

            $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));

            $result['html'] = $this->renderView('@RxConnexion/TransferInventory/item_delivery_form_all.html.twig', array(
                'page_title' => 'Receive Items',
                'transferInventory_id' => $transferInventory_id,
                'transferInventory' => $transferInventory
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/delivery/form_all_action", name="transfer_inventory_item_delivery_form_all_action")
     */
    public function item_delivery_form_all_actionAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item Receive'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $transferInventory_id = $request->get('transferInventory_id');
        $transferInventoryItemDelivery_form = $request->get('transferInventoryItemDelivery');
        $transferInventoryItems_form = $request->get('transferInventoryItems');
        $quantity = 0;
        $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));

        if(empty($transferInventoryItemDelivery_form['receiveDate']))
            $result['errorMessages'][] = 'Receive should not be blank.';

        foreach($transferInventoryItems_form as $transferInventoryItem_form) {
        	if($transferInventoryItem_form['quantity']) {
		        $quantity += str_replace(',', '', $transferInventoryItem_form['quantity']);

		        foreach ($transferInventory->getTransferInventoryItems() as $transferInventoryItem) {
			        if ($transferInventoryItem_form['id'] === $transferInventoryItem->getId() && $transferInventoryItem->getQuantityReceived() + str_replace(',', '', $transferInventoryItem_form['quantity']) > $transferInventoryItem->getQuantity()) {
				        //$result['errorMessages'][] = 'Item ' . $transferInventoryItem->getInventory()->getItem()->getDescription() . ' already exceed its required quantity.';
				        $result['errorMessages'][] = 'Item ' . $transferInventoryItem->getItem()->getDescription() . ' already exceed its required quantity.';
			        }
		        }
	        }
        }

        if($quantity === 0) {
            $result['errorMessages'][] = 'Atleast one(1) item with quantity is required.';
        }

        if(!count($result['errorMessages'])) {

            $inventoryService = $this->get('rx_connexion.inventoryService');
            //$location = $transferInventory->getBranchTo()->getFirstLocation();

            foreach($transferInventoryItems_form as $transferInventoryItem_form) {
                if(str_replace(',', '', $transferInventoryItem_form['quantity']) > 0) {
                	/**@var TransferInventoryItemEntity $transferInventoryItem*/
                    foreach($transferInventory->getTransferInventoryItems() as $transferInventoryItem) {
                        if($transferInventoryItem_form['id'] === $transferInventoryItem->getId()) {

                            $newTransferInventoryItemDelivery = new TransferInventoryItemDeliveryEntity();
                            $newTransferInventoryItemDelivery->setTransferInventoryItem($transferInventoryItem);
                            $newTransferInventoryItemDelivery->setReceiveDate($transferInventoryItemDelivery_form['receiveDate']);
                            $newTransferInventoryItemDelivery->setQuantity($transferInventoryItem_form['quantity']);
                            //$newTransferInventoryItemDelivery->setLocation(isset($transferInventoryItem_form['location_id']) ? $em->getReference('RxConnexionBundle:LocationEntity', $transferInventoryItem_form['location_id']) : null);
                            //$newTransferInventoryItemDelivery->setLocation($location);
                            $em->persist($newTransferInventoryItemDelivery);

                            $transferInventoryItem->setQuantityReceived($transferInventoryItem->getQuantityReceived() + str_replace(',', '', $transferInventoryItem_form['quantity']));

							if(isset($transferInventoryItem_form['inventorySerialNo'])) {
								if ($transferInventoryItem_form['inventorySerialNo']) {
									foreach ($transferInventoryItem_form['inventorySerialNo'] as $isn) {
										if (!empty($isn)) {
											/**@var TransferInventoryDeliveryItemTransferInventoryItemInvSerialNoEntity $transferInventoryDeliveryItemTransferInventoryItemInvSerialNo */
											$transferInventoryDeliveryItemTransferInventoryItemInvSerialNo = $em->getRepository(TransferInventoryDeliveryItemTransferInventoryItemInvSerialNoEntity::class)->find($isn);
											$newIsn = new TransferInventoryItemDeliveryInventorySerialNoEntity();
											$newIsn->setTransferInventoryItemDelivery($newTransferInventoryItemDelivery);
											$newIsn->setInventorySerialNo($transferInventoryDeliveryItemTransferInventoryItemInvSerialNo->getTransferInventoryItemInventorySerialNo()->getInventorySerialNo());
											$newIsn->setTransferInventoryDeliveryItemTransferInventoryItemInvSerialNo($transferInventoryDeliveryItemTransferInventoryItemInvSerialNo);
											$em->persist($newIsn);
											$newTransferInventoryItemDelivery->addTransferInventoryItemDeliveryInventorySerialNo($newIsn);
											$transferInventoryDeliveryItemTransferInventoryItemInvSerialNo->getTransferInventoryItemInventorySerialNo()->getInventorySerialNo()->addTransferInventoryItemDeliveryInventorySerialNo($newIsn);
										}
									}
								}
							}

                            $em->flush();

                            /*$newAT = new AuditTrailEntity();
                            $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                            $newAT->entity = $newTransferInventoryItemDelivery;
                            $newAT->setRefTable('transfer_inventory_item_delivery');
                            $newAT->parseInformation('New');
                            $em->persist($newAT);
                            $em->flush();*/

                            $inventoryService->recordMovement('Inventory Transfer Inventory Item Receive', array(
                                'action' => 'New',
                                'transferInventoryItemDelivery' => $newTransferInventoryItemDelivery
                            ));
                        }
                    }
                }
            }

	        $transferInventory = $em->getRepository('RxConnexionBundle:TransferInventoryEntity')->find(base64_decode($transferInventory_id));
            $em->refresh($transferInventory);
            $transferInventory->setStatus($transferInventory->getTotalQuantity() == $transferInventory->getTotalQuantityReceived() ? 'Completed' : 'Approved');
            $em->flush();

            // TODO: accounting records
            /*if($transferInventory->getStatus() === 'Completed') {
                $inventoryService->recordAccountingTransferSupplies('Transfer Inventory', array('transferInventory' => $transferInventory));
            }*/

            $result['success'] = true;
            $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Saved.');
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/delivery/form", name="transfer_inventory_item_delivery_form")
     */
    public function item_delivery_formAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item Receive Update'))) return $authService->redirectToHome();

        if(!count($result['errorMessages'])) {

            $result['success'] = true;
            $em = $this->getDoctrine()->getManager();
            $transferInventoryItem_id = $request->query->get('transferInventoryItem_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find(base64_decode($transferInventoryItem_id));

            $transferInventoryItemDelivery = $em->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->find(base64_decode($id));
            if (!$transferInventoryItemDelivery) {
                $transferInventoryItemDelivery = new TransferInventoryItemDeliveryEntity();
            }

            $formOptions = array(
                'action' => $action,
                'branchId' => $transferInventoryItem->getTransferInventory()->getBranchTo()->getId(),
	            'transferInventoryItem_id' => $transferInventoryItem_id
            );
            $form = $this->createForm(TransferInventoryItemDeliveryForm::class, $transferInventoryItemDelivery, $formOptions);

            $title = ($action === 'n' ? 'Add' : 'Update') . ' Item Received';

            $result['html'] = $this->renderView('@RxConnexion/TransferInventory/item_delivery_form.html.twig', array(
                'page_title' => $title,
                'form' => $form->createView(),
                'action' => $action,
                'id' => $id,
                'transferInventoryItem' => $transferInventoryItem,
	            'transferInventoryItemDelivery' => $transferInventoryItemDelivery,
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/delivery/form_action", name="transfer_inventory_item_delivery_form_action")
     */
    public function item_delivery_form_actionAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = array();

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Transfer Inventory Item Receive Update'))) return $authService->redirectToHome();

        if(!count($result['errorMessages'])) {

            $inventoryService = $this->get('rx_connexion.inventoryService');
            $em = $this->getDoctrine()->getManager();
            $transferInventoryItemDelivery_form = $request->get('transferInventoryItemDelivery');

            $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find(base64_decode($transferInventoryItemDelivery_form['transferInventoryItem']));

            $transferInventoryItemDelivery = $em->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->find($transferInventoryItemDelivery_form['id']);
            if (!$transferInventoryItemDelivery) {
                $transferInventoryItemDelivery = new TransferInventoryItemDeliveryEntity();
            }

            $formOptions = array(
                'action' => $transferInventoryItemDelivery_form['action'],
                'branchId' => $transferInventoryItem->getTransferInventory()->getBranchTo()->getId()
            );
            $form = $this->createForm(TransferInventoryItemDeliveryForm::class, $transferInventoryItemDelivery, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->validate($transferInventoryItemDelivery_form);

            if(!count($errors)) {
                switch($transferInventoryItemDelivery_form['action']) {

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $transferInventoryItemDelivery->setTransferInventoryItem($transferInventoryItem);
                            $em->persist($transferInventoryItemDelivery);
                            $em->flush();

                            $em->refresh($transferInventoryItem);
                            $transferInventoryItem->updateQuantityReceived();
                            $em->flush();
                            $em->refresh($transferInventoryItem);
                            $transferInventory = $transferInventoryItem->getTransferInventory();
                            $transferInventory->setStatus($transferInventory->getTotalQuantity() == $transferInventory->getTotalQuantityReceived() ? 'Completed' : 'Approved');
                            $em->flush();

                            /*$newAT = new AuditTrailEntity();
                            $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                            $newAT->entity = $transferInventoryItemDelivery;
                            $newAT->setRefTable('transfer_inventory_item_delivery');
                            $newAT->parseInformation('New');
                            $em->persist($newAT);
                            $em->flush();*/

                            $inventoryService->recordMovement('Inventory Transfer Inventory Item Receive', array(
                                'action' => 'New',
                                'transferInventoryItemDelivery' => $transferInventoryItemDelivery
                            ));

                            $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Saved.');
                        }

                        break;

                    case 'u': // update

                        $transferInventoryItemDelivery_obj = $em->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->find($transferInventoryItemDelivery_form['id']);

                        /*$newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $transferInventoryItemDelivery_obj;
                        $newAT->setRefTable('transfer_inventory_item_delivery');
                        $newAT->parseOriginalDetails();*/

                        $transferInventoryItemDelivery_obj->setReceiveDate($transferInventoryItemDelivery_form['receive_date']);
                        $transferInventoryItemDelivery_obj->setQuantity($transferInventoryItemDelivery_form['quantity']);
                        //$transferInventoryItemDelivery_obj->setLocation(isset($transferInventoryItemDelivery_form['location']) ? $em->getReference('RxConnexionBundle:LocationEntity', $transferInventoryItemDelivery_form['location']) : null);

                        //$newAT->parseInformation('Update');
                        //$em->persist($newAT);

	                    $transferInventoryDeliveryItemTransferInventoryItemInvSerialNos = new ArrayCollection();
	                    foreach ($request->get('transferInventoryDeliveryItemTransferInventoryItemInvSerialNo') ?: [] as $tiidisn) {
	                    	if(!empty($tiidisn)) {
			                    $transferInventoryDeliveryItemTransferInventoryItemInvSerialNo = $em->getRepository(TransferInventoryDeliveryItemTransferInventoryItemInvSerialNoEntity::class)->find($tiidisn);
			                    $transferInventoryDeliveryItemTransferInventoryItemInvSerialNos->add($transferInventoryDeliveryItemTransferInventoryItemInvSerialNo);
		                    }
	                    }
	                    //die(var_dump($transferInventoryDeliveryItemTransferInventoryItemInvSerialNos->first()->getId(), $transferInventoryItemDelivery_obj->getTransferInventoryItemDeliveryInventorySerialNos()->first()->getTransferInventoryDeliveryItemTransferInventoryItemInvSerialNo()->getId()));
	                    $transferInventoryItemDelivery_obj->cascadeTransferInventoryItemDeliveryInventorySerialNos_byTransferInventoryDeliveryItemTransferInventoryItemInvSerialNo($transferInventoryDeliveryItemTransferInventoryItemInvSerialNos, $em);


                        $em->flush();

                        $em->refresh($transferInventoryItem);
                        $transferInventoryItem->updateQuantityReceived();
                        $em->flush();
                        $em->refresh($transferInventoryItem);
                        $transferInventory = $transferInventoryItem->getTransferInventory();
                        $transferInventory->setStatus($transferInventory->getTotalQuantity() == $transferInventory->getTotalQuantityReceived() ? 'Completed' : 'Approved');
                        $em->flush();
                        
                        

                        $inventoryService->recordMovement('Inventory Transfer Inventory Item Receive', array(
                            'action' => 'Update',
                            'transferInventoryItemDelivery' => $transferInventoryItemDelivery_obj
                        ));

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');

                        break;

                    case 'd': // delete

                        $transferInventoryItemDelivery = $em->getRepository('RxConnexionBundle:TransferInventoryItemDeliveryEntity')->find($transferInventoryItemDelivery_form['id']);
                        $em->remove($transferInventoryItemDelivery);

                        /*$newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $transferInventoryItemDelivery;
                        $newAT->setRefTable('transfer_inventory_item_delivery');
                        $newAT->parseInformation('Delete');
                        $em->persist($newAT);*/

                        $inventoryService->recordMovement('Inventory Transfer Inventory Item Receive', array(
                            'action' => 'Delete',
                            'transferInventoryItemDelivery' => $transferInventoryItemDelivery
                        ));

                        $em->flush();

	                    $transferInventoryItem = $em->getRepository('RxConnexionBundle:TransferInventoryItemEntity')->find(base64_decode($transferInventoryItemDelivery_form['transferInventoryItem']));
	                    $em->refresh($transferInventoryItem);
                        $transferInventoryItem->updateQuantityReceived();
                        $em->flush();
                        $em->refresh($transferInventoryItem);
                        $transferInventory = $transferInventoryItem->getTransferInventory();
                        $transferInventory->setStatus($transferInventory->getTotalQuantity() == $transferInventory->getTotalQuantityReceived() ? 'Completed' : 'Approved');
                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Deleted.');

                        break;
                }

                $result['success'] = true;

            } else {

                foreach($errors as $error) {
                    $result['errorMessages'][] = $error;
                }
            }
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/generate-egress/{pmti_id}", name="transfer_inventory_generate_egress")
     */
    public function transfer_inventory_generate_egressAction($pmti_id){
        /**
         * @var TransferInventoryEntity $transferInventory_i
         * @var TransferInventoryItemEntity $transferInventoryItem_i
         * @var TransferInventoryDeliveryEntity $transferInventoryDelivery_i
         * @var TransferInventoryDeliveryItemEntity $transferInventoryDeliveryItem_i
         */
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Project Management Inventory Egress'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $pmti = $em->getRepository('RxConnexionBundle:ProjectManagementTransferInventoryEntity')->find(base64_decode($pmti_id));
        $transferInventory_i = $pmti->getTransferInventoryIngress();

        $transferInventory_e = new TransferInventoryEntity();
        $transferInventory_e->setBranchFrom($transferInventory_i->getBranchTo());
        $transferInventory_e->setLocationFrom($transferInventory_i->getLocationTo());
        $transferInventory_e->setBranchTo($transferInventory_i->getBranchFrom());
        $transferInventory_e->setLocationTo($transferInventory_i->getLocationFrom());
        $transferInventory_e->setTransferDate(date('m/d/Y'));
//        $transferInventory_e->setDe($transferInventory_i->getDepartment());
        $transferInventory_e->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
        $em->persist($transferInventory_e);
        $em->flush(); // flush first to get id

        $transferInventory_e->setStatus(TransferInventoryEntity::STATUS_APPROVED);
        $transferInventory_e->setTransferNo('SRS-' . $transferInventory_e->getBranchFrom()->getCode() . '-' . $transferInventory_e->getBranchTo()->getCode() . '-' . sprintf('%006d', $transferInventory_e->getId()));

//        $newAT = new AuditTrailEntity();
//        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//        $newAT->entity = $transferInventory_e;
//        $newAT->setRefTable('transfer_inventory');
//        $newAT->parseInformation('New');
//        $em->persist($newAT);

        $pmti->setTransferInventoryEgress($transferInventory_e);

        $deliveredItems = $transferInventory_i->getDistinctDeliveredItems();
        foreach($transferInventory_i->getTransferInventoryItems() as $transferInventoryItem_i){

            if(/*!$transferInventoryItem_i->getIsConsumable() && */in_array($transferInventoryItem_i->getItem()->getId(), $deliveredItems['ids'])){
                $transferInventoryItem_e = new TransferInventoryItemEntity();
                $transferInventoryItem_e->setTransferInventory($transferInventory_e);
                $transferInventoryItem_e->setIsConsumable($transferInventoryItem_i->getIsConsumable());
                $transferInventoryItem_e->setInventory($transferInventoryItem_i->getInventory());
                $transferInventoryItem_e->setQuantity($transferInventoryItem_i->getQuantityDelivered());
                $transferInventoryItem_e->setItem($transferInventoryItem_i->getItem());
                $transferInventoryItem_e->setNote($transferInventoryItem_i->getNote());
                $em->persist($transferInventoryItem_e);

                /*$newAT = new AuditTrailEntity();
                $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                $newAT->entity = $transferInventoryEgressItem;
                $newAT->setRefTable('transfer_inventory_item');
                $newAT->parseInformation('New');
                $em->persist($newAT);*/
            }
        }

        $em->flush();


        return $this->redirect($this->generateUrl('transfer_inventory_item', array(
            'transferInventory_id' => $transferInventory_e->getIdEncoded()
        )), 302);

    }
}
