<?php

namespace RxConnexionBundle\Controller;

use Doctrine\Common\Persistence\ObjectManager;
use RxConnexionBundle\Entity\CanvassEntity;
use RxConnexionBundle\Entity\CanvassItemEntity;
use RxConnexionBundle\Entity\HealthFacilityEntity;
use RxConnexionBundle\Entity\MaterialRequisitionItemUnitMeasurementEntity;
use RxConnexionBundle\Entity\MaterialRequisitionNoteEntity;
use RxConnexionBundle\Entity\PurchaseInvoiceEntity;
use RxConnexionBundle\Entity\PurchaseOrderBreakdownItemDeliverySerialNoEntity;
use RxConnexionBundle\Entity\SupplierEntity;
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\CanvassItemUnitMeasurementEntity;

use RxConnexionBundle\Entity\MaterialRequisitionEntity;
use RxConnexionBundle\Entity\PurchaseOrderStatusEntity;
//use RxConnexionBundle\Entity\UserNotifEntity;
use RxConnexionBundle\Form\MaterialRequisitionForm;

use RxConnexionBundle\Entity\MaterialRequisitionItemEntity;
use RxConnexionBundle\Form\MaterialRequisitionItemForm;

use RxConnexionBundle\Entity\MaterialRequisitionStatusEntity;

use RxConnexionBundle\Entity\CanvassStatusEntity;

use RxConnexionBundle\Entity\CanvassItemSupplierEntity;
use RxConnexionBundle\Form\CanvassItemSupplierForm;

use RxConnexionBundle\Entity\PurchaseOrderEntity;
use RxConnexionBundle\Entity\PurchaseOrderItemEntity;

use RxConnexionBundle\Entity\PurchaseOrderBreakdownEntity;
use RxConnexionBundle\Entity\PurchaseOrderBreakdownItemEntity;
use RxConnexionBundle\Form\MaterialRequisitionNoteForm;
use RxConnexionBundle\Form\PurchaseOrderBreakdownForm;

use RxConnexionBundle\Entity\PurchaseOrderBreakdownInvoiceEntity;
use RxConnexionBundle\Entity\PurchaseOrderBreakdownItemDeliveryEntity;
use RxConnexionBundle\Form\PurchaseOrderBreakdownItemDeliveryForm;

//use RxConnexionBundle\Entity\TransmittalEntity;
//use RxConnexionBundle\Form\TransmittalForm;

//use RxConnexionBundle\Entity\TransmittalItemEntity;

//use RxConnexionBundle\Entity\TransmittalItemDeliveryEntity;
//use RxConnexionBundle\Form\TransmittalItemDeliveryForm;

//use RxConnexionBundle\Entity\TransactionEntity;
//use RxConnexionBundle\Entity\TransactionLinkEntity;
//use RxConnexionBundle\Entity\TransactionJournalEntryEntity;
//use RxConnexionBundle\Entity\GeneralLedgerAccountEntity;
//use RxConnexionBundle\Entity\SubsidiaryLedgerAccountEntity;
//use RxConnexionBundle\Entity\CheckTranEntity;

use RxConnexionBundle\Entity\PurchaseInvoicePaymentEntity;
use RxConnexionBundle\Form\PurchaseInvoicePaymentForm;

use RxConnexionBundle\Entity\PurchaseInvoiceCreditPaymentEntity;
use RxConnexionBundle\Form\PurchaseInvoiceCreditPaymentForm;

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

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

        $user = $this->getUser();
        return $this->render('@RxConnexion/MaterialRequisition/index.html.twig', array(
            'title' => 'Order Supplies',
            'page_title' => 'Order Supplies',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/materialRequisition.js','rxconnexion/admin/js/report/report.js'),
            'status' => $request->query->get('status'),
            'user' => $user,
        ));
    }

    /**
     * @Route("/ajax_list", name="material_requisition_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:MaterialRequisitionEntity')->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 = "material_requisition_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 Material Requisition New', 'Admin Material Requisition Update'))) return $authService->redirectToHome();

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

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

//        $userBranches = array();
//        if(!is_null($userData) && !empty($userData)) {
//            if ($userData['type'] != 'Super Admin') {
//                if (count($userData['company']['companyBranches']) > 0) {
//                    $hf_ors = '';
//                    foreach ($userData['company']['companyBranches'] as $key => $branchId) {
//                        $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "hf.`id` = :healthFacility_id_$key";
//                        $userBranches[] = $branchId;
//                    }
//                } else {
//                    $userBranches[] = null;
//                }
//            }
//        }

        $formOptions = array(
            'action' => $action,
//            'user_branchIds' => $userBranches,
//            'user_departmentIds' => $userData['departmentIds']
        );
        $form = $this->createForm(MaterialRequisitionForm::class, $materialRequisition, $formOptions);

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

            $materialRequisition_form = $request->get($form->getName());
            $result = $this->processForm($materialRequisition_form, $materialRequisition, $form, $request, $user);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('material_requisition'), 302);
                } else if($result['redirect'] === 'item') {
                    return $this->redirect($this->generateUrl('material_requisition_item', array(
                        'materialRequisition_id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('material_requisition_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('material_requisition_form'), 302);
                }
            }
        }

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

        return $this->render('@RxConnexion/MaterialRequisition/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/materialRequisition_form.js?v=1.0.2'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id
        ));
    }

    private function processForm($materialRequisition_form, $materialRequisition, $form, Request $request, $user) {

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

        $errors = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->validate($materialRequisition_form);

        if(!count($errors)) {

            switch($materialRequisition_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $userData = $this->get('session')->get('userData');

                        //$materialRequisition->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $userData['id']));
                        $em->persist($materialRequisition);
                        $em->flush();

                        $materialRequisition->setMaterialRequisitionNo('MRN-' . sprintf('%03d', $materialRequisition->getHealthFacility()->getId()) . '-' . sprintf('%012d', $materialRequisition->getId()));
                        $em->flush();

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

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

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

                    } else {

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

                    break;

                case 'u': // update

                    $materialRequisition_obj = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find($materialRequisition_form['id']);

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

                    $materialRequisition_obj->setHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity', $materialRequisition_form['healthFacility']));
//                    $materialRequisition_obj->setDepartment($em->getReference('RxConnexionBundle:DepartmentEntity', $materialRequisition_form['department']));
//                    $materialRequisition_obj->setPurpose($em->getReference('RxConnexionBundle:PurposeEntity', $materialRequisition_form['purpose']));
                    $materialRequisition_obj->setRequestDate($materialRequisition_form['request_date']);
                    $materialRequisition_obj->setReferenceNo($materialRequisition_form['reference_no']);
                    $materialRequisition_obj->setTitle($materialRequisition_form['title']);
//                    $materialRequisition_obj->setSpecificPurpose($materialRequisition_form['specific_purpose']);
                    $materialRequisition_obj->setNote($materialRequisition_form['note']);
                    $materialRequisition->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $materialRequisition_form['account_user']));

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

                    $em->flush();

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

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

                    break;

                case 'd': // delete

                    $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find($materialRequisition_form['id']);
                    $em->remove($materialRequisition);

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

                    $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;
    }

    /**
     * @Route("/dashboard_data", name="material_requisition_dashboard_data")
     */
    public function dashboard_dataAction() {

        $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 Material Requisition'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {
            $result['success'] = true;
            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/dashboard_data.html.twig', array(
                'mrs' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->dashboardData($this->get('session')->get('userData'))
            ));
        }

        return new JsonResponse($result);
    }

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

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

        $em = $this->getDoctrine()->getManager();
        $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));

        return $this->render('@RxConnexion/MaterialRequisition/item.html.twig', array(
            'title' => 'Material Requisition Items',
            'page_title' => 'Material Requisition Items',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/materialRequisitionItem.js?v=1.0.5'),
            'materialRequisition_id' => $materialRequisition_id,
            'materialRequisition' => $materialRequisition
        ));
    }

    /**
     * @Route("/item/ajax_list", name="material_requisition_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:MaterialRequisitionItemEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/form", name="material_requisition_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 Material Requisition Item New', 'Admin Material Requisition 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();
            $materialRequisition_id = $request->query->get('materialRequisition_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));
            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));
            $materialRequisitionItem = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')->find(base64_decode($id));

            if(!$materialRequisitionItem) {
                $materialRequisitionItem = new MaterialRequisitionItemEntity();
            }

            $formOptions = array(
                'materialRequisition_id' => $materialRequisition->getId(),
                'action' => $action
            );
            $form = $this->createForm(MaterialRequisitionItemForm::class, $materialRequisitionItem, $formOptions);

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

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/item_form.html.twig', array(
                'page_title' => $title,
                'form' => $form->createView(),
                'action' => $action,
                'id' => $id,
                'itemCategories' => $em->getRepository('RxConnexionBundle:ItemCategoryEntity')->findBy(array(), array('description' => 'ASC')),
                'suppliers' => $em->getRepository('RxConnexionBundle:SupplierEntity')->findBy(array(), array('description' => 'ASC'))
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/form_action", name="material_requisition_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 Material Requisition Item New', 'Admin Material Requisition 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();
            $materialRequisitionItem_form = $request->get('materialRequisitionItem');

            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find($materialRequisitionItem_form['materialRequisition_id']);
            $materialRequisitionItem_obj = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')->find($materialRequisitionItem_form['id']);
            $materialRequisitionItem = new MaterialRequisitionItemEntity($materialRequisitionItem_obj);

            $formOptions = array('action' => $materialRequisitionItem_form['action']);
            $form = $this->createForm(new MaterialRequisitionItemForm($materialRequisition, $materialRequisitionItem_obj), $materialRequisitionItem, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')->validate($materialRequisitionItem_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find($materialRequisitionItem_form['item_id']);

                            $materialRequisitionItem->setItem($item);
                            $materialRequisitionItem->setLocation($materialRequisitionItem_form['location_id'] > 0 ? $em->getReference('RxConnexionBundle:LocationEntity', $materialRequisitionItem_form['location_id']) : null);
                            $materialRequisitionItem->setMaterialRequisition($materialRequisition);
                            $em->persist($materialRequisitionItem);
                            $em->flush();

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

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

                        break;

                    case 'u': // update

                        $materialRequisitionItem_obj = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')->find($materialRequisitionItem_form['id']);

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

                        $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find($materialRequisitionItem_form['item_id']);

                        $materialRequisitionItem_obj->setItem($item);
                        $materialRequisitionItem_obj->setLocation($materialRequisitionItem_form['location_id'] > 0 ? $em->getReference('RxConnexionBundle:LocationEntity', $materialRequisitionItem_form['location_id']) : null);
                        $materialRequisitionItem_obj->setQuantity($materialRequisitionItem_form['quantity']);
                        $materialRequisitionItem_obj->setControlNo($materialRequisitionItem_form['control_no']);

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

                        $em->flush();

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

                        break;

                    case 'd': // delete

                        $materialRequisitionItem = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')->find($materialRequisitionItem_form['id']);
                        $em->remove($materialRequisitionItem);

                        $newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $materialRequisitionItem;
                        $newAT->setRefTable('material_requisition_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;
                }
            }
        }*/

        $result['success'] = false;

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

            $materialRequisition_id = $request->get('materialRequisition_id');
            $item_id = $request->get('id');
            //$locationId = $request->get('location');
            //$defaultLocationId = $request->get('defaultLocation');
            $price = str_replace(',', '', $request->get('price'));
	        $initialPrice = str_replace(',', '', $request->get('initialPrice'));
	        $totalPrice = str_replace(',', '', $request->get('totalPrice'));
	        $tax = str_replace(',', '', $request->get('tax'));
	        $quantity = str_replace(',', '', $request->get('quantity'));
            $note = $request->get('note');

            if($quantity > 0 && /*$price > 0*/ is_numeric($price)) {

                //$adjustedCost = $request->get('adjustedCost');
                //$unitOfMeasurementId = $request->get('unitOfMeasurement');
                //$quantities = $request->get('itemQuantities');
                //$controlNo = $request->get('controlNo');
                $em = $this->getDoctrine()->getManager();
                $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));
                $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find(base64_decode($item_id));
                //$location = $em->getRepository('RxConnexionBundle:LocationEntity')->find(!empty($locationId) ? $locationId : $defaultLocationId );

                $materialRequisitionItem = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemEntity')->findOneBy(array(
                    'item' => $item,
                    'materialRequisition' => $materialRequisition
                ));

                $item_obj = $em->getRepository('RxConnexionBundle:ItemEntity')->find(base64_decode($item_id));

                //if(empty($locationId) && empty($defaultLocationId)  ){
                //    $result['success'] = false;
                //    $result['messages'] = 'Please select location';
                //} elseif(!$item_obj->getSmallestItemUnitMeasurement()){
                //    $result['success'] = false;
                //    $result['messages'] = 'There are no unit of measurement on this item';
                //} else {
                if($materialRequisitionItem) {
                    $materialRequisitionItem->setQuantity($quantity);
                    $materialRequisitionItem->setInitialPrice($initialPrice);
                    $materialRequisitionItem->setTax($tax);
                    $materialRequisitionItem->setPrice($price);
                    $materialRequisitionItem->setTotalPrice($totalPrice);
                    $materialRequisitionItem->setNote($note);
                    //$materialRequisitionItem->setLocation($location);
                    //$materialRequisitionItem->setItemUnitMeasurement($em->getReference('RxConnexionBundle:ItemUnitMeasurementEntity',$unitOfMeasurementId));
                    //$materialRequisitionItem->setAdjustedCost($adjustedCost);
                } else {
                    $materialRequisitionItem = new MaterialRequisitionItemEntity();
                    $materialRequisitionItem->setMaterialRequisition($materialRequisition);
                    $materialRequisitionItem->setItem($item_obj);
                    $materialRequisitionItem->setInitialPrice($initialPrice);
                    $materialRequisitionItem->setTax($tax);
                    $materialRequisitionItem->setPrice($price);
	                $materialRequisitionItem->setTotalPrice($totalPrice);
	                $materialRequisitionItem->setQuantity($quantity);
                    $materialRequisitionItem->setNote($note);
                    $materialRequisitionItem->setLocation(null);
                    //$materialRequisitionItem->setItemUnitMeasurement($item_obj->getSmallestItemUnitMeasurement());
                    //$materialRequisitionItem->setAdjustedCost($adjustedCost);
                    //$materialRequisitionItem->setControlNo($controlNo);
                    $em->persist($materialRequisitionItem);
                }

                $em->flush();

                /*if(!empty($quantities)){
                    $quantitiesArr = json_decode($quantities,true);

                    foreach ($quantitiesArr as $quantity){

                        $materialRequisitionItemUnitMeasurement = $em->getRepository('RxConnexionBundle:MaterialRequisitionItemUnitMeasurementEntity')->findOneBy(array(
                            'itemUnitMeasurement' => $em->getReference('RxConnexionBundle:ItemUnitMeasurementEntity',$quantity['item_unit_measurement_id']),
                            'materialRequisitionItem' => $materialRequisitionItem
                        ));

                        if($materialRequisitionItemUnitMeasurement){
                            $materialRequisitionItemUnitMeasurement->setQuantity($quantity['quantity']);
                            $em->flush();
                        } else {
                            $materialRequisitionItemUnitMeasurement_obj =  new MaterialRequisitionItemUnitMeasurementEntity();
                            $materialRequisitionItemUnitMeasurement_obj->setMaterialRequisitionItem($materialRequisitionItem);
                            $materialRequisitionItemUnitMeasurement_obj->setItemUnitMeasurement($em->getReference('RxConnexionBundle:ItemUnitMeasurementEntity',$quantity['item_unit_measurement_id']));
                            $materialRequisitionItemUnitMeasurement_obj->setQuantity($quantity['quantity']);
                            $em->persist($materialRequisitionItemUnitMeasurement_obj);
                            $em->flush();
                        }
                    }
                }*/

                $result['success'] = true;
                //}

            } else {
                $result['messages'] = "";
                if($quantity <= 0)
                    $result['messages'] .= "Please enter quantity.\n";

                if(/*$price <= 0*/!is_numeric($price))
                    $result['messages'] .= "Please enter valid price.\n";
            }

        }

        return new JsonResponse($result);
    }


    /**
     * @Route("/item/remove", name="material_requisition_item_remove")
     */
    public function item_removeAction(Request $request) {

        $result['success'] = false;

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

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

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

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

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

        $result['success'] = false;
        $result['errorMessages'] = array();
        $userData = $this->get('session')->get('userData');

        $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 Material Requisition Send'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

            $em = $this->getDoctrine()->getManager();
            $materialRequisition_id = $request->get('materialRequisition_id');
            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));
            $materialRequisition->setApprovalBatchNo($materialRequisition->getApprovalBatchNo() + 1);
//            $successMsg = 'Record has been successfully sent for approval.';

            $materialRequisition->setStatus('Active');
            $em->flush();
            $successMsg = 'Record has been successfully sent and approved.';

//            $this->createCanvass($materialRequisition);

            $this->canvass_po_autoCreate($materialRequisition);

            /*
            $statusApprovalPendingOperationsDivisionManagerApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Operations Division Manager Approval'));

            if($statusApprovalPendingOperationsDivisionManagerApproval && $statusApprovalPendingOperationsDivisionManagerApproval->getLevel() > 0) {

                $countForApprovalByUser = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->countForApprovalByUser($userData, 'Pending Operations Division Manager Approval');
                if($countForApprovalByUser <= 0){
                    $materialRequisition->setStatus('Pending Operations Division Manager Approval');

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

                        $newMaterialRequisitionStatus = new MaterialRequisitionStatusEntity();
                        $newMaterialRequisitionStatus->setMaterialRequisition($materialRequisition);
                        $newMaterialRequisitionStatus->setStatus('Pending Operations Division Manager Approval');
                        $newMaterialRequisitionStatus->setBatchNo($materialRequisition->getApprovalBatchNo());
                        $em->persist($newMaterialRequisitionStatus);
                    }

                    $em->flush();
                } else {

                    $materialRequisition->setStatus('Active');
                    $em->flush();
                    $successMsg = 'Record has been successfully sent and approved.';
                    $this->createCanvass($materialRequisition);
                }

            } else {

                $statusApprovalPendingAdminApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Admin Approval'));
                if($statusApprovalPendingAdminApproval && $statusApprovalPendingAdminApproval->getLevel() > 0) {

                    $countForApprovalByUser = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->countForApprovalByUser($userData, 'Pending Admin Approval');
                    if($countForApprovalByUser <= 0) {
                        $materialRequisition->setStatus('Pending Admin Approval');

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

                            $newMaterialRequisitionStatus = new MaterialRequisitionStatusEntity();
                            $newMaterialRequisitionStatus->setMaterialRequisition($materialRequisition);
                            $newMaterialRequisitionStatus->setStatus('Pending Admin Approval');
                            $newMaterialRequisitionStatus->setBatchNo($materialRequisition->getApprovalBatchNo());
                            $em->persist($newMaterialRequisitionStatus);
                        }

                        $em->flush();
                    } else {

                        $materialRequisition->setStatus('Active');
                        $em->flush();
                        $successMsg = 'Record has been successfully sent and approved.';
                        $this->createCanvass($materialRequisition);
                    }

                } else {

                    $materialRequisition->setStatus('Active');
                    $em->flush();

                    $this->createCanvass($materialRequisition);
                }
            }

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


            $em->flush();

            $this->get('session')->getFlashBag()->set('success_messages', $successMsg);

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }


    /**
     * @Route("/void", name="material_requisition_void")
     */
    public function voidAction(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 Material Requisition Void'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

            $em = $this->getDoctrine()->getManager();
            $materialRequisition_id = $request->get('materialRequisition_id');
            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));

            $materialRequisition->doVoid();

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

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

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/view/{materialRequisition_id}",
     *      defaults = {
     *          "materialRequisition_id": "0"
     *      },
     *      name = "material_requisition_view"
     * )
     */
    public function viewAction($materialRequisition_id) {

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

        $em = $this->getDoctrine()->getManager();
        $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));

//        $canApproveByUser = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->countForApprovalByUser($this->get('session')->get('userData'), $materialRequisition->getStatus(), $materialRequisition->getId()) > 0;

        return $this->render('@RxConnexion/MaterialRequisition/view.html.twig', array(
            'title' => 'Material Requisition Info',
            'page_title' => 'Material Requisition Info',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/materialRequisition_view.js'),
            'materialRequisition_id' => $materialRequisition_id,
            'materialRequisition' => $materialRequisition,
//            'canApproveByUser' => $canApproveByUser,
//            'statusApproval' => $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => $materialRequisition->getStatus()))
        ));
    }

    /**
     * @Route(
     *      "/status_approval",
     *      name = "material_requisition_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();
            $materialRequisition_id = $request->get('materialRequisition_id');
            $action = $request->get('action');
            $notes = $request->get('notes');
            $user = $authService->getUser();

            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));

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

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

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

                //$em->flush();

                $statusApprovalPendingOperationsDivisionManagerApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Operations Division Manager Approval'));
                $statusApprovalPendingFinanceOfficerApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Finance Officer Approval'));
                $statusApprovalPendingAdminApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Admin Approval'));

                $approvalCount = 0;

                foreach($materialRequisition->getMaterialRequisitionStatuses() as $materialRequisitionStatus) {
                    if($materialRequisitionStatus->getBatchNo() === $materialRequisition->getApprovalBatchNo() && $materialRequisitionStatus->getApprovalDescription() === 'Approved'){
                        $approvalCount++;
                    }
                }

                if($materialRequisition->getStatus() === 'Pending Operations Division Manager Approval') {

                    if($statusApprovalPendingOperationsDivisionManagerApproval->getLevel() === $approvalCount && $statusApprovalPendingFinanceOfficerApproval && $statusApprovalPendingFinanceOfficerApproval->getLevel() > 0) {

                        $materialRequisition->setStatus('Pending Finance Officer Approval');
                        $materialRequisition->setApprovalBatchNo($materialRequisition->getApprovalBatchNo() + 1);

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

                            $newMaterialRequisitionStatus = new MaterialRequisitionStatusEntity();
                            $newMaterialRequisitionStatus->setMaterialRequisition($materialRequisition);
                            $newMaterialRequisitionStatus->setStatus('Pending Finance Officer Approval');
                            $newMaterialRequisitionStatus->setBatchNo($materialRequisition->getApprovalBatchNo());
                            $em->persist($newMaterialRequisitionStatus);
                        }

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($materialRequisition->getUser());
                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                        $newUserNotif->setRef('material_requisition');
                        $newUserNotif->setRefId($materialRequisition->getId());
                        $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been approved and is now "Pending Finance Office Approval".');
                        $em->persist($newUserNotif);

                        $em->flush();

                    } else if($statusApprovalPendingOperationsDivisionManagerApproval->getLevel() === $approvalCount && $statusApprovalPendingAdminApproval && $statusApprovalPendingAdminApproval->getLevel() > 0) {

                        $materialRequisition->setStatus('Pending Admin Approval');
                        $materialRequisition->setApprovalBatchNo($materialRequisition->getApprovalBatchNo() + 1);

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

                            $newMaterialRequisitionStatus = new MaterialRequisitionStatusEntity();
                            $newMaterialRequisitionStatus->setMaterialRequisition($materialRequisition);
                            $newMaterialRequisitionStatus->setStatus('Pending Admin Approval');
                            $newMaterialRequisitionStatus->setBatchNo($materialRequisition->getApprovalBatchNo());
                            $em->persist($newMaterialRequisitionStatus);
                        }

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($materialRequisition->getUser());
                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                        $newUserNotif->setRef('material_requisition');
                        $newUserNotif->setRefId($materialRequisition->getId());
                        $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been approved and is now "Pending Admin Approval".');
                        $em->persist($newUserNotif);

                        $em->flush();

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

                        $materialRequisition->setStatus('Active');

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($materialRequisition->getUser());
                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                        $newUserNotif->setRef('material_requisition');
                        $newUserNotif->setRefId($materialRequisition->getId());
                        $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been approved and is now for supplier canvassing.');
                        $em->persist($newUserNotif);

                        $em->flush();

                        $this->createCanvass($materialRequisition);
                    }

                } else if($materialRequisition->getStatus() === 'Pending Finance Officer Approval') {

                    if($statusApprovalPendingFinanceOfficerApproval->getLevel() === $approvalCount && $statusApprovalPendingAdminApproval && $statusApprovalPendingAdminApproval->getLevel() > 0) {

                        $materialRequisition->setStatus('Pending Admin Approval');
                        $materialRequisition->setApprovalBatchNo($materialRequisition->getApprovalBatchNo() + 1);

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

                            $newMaterialRequisitionStatus = new MaterialRequisitionStatusEntity();
                            $newMaterialRequisitionStatus->setMaterialRequisition($materialRequisition);
                            $newMaterialRequisitionStatus->setStatus('Pending Admin Approval');
                            $newMaterialRequisitionStatus->setBatchNo($materialRequisition->getApprovalBatchNo());
                            $em->persist($newMaterialRequisitionStatus);
                        }

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($materialRequisition->getUser());
                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                        $newUserNotif->setRef('material_requisition');
                        $newUserNotif->setRefId($materialRequisition->getId());
                        $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been approved and is now "Pending Admin Approval".');
                        $em->persist($newUserNotif);

                        $em->flush();

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

                        $materialRequisition->setStatus('Active');

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($materialRequisition->getUser());
                        $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                        $newUserNotif->setRef('material_requisition');
                        $newUserNotif->setRefId($materialRequisition->getId());
                        $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been approved and is now for supplier canvassing.');
                        $em->persist($newUserNotif);

                        $em->flush();

                        $this->createCanvass($materialRequisition);
                    }

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

                    $materialRequisition->setStatus('Active');

                    $newUserNotif = new UserNotifEntity();
                    $newUserNotif->setUser($materialRequisition->getUser());
                    $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                    $newUserNotif->setRef('material_requisition');
                    $newUserNotif->setRefId($materialRequisition->getId());
                    $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been approved and is now for supplier canvassing.');
                    $em->persist($newUserNotif);

                    $em->flush();

                    $this->createCanvass($materialRequisition);
                }

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

            } else {

                $materialRequisition->setStatus('Rejected');

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

                //$em->flush();

                foreach($materialRequisition->getMaterialRequisitionStatuses() as $materialRequisitionStatus) {
                    if($materialRequisitionStatus->getBatchNo() === $materialRequisition->getApprovalBatchNo() && $materialRequisitionStatus->getApprovalDescription() === 'Pending'){
                        $materialRequisitionStatus->setApprovalDescription('Cancelled');
                    }
                }

                //$em->flush();

                $newUserNotif = new UserNotifEntity();
                $newUserNotif->setUser($materialRequisition->getUser());
                $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
                $newUserNotif->setRef('material_requisition');
                $newUserNotif->setRefId($materialRequisition->getId());
                $newUserNotif->setDetail('PR No. ' . $materialRequisition->getMaterialRequisitionNo() . ' has been rejected.');
                $em->persist($newUserNotif);

                $em->flush();

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

            return $this->redirect($this->generateUrl('material_requisition_view', array(
                'materialRequisition_id' => $materialRequisition_id
            )), 302);

        } else {

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

    private function createCanvass(MaterialRequisitionEntity $materialRequisition) {
        if($materialRequisition->getHasItemForSupplierCanvassing()) {

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

            $newCanvass = new CanvassEntity();
            $newCanvass->setMaterialRequisition($materialRequisition);
            $em->persist($newCanvass);
            $em->flush();

            $newCanvass->setCanvassNo('CVS-' . $materialRequisition->getHealthFacility()->getId() . '-' . sprintf('%06d', $newCanvass->getId()));

            foreach($materialRequisition->getMaterialRequisitionItems() as $materialRequisitionItem) {

                    $newCanvassItem = new CanvassItemEntity();
                    $newCanvassItem->setCanvass($newCanvass);
                    $newCanvassItem->setMaterialRequisitionItem($materialRequisitionItem);
                    $newCanvassItem->setQuantity($materialRequisitionItem->getQuantity());
                    $newCanvassItem->setItemUnitMeasurement($materialRequisitionItem->getItemUnitMeasurement());
                    $em->persist($newCanvassItem);
                    $em->flush();

//                    $itemSuppliers = $materialRequisitionItem->getItem()->getItemSuppliers();
                    $itemSupplier = $materialRequisitionItem->getItem();

                      /* one item one supplier supplier  */
//                    if(count($itemSuppliers)){
//                        foreach ($itemSuppliers as $itemSupplier){
//                            $newCanvassItemSupplier = new CanvassItemSupplierEntity();
//                            $newCanvassItemSupplier->setSupplier($itemSupplier->getSupplier());
//                            $newCanvassItemSupplier->setCanvassItem($newCanvassItem);
//                            $newCanvassItemSupplier->setPrice($itemSupplier->getPrice());
//                            $newCanvassItemSupplier->setIsSelected(true);
//                            $em->persist($newCanvassItemSupplier);
//                            $em->flush();
//                        }
//                    }

                $newCanvassItemSupplier = new CanvassItemSupplierEntity();
                $newCanvassItemSupplier->setSupplier($itemSupplier->getSupplier());
                $newCanvassItemSupplier->setCanvassItem($newCanvassItem);
                $newCanvassItemSupplier->setCanvassDate(date('Y-m-d'));
                $newCanvassItemSupplier->setQuantity($materialRequisitionItem->getQuantity());
                $newCanvassItemSupplier->setPrice($materialRequisitionItem->getPrice());
                $newCanvassItemSupplier->setIsSelected(true);
                $em->persist($newCanvassItemSupplier);
                $em->flush();

                    /*foreach ($materialRequisitionItem->getMaterialRequisitionItemUnitMeasurements() as $materialRequisitionItemUnitMeasurement){

                        $newCanvassItemUnitMeasurement =  new CanvassItemUnitMeasurementEntity();
                        $newCanvassItemUnitMeasurement->setCanvassItem($newCanvassItem);
                        $newCanvassItemUnitMeasurement->setItemUnitMeasurement($materialRequisitionItemUnitMeasurement->getItemUnitMeasurement());
                        $newCanvassItemUnitMeasurement->setQuantity($materialRequisitionItemUnitMeasurement->getQuantity());
                        $em->persist($newCanvassItemUnitMeasurement);
                        $em->flush();

                        $itemUnitMeasurement = $materialRequisitionItemUnitMeasurement->getItemUnitMeasurement();

                        if(count($itemUnitMeasurement->getItemUnitMeasurementSuppliers())) {
                            foreach ($itemUnitMeasurement->getItemUnitMeasurementSuppliers() as $itemUnitSupplier) {
                                $newCanvassItemSupplier = new CanvassItemSupplierEntity();
                                $newCanvassItemSupplier->setSupplier($itemUnitSupplier->getSupplier());
                                $newCanvassItemSupplier->setCanvassItem($newCanvassItem);
                                $newCanvassItemSupplier->setPrice($itemUnitSupplier->getPrice());
                                $newCanvassItemSupplier->setIsSelected(true);
                                $em->persist($newCanvassItemSupplier);
                                $em->flush();
                            }
                        }
                    }*/



                /*if($materialRequisitionItem->getQuantityForCanvassing() > 0) {

                    $newCanvassItem = new CanvassItemEntity();
                    $newCanvassItem->setCanvass($newCanvass);
                    $newCanvassItem->setMaterialRequisitionItem($materialRequisitionItem);
                    $newCanvassItem->setQuantity($materialRequisitionItem->getQuantityForCanvassing());
                    $em->persist($newCanvassItem);

                    $itemSuppliers = $materialRequisitionItem->getItem()->getItemSuppliers();

                    if(count($itemSuppliers)){
                        foreach ($itemSuppliers as $itemSupplier){
                            $newCanvassItemSupplier =  new CanvassItemSupplierEntity();
                            $newCanvassItemSupplier->setSupplier($itemSupplier->getSupplier());
                            $newCanvassItemSupplier->setCanvassItem($newCanvassItem);
                            $newCanvassItemSupplier->setPrice($itemSupplier->getPrice());
                            $newCanvassItemSupplier->setIsSelected(true);
                            $em->persist($newCanvassItemSupplier);
                            $em->flush();
                        }

                    }
                }*/
            }

//            $em->flush();
        }

        return $newCanvass;
    }

    /**
     * @Route(
     *      "/canvass",
     *      name = "material_requisition_canvass"
     * )
     */
    public function canvassAction(Request $request) {

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

        return $this->render('@RxConnexion/MaterialRequisition/canvass.html.twig', array(
            'title' => 'Canvass Supplier',
            'page_title' => 'Canvass Supplier',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/canvass.js?v=1.0.1'),
            'status' => $request->query->get('status')
        ));
    }

    /**
     * @Route("/canvass/ajax_list", name="material_requisition_canvass_ajax_list")
     */
    public function canvass_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:CanvassEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/canvass/view/{canvass_id}",
     *      name = "material_requisition_canvass_view"
     * )
     */
    public function canvass_viewAction($canvass_id) {

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

        $em = $this->getDoctrine()->getManager();
        $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

//        $canApproveByUser = $em->getRepository('RxConnexionBundle:CanvassEntity')->countForApprovalByUser($this->get('session')->get('userData'), $canvass->getStatus(), $canvass->getId()) > 0;

        return $this->render('@RxConnexion/MaterialRequisition/canvass_view.html.twig', array(
            'title' => 'Supplier Canvassing',
            'page_title' => 'Supplier Canvassing',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/canvass_view.js?v=1.0.4'),
            'canvass_id' => $canvass_id,
            'canvass' => $canvass,
//            'canApproveByUser' => $canApproveByUser,
//            'statusApproval' => $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => $canvass->getStatus()))
        ));
    }

    /**
     * @Route(
     *      "/canvass/print_blank_po/{canvass_id}",
     *      name = "material_requisition_canvass_print_blank_po"
     * )
     */
    public function canvass_print_blank_poAction($canvass_id) {

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

        $canvass = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

        $facade = $this->get('ps_pdf.facade');
        $response = new Response();
        $this->render('@RxConnexion/MaterialRequisition/canvass_print_blank_po.pdf.twig', array(
            'canvass' => $canvass
        ), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);

        $filePath = __DIR__ . '/../../../web/tmp/canvass-print-blank-po-' . time() . '.pdf';
        file_put_contents($filePath, $content);

        // Start of stream download

        $file = $filePath;

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $canvass->getMaterialRequisition()->getMaterialRequisitionNo() . '-blank-po.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("/canvass/send", name="material_requisition_canvass_send")
     */
    public function canvass_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 Canvass Send'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $canvass_id = $request->get('canvass_id');
        $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

        /*if($canvass->getHasQuantityForCanvassing()) {
            $result['errorMessages'][] = 'Some items has pending quantity for canvassing.';
        }*/

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

            $em->flush();

            $this->createPurchaseOrder($canvass);

            /*
            $canvass->setApprovalBatchNo($canvass->getApprovalBatchNo() + 1);

            $statusApprovalPendingPurchasingManagerApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Purchasing Manager Approval For PO'));
            if($statusApprovalPendingPurchasingManagerApproval && $statusApprovalPendingPurchasingManagerApproval->getLevel() > 0) {

                $canvass->setStatus('Pending Purchasing Manager Approval For PO');

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

                    $newCanvassStatus = new CanvassStatusEntity();
                    $newCanvassStatus->setCanvass($canvass);
                    $newCanvassStatus->setStatus('Pending Purchasing Manager Approval For PO');
                    $newCanvassStatus->setBatchNo($canvass->getApprovalBatchNo());
                    $em->persist($newCanvassStatus);
                }

                $em->flush();

            } else {

                $statusApprovalPendingAdminApprovalForPurchaseOrder = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Admin Approval For PO'));
                if($statusApprovalPendingAdminApprovalForPurchaseOrder && $statusApprovalPendingAdminApprovalForPurchaseOrder->getLevel() > 0) {

                    $canvass->setStatus('Pending Admin Approval For PO');

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

                        $newCanvassStatus = new CanvassStatusEntity();
                        $newCanvassStatus->setCanvass($canvass);
                        $newCanvassStatus->setStatus('Pending Admin Approval For PO');
                        $newCanvassStatus->setBatchNo($canvass->getApprovalBatchNo());
                        $em->persist($newCanvassStatus);
                    }

                    $em->flush();

                } else {

                    $canvass->setStatus('Approved');
                    $em->flush();

                    $this->createPurchaseOrder($canvass);
                }
            }

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

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

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/canvass/print_quotation/{canvass_id}",
     *      name = "material_requisition_canvass_print_quotation"
     * )
     */
    public function canvass_print_quotationAction($canvass_id) {

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

        $canvass = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));
        $suppliers = array();

        foreach($canvass->getCanvassItems() as $canvassItem) {
            foreach($canvassItem->getCanvassItemSuppliers() as $canvassItemSupplier) {
                $currency = $canvassItemSupplier->getCurrency();
                $supplier = $canvassItemSupplier->getSupplier();
                $totalAmt = $canvassItem->getQuantity() * $canvassItemSupplier->getPrice();
                $found = false;
                foreach($suppliers as $key => $supp) {
                    if($supp['id'] == $supplier->getId()) {
                        $suppliers[$key]['totalAmt'] += $totalAmt;
                        $found = true;
                        break;
                    }
                }
                if(!$found) {
                    $suppliers[] = array(
                        'id' => $supplier->getId(),
                        'desc' => $supplier->getDescription(),
                        'payMode' => $canvassItemSupplier->getPaymentMode(),
                        'payTerm' => $canvassItemSupplier->getTerm(),
                        'currencyCode' => $currency ? $currency->getCode() : '',
                        'totalAmt' => $totalAmt
                    );
                }
            }
        }

        $facade = $this->get('ps_pdf.facade');
        $response = new Response();
        $this->render('@RxConnexion/MaterialRequisition/canvass_print_quotation.pdf.twig', array(
            'canvass' => $canvass,
            'suppliers' => $suppliers
        ), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);

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

        // Start of stream download

        $file = $filePath;

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $canvass->getMaterialRequisition()->getMaterialRequisitionNo() . ' (Canvass no. ' . $canvass->getCanvassNo() . ') Quotation.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(
     *      "/canvass/status_approval",
     *      name = "material_requisition_canvass_status_approval"
     * )
     */
    public function canvass_status_approvalAction(Request $request) {

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

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

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

            $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

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

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

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

                //$em->flush();

                $statusApprovalPendingFinanceOfficerApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Finance Officer Approval For PO'));
                $statusApprovalPendingAdminApprovalForPurchaseOrder = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Admin Approval For PO'));

                $approvalCount = 0;

                foreach($canvass->getCanvassStatuses() as $canvassStatus) {
                    if($canvassStatus->getBatchNo() === $canvass->getApprovalBatchNo() && $canvassStatus->getApprovalDescription() === 'Approved'){
                        $approvalCount++;
                    }
                }

                if($canvass->getStatus() === 'Pending Finance Officer Approval For PO') {

                    if($statusApprovalPendingFinanceOfficerApproval->getLevel() === $approvalCount && $statusApprovalPendingAdminApprovalForPurchaseOrder && $statusApprovalPendingAdminApprovalForPurchaseOrder->getLevel() > 0) {

                        $canvass->setStatus('Pending Admin Approval For PO');
                        $canvass->setApprovalBatchNo($canvass->getApprovalBatchNo() + 1);

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

                            $newCanvassStatus = new CanvassStatusEntity();
                            $newCanvassStatus->setCanvass($canvass);
                            $newCanvassStatus->setStatus('Pending Admin Approval For PO');
                            $newCanvassStatus->setBatchNo($canvass->getApprovalBatchNo());
                            $em->persist($newCanvassStatus);
                        }

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($canvass->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('canvass');
                        $newUserNotif->setRefId($canvass->getId());
                        $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been approved and is now "Pending Admin Approval For PO".');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($canvass->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('canvass');
                        $newUserNotif->setRefId($canvass->getId());
                        $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been approved and is now "Pending Admin Approval For PO".');
                        $em->persist($newUserNotif);

                        $em->flush();

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

                        $canvass->setStatus('Approved');

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($canvass->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('canvass');
                        $newUserNotif->setRefId($canvass->getId());
                        $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been approved and is now in Purchase Order.');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($canvass->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('canvass');
                        $newUserNotif->setRefId($canvass->getId());
                        $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been approved and is now in Purchase Order.');
                        $em->persist($newUserNotif);

                        $em->flush();

                        $this->createPurchaseOrder($canvass);
                    }

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

                    $canvass->setStatus('Approved');

                    $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                    $newUserNotif = new UserNotifEntity();
                    $newUserNotif->setUser($canvass->getMaterialRequisition()->getUser());
                    $newUserNotif->setBatchNo($notifBatchNo);
                    $newUserNotif->setRef('canvass');
                    $newUserNotif->setRefId($canvass->getId());
                    $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been approved and is now in Purchase Order.');
                    $em->persist($newUserNotif);

                    $newUserNotif = new UserNotifEntity();
                    $newUserNotif->setUser($canvass->getUserWhoSent());
                    $newUserNotif->setBatchNo($notifBatchNo);
                    $newUserNotif->setRef('canvass');
                    $newUserNotif->setRefId($canvass->getId());
                    $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been approved and is now in Purchase Order.');
                    $em->persist($newUserNotif);

                    $em->flush();

                    $this->createPurchaseOrder($canvass);
                }

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

            } else {

                $canvass->setStatus('Supplier Canvassing');

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

                //$em->flush();

                foreach($canvass->getCanvassStatuses() as $canvassStatus) {
                    if($canvassStatus->getBatchNo() === $canvass->getApprovalBatchNo() && $canvassStatus->getApprovalDescription() === 'Pending'){
                        $canvassStatus->setApprovalDescription('Cancelled');
                    }
                }

                $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                $newUserNotif = new UserNotifEntity();
                $newUserNotif->setUser($canvass->getMaterialRequisition()->getUser());
                $newUserNotif->setBatchNo($notifBatchNo);
                $newUserNotif->setRef('canvass');
                $newUserNotif->setRefId($canvass->getId());
                $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been rejected and is for supplier canvassing again.');
                $em->persist($newUserNotif);

                $newUserNotif = new UserNotifEntity();
                $newUserNotif->setUser($canvass->getUserWhoSent());
                $newUserNotif->setBatchNo($notifBatchNo);
                $newUserNotif->setRef('canvass');
                $newUserNotif->setRefId($canvass->getId());
                $newUserNotif->setDetail('Canvass No. ' . $canvass->getCanvassNo() . ' has been rejected and is for supplier canvassing again.');
                $em->persist($newUserNotif);

                $em->flush();

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

            return $this->redirect($this->generateUrl('material_requisition_canvass_view', array(
                'canvass_id' => $canvass_id
            )), 302);

        } else {

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

    /**
     * @Route("/canvass/dashboard_data", name="material_requisition_canvass_dashboard_data")
     */
    public function canvass_dashboard_dataAction() {

        $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 Canvass'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {
            $result['success'] = true;
            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/canvass_dashboard_data.html.twig', array(
                'canvasses' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:CanvassEntity')->dashboardData($this->get('session')->get('userData'))
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/ajax_list", name="material_requisition_canvass_item_ajax_list")
     */
    public function canvass_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:CanvassItemEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/form", name="material_requisition_canvass_item_supplier_form")
     */
    public function canvass_item_supplier_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 Canvass Add Supplier'))) $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();
            $canvassItem_id = $request->query->get('canvassItem_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find(base64_decode($canvassItem_id));
            $canvassItemSupplier_obj = $em->getRepository('RxConnexionBundle:CanvassItemSupplierEntity')->find(base64_decode($id));
            $canvassItemSupplier = new CanvassItemSupplierEntity($canvassItemSupplier_obj);

            $formOptions = array('action' => $action);
            $form = $this->createForm(new CanvassItemSupplierForm($canvassItem, $canvassItemSupplier_obj), $canvassItemSupplier, $formOptions);

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/form_action", name="material_requisition_canvass_item_supplier_form_action")
     */
    public function canvass_item_supplier_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 Canvass Add Supplier'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

            $em = $this->getDoctrine()->getManager();
            $canvassItemSupplier_form = $request->get('canvassItemSupplier');

            $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find($canvassItemSupplier_form['canvassItem_id']);
            $canvassItemSupplier_obj = $em->getRepository('RxConnexionBundle:CanvassItemSupplierEntity')->find($canvassItemSupplier_form['id']);
            $canvassItemSupplier = new CanvassItemSupplierEntity($canvassItemSupplier_obj);

            $formOptions = array('action' => $canvassItemSupplier_form['action']);
            $form = $this->createForm(new CanvassItemSupplierForm($canvassItem, $canvassItemSupplier_obj), $canvassItemSupplier, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:CanvassItemSupplierEntity')->validate($canvassItemSupplier_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $supplier = $em->getRepository('RxConnexionBundle:SupplierEntity')->find($canvassItemSupplier_form['supplier_id']);

                            $canvassItemSupplier->setSupplier($supplier);
                            $canvassItemSupplier->setCanvassItem($canvassItem);
                            $em->persist($canvassItemSupplier);
                            $em->flush();

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

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

                        break;

                    case 'u': // update

                        $canvassItemSupplier_obj = $em->getRepository('RxConnexionBundle:CanvassItemSupplierEntity')->find($canvassItemSupplier_form['id']);

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

                        $supplier = $em->getRepository('RxConnexionBundle:SupplierEntity')->find($canvassItemSupplier_form['supplier_id']);

                        $canvassItemSupplier_obj->setSupplier($supplier);
                        $canvassItemSupplier_obj->setPrice($canvassItemSupplier_form['price']);
                        $canvassItemSupplier_obj->setNote($canvassItemSupplier_form['note']);

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

                        $em->flush();

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

                        break;

                    case 'd': // delete

                        $canvassItemSupplier = $em->getRepository('RxConnexionBundle:CanvassItemSupplierEntity')->find($canvassItemSupplier_form['id']);
                        $em->remove($canvassItemSupplier);

//                        $newAT = new AuditTrailEntity();
//                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                        $newAT->entity = $canvassItemSupplier;
//                        $newAT->setRefTable('canvass_item_supplier');
//                        $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("/canvass/item/supplier/form_multiple", name="material_requisition_canvass_item_supplier_form_multiple")
     */
    public function canvass_item_supplier_form_multipleAction(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 Canvass Add Supplier'))) $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();
            $canvassItem_id = $request->query->get('canvassItem_id');

            $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find(base64_decode($canvassItem_id));
            $item = $canvassItem->getMaterialRequisitionItem()->getItem();

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/canvass_item_supplier_form_multiple.html.twig', array(
                'canvassItem' => $canvassItem,
                'item' => $item,
                'supplierHistories' => $em->getRepository('RxConnexionBundle:ItemEntity')->supplierHistoryForCanvassing($item->getId())
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/do_add", name="material_requisition_canvass_item_supplier_do_add")
     */
    public function canvass_item_supplier_do_addAction(Request $request) {

        $result['success'] = false;
        $result['errorMessages'] = '';

        $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 Canvass Add Supplier'))) $result['errorMessages'] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $canvassItem_id = $request->get('canvassItem_id');
        $supplier_id = $request->get('supplier_id');
        $price = $request->get('price');
        // $qty = $request->get('qty');

        $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find($canvassItem_id);

        if(!is_numeric($price) || $price <= 0) {
            $result['errorMessages'] = 'Please enter price.';
        }
        if($canvassItem->getHasSupplierById($supplier_id)) {
            $result['errorMessages'] = 'Supplier already exist.';
        }

        if(empty($result['errorMessages'])) {

            $currency_id = $request->get('currency_id');
            $paymentMode = $request->get('paymentMode');
            $term = $request->get('term');
            $wTaxRate_id = $request->get('wTaxRate_id');
            $note = $request->get('note');

            if($currency_id > 0) {
                $currency = $em->getRepository('RxConnexionBundle:CurrencyEntity')->find($currency_id);
            } else {
                $currency = null;
            }

            if($wTaxRate_id > 0) {
                $wTaxRate = $em->getRepository('RxConnexionBundle:WithholdingTaxRateEntity')->find($wTaxRate_id);
            } else {
                $wTaxRate = null;
            }

            $canvassItems = $canvassItem->getCanvass()->getCanvassItems();
            foreach($canvassItems as $ci) {
                $canvassItemSuppliers = $ci->getCanvassItemSuppliers();
                if($canvassItemSuppliers->count()) {
                    foreach($canvassItemSuppliers as $cis) {
                        if($cis->getSupplier()->getId() != $supplier_id) {
                            continue;
                        }
//                        $cis->setCurrency($currency);
//                        $cis->setWithholdingTaxRate($wTaxRate);
                        $cis->setPaymentMode($paymentMode);
                        $cis->setTerm($term);
                    }
                }
            }

            $canvassItemSupplier = new CanvassItemSupplierEntity();
            $canvassItemSupplier->setCanvassItem($canvassItem);
            $canvassItemSupplier->setSupplier($em->getReference('RxConnexionBundle:SupplierEntity', $supplier_id));
            $canvassItemSupplier->setCurrency($currency);
//            $canvassItemSupplier->setWithholdingTaxRate($wTaxRate);
            $canvassItemSupplier->setPaymentMode($paymentMode);
            $canvassItemSupplier->setTerm($term);
            $canvassItemSupplier->setCanvassDate(date('m/d/Y'));
            $canvassItemSupplier->setPrice($price);
            // $canvassItemSupplier->setQuantity(is_numeric($qty) ? $qty : 0);
            $canvassItemSupplier->setNote($note);
            $em->persist($canvassItemSupplier);
            $em->flush();

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/select", name="material_requisition_canvass_item_supplier_select")
     */
    public function canvass_item_supplier_selectAction(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 Canvass Select Supplier'))) $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();
            $canvassItem_id = $request->query->get('canvassItem_id');
            $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find(base64_decode($canvassItem_id));
            $item = $canvassItem->getMaterialRequisitionItem()->getItem();

            $title = 'Select Supplier';

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/canvass_item_supplier_select.html.twig', array(
                'page_title' => $title,
                'canvassItem' => $canvassItem,
                'item' => $item,
                'supplierHistories' => $em->getRepository('RxConnexionBundle:ItemEntity')->supplierHistoryForCanvassing($item->getId()),
//                'currencies' => $em->getRepository('RxConnexionBundle:CurrencyEntity')->findAll(),
//                'wTaxRates' => $em->getRepository('RxConnexionBundle:WithholdingTaxRateEntity')->findBy(array(), array('description' => 'asc'))
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/select_action", name="material_requisition_canvass_item_supplier_select_action")
     */
    public function canvass_item_supplier_select_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 Canvass Select Supplier'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

        $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find(base64_decode($request->get('canvassItem_id')));
        $canvassItemSuppliers = $request->get('canvassItemSuppliers');

        /*foreach($canvassItemSuppliers as $canvassItemSupplier_form) {
            if(isSet($canvassItemSupplier_form['isSelected'])) {
                $totalQuantity += str_replace(',' ,'', $canvassItemSupplier_form['quantity']);
            }
        }*/

        /*        if($totalQuantity > $canvassItem->getQuantityForCanvassing())
                    $result['errorMessages'][] = 'Total quantity is greater than the quantity for canvassing.';*/

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

            $result['success'] = true;

            /*  $canvassItem->setQuantityCanvassed($totalQuantity);*/

            foreach($canvassItemSuppliers as $canvassItemSupplier_form) {
                foreach($canvassItem->getCanvassItemSuppliers() as $canvassItemSupplier) {
                    if($canvassItemSupplier_form['id'] === $canvassItemSupplier->getId()) {

                        $supplier = $canvassItemSupplier->getSupplier();

//                        if($canvassItemSupplier_form['currency'] > 0) {
//                            $currency = $em->getRepository('RxConnexionBundle:CurrencyEntity')->find($canvassItemSupplier_form['currency']);
//                        } else {
//                            $currency = null;
//                        }
//
//                        if($canvassItemSupplier_form['wTaxRate'] > 0) {
//                            $wTaxRate = $em->getRepository('RxConnexionBundle:WithholdingTaxRateEntity')->find($canvassItemSupplier_form['wTaxRate']);
//                        } else {
//                            $wTaxRate = null;
//                        }

                        foreach($canvassItem->getCanvass()->getCanvassItems() as $ci) {
                            $ciss = $ci->getCanvassItemSuppliers();
                            if(!$ciss->count()) {
                                continue;
                            }
                            foreach($ciss as $cis) {
                                if($cis->getId() === $canvassItemSupplier->getId() || $cis->getSupplier() !== $supplier) {
                                    continue;
                                }
//                                $cis->setCurrency($currency);
//                                $cis->setWithholdingTaxRate($wTaxRate);
                                $cis->setPaymentMode($canvassItemSupplier_form['paymentMode']);
                                $cis->setTerm($canvassItemSupplier_form['term']);
                            }
                        }

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

                        //$canvassItemSupplier->setIsSelected(isSet($canvassItemSupplier_form['isSelected']));
                        $canvassItemSupplier->setIsSelected($canvassItemSupplier_form['quantity'] > 0);
                        $canvassItemSupplier->setQuantity($canvassItemSupplier_form['quantity']);
                        $canvassItemSupplier->setPrice($canvassItemSupplier_form['price']);
//                        $canvassItemSupplier->setCurrency($currency);
//                        $canvassItemSupplier->setWithholdingTaxRate($wTaxRate);
                        $canvassItemSupplier->setPaymentMode($canvassItemSupplier_form['paymentMode']);
                        $canvassItemSupplier->setTerm($canvassItemSupplier_form['term']);
                        //$canvassItemSupplier->setDownPayment($canvassItemSupplier_form['downPayment']);
                        /*$canvassItemSupplier->setItemUnitMeasurement($em->getReference('RxConnexionBundle:ItemUnitMeasurementEntity' ,$canvassItemSupplier_form['unitOfMeasurement']));*/
                        //$canvassItemSupplier->setItemUnitMeasurement($canvassItem->getMaterialRequisitionItem()->getItem()->getSmallestItemUnitMeasurement());

                        /*$itemSupplier = $canvassItemSupplier->getSupplier()->getItemSupplier($canvassItem->getMaterialRequisitionItem()->getItem()->getId());

                        if(!is_null($itemSupplier)){
                            $itemSupplier->setPrice($canvassItemSupplier_form['price']);
                        }*/

                        $canvassItemSupplier->getCanvassItem()->updateQuantityCanvassed();

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

                        //$em->flush();
                    }
                }
            }

            $em->flush();

            $canvassItem->getMaterialRequisitionItem()->updateQuantityCanvassed();

            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/details", name="material_requisition_canvass_item_supplier_details")
     */
    public function canvass_item_supplier_detailsAction(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 Canvass Select Supplier'))) $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();
            $canvassItem_id = $request->query->get('canvassItem_id');
            $canvassItem = $em->getRepository('RxConnexionBundle:CanvassItemEntity')->find(base64_decode($canvassItem_id));

            $title = 'Details';

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/canvass_item_supplier_details.html.twig', array(
                'page_title' => $title,
                'canvassItem' => $canvassItem
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/item/supplier/remove", name="material_requisition_canvass_item_supplier_remove")
     */
    public function canvass_item_supplier_removeAction(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 Canvass Select Supplier'))) $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();
            $canvassItemSupplier_id = $request->get('canvassItemSupplier_id');
            $canvassItemSupplier = $em->getRepository('RxConnexionBundle:CanvassItemSupplierEntity')->find(base64_decode($canvassItemSupplier_id));
            $em->remove($canvassItemSupplier);

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

            if($canvassItemSupplier->getIsSelected()) {
                $canvassItemSupplier->getCanvassItem()->setQuantityCanvassed($canvassItemSupplier->getCanvassItem()->getQuantityCanvassed() - $canvassItemSupplier->getQuantity());
                $canvassItemSupplier->getCanvassItem()->getMaterialRequisitionItem()->updateQuantityCanvassed();
            }

            $em->flush();
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/void", name="material_requisition_canvass_void")
     */
    public function canvass_voidAction(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 Canvass Void'))) $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();
            $canvass_id = $request->query->get('canvass_id');

            $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/canvass_void.html.twig', array(
                'page_title' => 'Void Items',
                'canvass_id' => $canvass_id,
                'canvass' => $canvass
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/add_quantity", name="material_requisition_canvass_add_quantity")
     */
    public function canvass_add_quantityAction(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 Canvass Void'))) $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();
            $canvass_id = $request->query->get('canvass_id');

            $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/canvass_add_quantity.html.twig', array(
                'page_title' => 'Add Item Quantity',
                'canvass_id' => $canvass_id,
                'canvass' => $canvass
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/add_quantity_action", name="material_requisition_canvass_add_quantity_action")
     */
    public function canvass_add_quantity_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 Canvass Add Quantity'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $canvass_id = $request->get('canvass_id');
        $canvassItems_form = $request->get('canvassItems');
        $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));


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

            foreach($canvassItems_form as $canvassItem_form) {
                foreach($canvass->getCanvassItems() as $canvassItem) {
                    if($canvassItem_form['id'] === $canvassItem->getId()) {
                        $canvassItem->setQuantityAdded($canvassItem_form['addedQuantity']);
                        $em->flush();
                    }
                }
            }

            $em->refresh($canvass);
            $canvass->doAddQuantity();
            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/void_action", name="material_requisition_canvass_void_action")
     */
    public function canvass_void_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 Canvass Void'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $canvass_id = $request->get('canvass_id');
        $canvassItems_form = $request->get('canvassItems');
        $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

        foreach($canvassItems_form as $canvassItem_form) {

            foreach($canvass->getCanvassItems() as $canvassItem) {
                if($canvassItem_form['id'] === $canvassItem->getId() && $canvassItem->getQuantityCanvassed() + str_replace(',', '', $canvassItem_form['quantityVoided']) > $canvassItem->getQuantity() + $canvassItem->getQuantityAdded()) {
                    $result['errorMessages'][] = 'Item ' . $canvassItem->getMaterialRequisitionItem()->getItem()->getDescription() . ' already exceed its voidable quantity.';
                }
            }
        }

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

            foreach($canvassItems_form as $canvassItem_form) {
                foreach($canvass->getCanvassItems() as $canvassItem) {
                    if($canvassItem_form['id'] === $canvassItem->getId()) {

                        $canvassItem->setQuantityVoided($canvassItem_form['quantityVoided']);
                        $em->flush();
                    }
                }
            }

            $em->refresh($canvass);
            $canvass->doVoid();
            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/cancel", name="material_requisition_purchase_order_cancel")
     */
    public function purchase_order_cancelAction(Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $purchase_order_id = $request->get('purchaseOrder_id');
        $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchase_order_id));

        $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 Purchase Order Cancel'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!$purchaseOrder->getIsCancellable()) {
            $result['errorMessages'][] = 'Record is not cancellable, P.O.(s) were already sent.';
        }

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

            $canvass = $purchaseOrder->getCanvass();
            $purchaseOrder->setStatus('Cancelled');
            $purchaseOrder->getCanvass()->setStatus('Supplier Canvassing');

            foreach($purchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                $purchaseOrderItem->getMaterialRequisitionItem()->updateQuantityPo();
            }

//            $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

//            $newUserNotif = new UserNotifEntity();
//            $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
//            $newUserNotif->setBatchNo($notifBatchNo);
//            $newUserNotif->setRef('purchase_order');
//            $newUserNotif->setRefId($purchaseOrder->getId());
//            $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been cancelled of Canvass No. ' . $canvass->getCanvassNo() . ' which is now back to supplier canvassing.');
//            $em->persist($newUserNotif);
//
//            $newUserNotif = new UserNotifEntity();
//            $newUserNotif->setUser($canvass->getUserWhoSent());
//            $newUserNotif->setBatchNo($notifBatchNo);
//            $newUserNotif->setRef('purchase_order');
//            $newUserNotif->setRefId($purchaseOrder->getId());
//            $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been cancelled of Canvass No. ' . $canvass->getCanvassNo() . ' which is now back to supplier canvassing.');
//            $em->persist($newUserNotif);

            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/canvass/cancel", name="material_requisition_canvass_cancel")
     */
    public function canvass_cancelAction(Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $canvass_id = $request->get('canvass_id');
        $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find(base64_decode($canvass_id));

        $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 Canvass Cancel'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!$canvass->getMaterialRequisition()->getIsCancellable())
            $result['errorMessages'][] = 'Request is not cancellable.';

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

            $canvass->getMaterialRequisition()->doCancel();
            $em->flush();

            $em->refresh($canvass);
            $canvass->getMaterialRequisition()->updateQuantityCanvassed();
            $canvass->getMaterialRequisition()->updateQuantityVoided();
            $em->flush();

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

        return new JsonResponse($result);
    }

    private function createPurchaseOrder(CanvassEntity $canvass) {
        $em = $this->getDoctrine()->getManager();
        $canvass_id = $canvass->getId();
        $em->clear();
        $canvass = $em->getRepository('RxConnexionBundle:CanvassEntity')->find($canvass_id);
        $materialRequisition = $canvass->getMaterialRequisition();

        // Create new canvass for remaining quantities for canvassing
        // $this->createCanvass($materialRequisition);


        //refresh not working


//        $nextBatchNo = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->getNextBatchNo();
        $nextPurchaseOrderNo = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->getNextPurchaseOrderNo();
        $mrUser = $materialRequisition->getAccountUser();
        $cvsUser = $canvass->getUserWhoSent();

//        $vatRate = $em->getRepository('RxConnexionBundle:SysParamEntity')->getValueByDesc('Input Vat Percentage');
//        $statusApprovalPendingOperationsDivisionManagerSignatureForPo = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Operations Division Manager Signature For PO'));
//        $statusApprovalPendingFinanceOfficerSignatureForPo = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Finance Officer Signature For PO'));
//        $statusApprovalPendingFinalAdminApprovalForPo = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Final Admin Approval For PO'));

        foreach($canvass->getSelectedSuppliers() as $selectedSupplier) {

            $newPurchaseOrder = new PurchaseOrderEntity();
            $newPurchaseOrder->setCanvass($canvass);
            $newPurchaseOrder->setMaterialRequisition($canvass->getMaterialRequisition());
            $newPurchaseOrder->setSupplier($selectedSupplier['supplier']);
//            $newPurchaseOrder->setCurrency($selectedSupplier['currency']);
//            $newPurchaseOrder->setWithholdingTaxRate($selectedSupplier['withholdingTaxRate']);
//            $newPurchaseOrder->setWhTaxRate($selectedSupplier['withholdingTaxRate'] ? $selectedSupplier['withholdingTaxRate']->getRate() : null);
//            $newPurchaseOrder->setWhTaxLessVat($selectedSupplier['withholdingTaxRate'] ? $selectedSupplier['withholdingTaxRate']->getIsLessVat() : null);
//            $newPurchaseOrder->setVatRate($vatRate);
            $newPurchaseOrder->setPaymentMode($selectedSupplier['paymentMode']);
            $newPurchaseOrder->setTerm($selectedSupplier['term']);
            $newPurchaseOrder->setBatchNo(null);
            $em->persist($newPurchaseOrder);
            // $em->flush();
            /*
            $statusApproval = '';

            if($statusApprovalPendingOperationsDivisionManagerSignatureForPo && $statusApprovalPendingOperationsDivisionManagerSignatureForPo->getLevel() > 0) {

                $statusApproval = 'Pending Operations Division Manager Signature For PO';
                $newPurchaseOrder->setStatus($statusApproval);
                $newPurchaseOrder->setApprovalBatchNo($newPurchaseOrder->getApprovalBatchNo() + 1);

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

                    $newPurchaseOrderStatus = new PurchaseOrderStatusEntity();
                    $newPurchaseOrderStatus->setPurchaseOrder($newPurchaseOrder);
                    $newPurchaseOrderStatus->setStatus($statusApproval);
                    $newPurchaseOrderStatus->setBatchNo($newPurchaseOrder->getApprovalBatchNo());
                    $em->persist($newPurchaseOrderStatus);
                }

            } else if($statusApprovalPendingFinanceOfficerSignatureForPo && $statusApprovalPendingFinanceOfficerSignatureForPo->getLevel() > 0) {

                $statusApproval = 'Pending Finance Officer Signature For PO';
                $newPurchaseOrder->setStatus($statusApproval);
                $newPurchaseOrder->setApprovalBatchNo($newPurchaseOrder->getApprovalBatchNo() + 1);

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

                    $newPurchaseOrderStatus = new PurchaseOrderStatusEntity();
                    $newPurchaseOrderStatus->setPurchaseOrder($newPurchaseOrder);
                    $newPurchaseOrderStatus->setStatus($statusApproval);
                    $newPurchaseOrderStatus->setBatchNo($newPurchaseOrder->getApprovalBatchNo());
                    $em->persist($newPurchaseOrderStatus);
                }
            } else if($statusApprovalPendingFinalAdminApprovalForPo && $statusApprovalPendingFinalAdminApprovalForPo->getLevel() > 0) {

                $statusApproval = 'Pending Final Admin Approval For PO';
                $newPurchaseOrder->setStatus($statusApproval);
                $newPurchaseOrder->setApprovalBatchNo($newPurchaseOrder->getApprovalBatchNo() + 1);

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

                    $newPurchaseOrderStatus = new PurchaseOrderStatusEntity();
                    $newPurchaseOrderStatus->setPurchaseOrder($newPurchaseOrder);
                    $newPurchaseOrderStatus->setStatus($statusApproval);
                    $newPurchaseOrderStatus->setBatchNo($newPurchaseOrder->getApprovalBatchNo());
                    $em->persist($newPurchaseOrderStatus);
                }

            } else {
                $newPurchaseOrder->setStatus('Approved');
            }

            foreach($canvass->getCanvassItems() as $canvassItem) {
                if($canvassItem->getCanvassItemSuppliers()) {
                    foreach($canvassItem->getCanvassItemSuppliers() as $canvassItemSupplier) {
                        if($canvassItemSupplier->getIsSelected() && $canvassItemSupplier->getSupplier() === $selectedSupplier['supplier']) {
                            $newPurchaseOrderItem = new PurchaseOrderItemEntity();
                            $newPurchaseOrderItem->setPurchaseOrder($newPurchaseOrder);
                            $newPurchaseOrderItem->setMaterialRequisitionItem($canvassItem->getMaterialRequisitionItem());
                            $newPurchaseOrderItem->setCanvassItemSupplier($canvassItemSupplier);
                            $newPurchaseOrderItem->setQuantity($canvassItemSupplier->getQuantity());
                            $newPurchaseOrderItem->setQuantityWithPo($canvassItemSupplier->getQuantity());
                            // $newPurchaseOrderItem->setItemUnitMeasurement($canvassItemSupplier->getItemUnitMeasurement());
                            $newPurchaseOrderItem->setPrice($canvassItemSupplier->getPrice());
                            $newPurchaseOrderItem->setDownPayment($canvassItemSupplier->getDownPayment());
                            $em->persist($newPurchaseOrderItem);
                        }
                    }
                }
            }

            $em->flush();

            $em->refresh($newPurchaseOrder);

            $newPurchaseOrderBreakdown = new PurchaseOrderBreakdownEntity();
            $newPurchaseOrderBreakdown->setPurchaseOrder($newPurchaseOrder);
            $newPurchaseOrderBreakdown->setPurchaseOrderNo($nextPurchaseOrderNo);
            $newPurchaseOrderBreakdown->setPoDate(date('m/d/Y'));
            $em->persist($newPurchaseOrderBreakdown);
            $em->flush();

            $newPurchaseOrderBreakdown->setPoNo('PO-' . $materialRequisition->getBranch()->getCodeToUpper() . '-' . $materialRequisition->getDepartment()->getCodeToUpper() . '-' . sprintf('%06d', $newPurchaseOrderBreakdown->getId()));

            foreach($newPurchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {

                $newPurchaseOrderBreakdownItem = new PurchaseOrderBreakdownItemEntity;
                $newPurchaseOrderBreakdownItem->setPurchaseOrderBreakdown($newPurchaseOrderBreakdown);
                $newPurchaseOrderBreakdownItem->setPurchaseOrderItem($purchaseOrderItem);
                $newPurchaseOrderBreakdownItem->setQuantity($purchaseOrderItem->getQuantity());
                // $newPurchaseOrderBreakdownItem->setItemUnitMeasurement($purchaseOrderItem->getItemUnitMeasurement());
                $em->persist($newPurchaseOrderBreakdownItem);
            }

            $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

            $newUserNotif = new UserNotifEntity();
            $newUserNotif->setUser($mrUser);
            $newUserNotif->setBatchNo($notifBatchNo);
            $newUserNotif->setRef('canvass');
            $newUserNotif->setRefId($canvass->getId());
            $newUserNotif->setDetail('Purchase Order Batch No. ' . $newPurchaseOrder->getBatchNo() . (!empty($statusApproval) ? ' (' . $statusApproval . ')' : '') . ' has been created for Canvass No. ' . $canvass->getCanvassNo() . '.');
            $em->persist($newUserNotif);

            $newUserNotif = new UserNotifEntity();
            $newUserNotif->setUser($cvsUser);
            $newUserNotif->setBatchNo($notifBatchNo);
            $newUserNotif->setRef('canvass');
            $newUserNotif->setRefId($canvass->getId());
            $newUserNotif->setDetail('Purchase Order Batch No. ' . $newPurchaseOrder->getBatchNo() . (!empty($statusApproval) ? ' (' . $statusApproval . ')' : '') . ' has been created for Canvass No. ' . $canvass->getCanvassNo() . '.');
            $em->persist($newUserNotif);
             */


            foreach($canvass->getCanvassItems() as $canvassItem) {
                if($canvassItem->getCanvassItemSuppliers()) {
                    foreach($canvassItem->getCanvassItemSuppliers() as $canvassItemSupplier) {
                        if($canvassItemSupplier->getIsSelected() && $canvassItemSupplier->getSupplier() === $selectedSupplier['supplier']) {
                            $newPurchaseOrderItem = new PurchaseOrderItemEntity();
                            $newPurchaseOrderItem->setPurchaseOrder($newPurchaseOrder);
                            $newPurchaseOrderItem->setMaterialRequisitionItem($canvassItem->getMaterialRequisitionItem());
                            $newPurchaseOrderItem->setCanvassItemSupplier($canvassItemSupplier);
                            $newPurchaseOrderItem->setQuantity($canvassItemSupplier->getQuantity());
                            $newPurchaseOrderItem->setQuantityWithPo($canvassItemSupplier->getQuantity());
                            // $newPurchaseOrderItem->setItemUnitMeasurement($canvassItemSupplier->getItemUnitMeasurement());
                            $newPurchaseOrderItem->setPrice($canvassItemSupplier->getPrice());
                            $newPurchaseOrderItem->setDownPayment($canvassItemSupplier->getDownPayment());
                            $em->persist($newPurchaseOrderItem);
                        }
                    }
                }
            }

            $em->flush();

            $em->refresh($newPurchaseOrder);

            $newPurchaseOrderBreakdown = new PurchaseOrderBreakdownEntity();
            $newPurchaseOrderBreakdown->setPurchaseOrder($newPurchaseOrder);
            $newPurchaseOrderBreakdown->setPurchaseOrderNo($nextPurchaseOrderNo);
            $newPurchaseOrderBreakdown->setPoDate(date('m/d/Y'));
            $em->persist($newPurchaseOrderBreakdown);
            $em->flush();

            $newPurchaseOrderBreakdown->setPoNo('PO-' . $newPurchaseOrder->getSupplier()->getCode() . '-' . sprintf('%06d', $newPurchaseOrderBreakdown->getId()));

            foreach($newPurchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {

                $newPurchaseOrderBreakdownItem = new PurchaseOrderBreakdownItemEntity;
                $newPurchaseOrderBreakdownItem->setPurchaseOrderBreakdown($newPurchaseOrderBreakdown);
                $newPurchaseOrderBreakdownItem->setPurchaseOrderItem($purchaseOrderItem);
                $newPurchaseOrderBreakdownItem->setQuantity($purchaseOrderItem->getQuantity());
                // $newPurchaseOrderBreakdownItem->setItemUnitMeasurement($purchaseOrderItem->getItemUnitMeasurement());
                $em->persist($newPurchaseOrderBreakdownItem);
            }
            $em->flush();

            $em->refresh($newPurchaseOrder);

            foreach($newPurchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                // $purchaseOrderItem->updateQuantityWithPo();
                $purchaseOrderItem->getMaterialRequisitionItem()->updateQuantityPo();
            }

            $em->flush();

//            $nextPurchaseOrderNo++;
        }
    }

    /**
     * @Route(
     *      "/purchase_order/index",
     *      name = "material_requisition_purchase_order"
     * )
     */
    public function purchase_orderAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Purchase Order'))) return $authService->redirectToHome();
	    $userData = $this->get('session')->get('userData');
	    $em = $this->getDoctrine()->getManager();
        return $this->render('@RxConnexion/MaterialRequisition/purchase_order.html.twig', array(
            'title' => 'Purchase Order',
            'page_title' => 'Purchase Order',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseOrder.js?v=1.0.4'),
	        'branches' => $userData['type'] == 'Super Admin'
		        ? $em->getRepository(HealthFacilityEntity::class)->findAllNotDeleted()
		        : $em->getRepository(HealthFacilityEntity::class)->findAllByIds($userData['branches'], true),
            'status' => $request->query->get('status')
        ));
    }

    /**
     * @Route("/purchase_order/ajax_list", name="material_requisition_purchase_order_ajax_list")
     */
    public function purchase_order_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:PurchaseOrderEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/purchase_order/view/{purchaseOrder_id}",
     *      name = "material_requisition_purchase_order_view"
     * )
     */
    public function purchase_order_viewAction($purchaseOrder_id) {

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

        $em = $this->getDoctrine()->getManager();
        $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));
//        $canApproveByUser = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->countForApprovalByUser($this->get('session')->get('userData'), $purchaseOrder->getStatus(), $purchaseOrder->getId()) > 0;

        return $this->render('@RxConnexion/MaterialRequisition/purchase_order_view.html.twig', array(
            'title' => 'Purchase Order',
            'page_title' => 'Purchase Order',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseOrder_view.js?v=1.0.2'),
            'purchaseOrder_id' => $purchaseOrder_id,
            'purchaseOrder' => $purchaseOrder,
//            'canApproveByUser' => $canApproveByUser,
//            'statusApproval' => $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => $purchaseOrder->getStatus()))
        ));
    }

    /**
     * @Route("/purchase_order/send", name="material_requisition_purchase_order_send")
     */
    public function purchase_order_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 Purchase Order Send'))) $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();
            $purchaseOrder_id = $request->get('purchaseOrder_id');
            $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));

            foreach($purchaseOrder->getPurchaseOrderBreakdowns() as $purchaseOrderBreakdown) {
                if($purchaseOrderBreakdown->getStatus() === 'New') {

                    $purchaseOrderBreakdown->setStatus('Sent');

                    $purchaseInvoice = new PurchaseInvoiceEntity();
                    $purchaseInvoice->setPurchaseOrderBreakDown($purchaseOrderBreakdown);
                    $em->persist($purchaseInvoice);
                    $em->flush();

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

//                    $userTypes = $em->getRepository('RxConnexionBundle:UserAccessEntity')->findDistinctTypeByDescription('Admin Purchase Invoice');
//                    foreach($userTypes as $userType){
//                        $users = $em->getRepository('RxConnexionBundle:UserEntity')->findBy(array('type' => $userType));
//                        foreach($users as $user){
//                            $newUserNotif = new UserNotifEntity();
//                            $newUserNotif->setUser($user);
//                            $newUserNotif->setBatchNo(null);
//                            $newUserNotif->setRef('material_requisition_purchase_invoice');
//                            $newUserNotif->setRefId($purchaseInvoice->getId());
//                            $newUserNotif->setDetail('New Purchase Invoice has been created for P.O. # ' . $purchaseInvoice->getPurchaseOrderBreakdown()->getPoNo());
//                            $em->persist($newUserNotif);
//                        }
//                    }
                }
            }

            $purchaseOrder->updateStatus();
            $em->flush();

            $this->get('session')->getFlashBag()->set('success_messages', 'P.O. Successfully Sent.');
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/purchase_order/status_approval",
     *      name = "material_requisition_purchase_order_status_approval"
     * )
     */
    public function purchase_order_status_approvalAction(Request $request) {

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

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

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

            $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));

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

            $statusApprovalPendingOperationsDivisionManagerSignatureForPo = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Operations Division Manager Signature For PO'));
            $statusApprovalPendingFinanceOfficerSignatureForPo = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Finance Officer Signature For PO'));
            $statusApprovalPendingFinalAdminApprovalForPo = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Pending Final Admin Approval For PO'));

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

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

                //$em->flush();

                $approvalCount = 0;

                foreach($purchaseOrder->getPurchaseOrderStatuses() as $purchaseOrderStatus) {
                    if($purchaseOrderStatus->getBatchNo() === $purchaseOrder->getApprovalBatchNo() && $purchaseOrderStatus->getApprovalDescription() === 'Approved'){
                        $approvalCount++;
                    }
                }

                if($purchaseOrder->getStatus() === 'Pending Operations Division Manager Signature For PO') {

                    if($statusApprovalPendingOperationsDivisionManagerSignatureForPo->getLevel() === $approvalCount && $statusApprovalPendingFinanceOfficerSignatureForPo && $statusApprovalPendingFinanceOfficerSignatureForPo->getLevel() > 0) {

                        $purchaseOrder->setStatus('Pending Finance Officer Signature For PO');
                        $purchaseOrder->setApprovalBatchNo($purchaseOrder->getApprovalBatchNo() + 1);

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

                            $newPurchaseOrderStatus = new PurchaseOrderStatusEntity();
                            $newPurchaseOrderStatus->setPurchaseOrder($purchaseOrder);
                            $newPurchaseOrderStatus->setStatus('Pending Finance Officer Signature For PO');
                            $newPurchaseOrderStatus->setBatchNo($purchaseOrder->getApprovalBatchNo());
                            $em->persist($newPurchaseOrderStatus);
                        }

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now "Pending Finance Officer Signature For PO".');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now "Pending Finance Officer Signature For PO".');
                        $em->persist($newUserNotif);

                        $em->flush();

                    } else if($statusApprovalPendingOperationsDivisionManagerSignatureForPo->getLevel() === $approvalCount && $statusApprovalPendingFinalAdminApprovalForPo && $statusApprovalPendingFinalAdminApprovalForPo->getLevel() > 0) {

                        $purchaseOrder->setStatus('Pending Final Admin Approval For PO');
                        $purchaseOrder->setApprovalBatchNo($purchaseOrder->getApprovalBatchNo() + 1);

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

                            $newPurchaseOrderStatus = new PurchaseOrderStatusEntity();
                            $newPurchaseOrderStatus->setPurchaseOrder($purchaseOrder);
                            $newPurchaseOrderStatus->setStatus('Pending Final Admin Approval For PO');
                            $newPurchaseOrderStatus->setBatchNo($purchaseOrder->getApprovalBatchNo());
                            $em->persist($newPurchaseOrderStatus);
                        }

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now "Pending Final Admin Approval For PO".');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now "Pending Final Admin Approval For PO".');
                        $em->persist($newUserNotif);

                        $em->flush();

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

                        $purchaseOrder->setStatus('Approved');

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now ready for sending.');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now ready for sending.');
                        $em->persist($newUserNotif);

                        $em->flush();
                    }

                } else if($purchaseOrder->getStatus() === 'Pending Finance Officer Signature For PO') {

                    if($statusApprovalPendingFinanceOfficerSignatureForPo->getLevel() === $approvalCount && $statusApprovalPendingFinalAdminApprovalForPo && $statusApprovalPendingFinalAdminApprovalForPo->getLevel() > 0) {

                        $purchaseOrder->setStatus('Pending Final Admin Approval For PO');
                        $purchaseOrder->setApprovalBatchNo($purchaseOrder->getApprovalBatchNo() + 1);

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

                            $newPurchaseOrderStatus = new PurchaseOrderStatusEntity();
                            $newPurchaseOrderStatus->setPurchaseOrder($purchaseOrder);
                            $newPurchaseOrderStatus->setStatus('Pending Final Admin Approval For PO');
                            $newPurchaseOrderStatus->setBatchNo($purchaseOrder->getApprovalBatchNo());
                            $em->persist($newPurchaseOrderStatus);
                        }

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now "Pending Final Admin Approval For PO".');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now "Pending Final Admin Approval For PO".');
                        $em->persist($newUserNotif);

                        $em->flush();

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

                        $purchaseOrder->setStatus('Approved');

                        $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now ready for sending.');
                        $em->persist($newUserNotif);

                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now ready for sending.');
                        $em->persist($newUserNotif);

                        $em->flush();
                    }

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

                    $purchaseOrder->setStatus('Approved');

                    $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                    $newUserNotif = new UserNotifEntity();
                    $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                    $newUserNotif->setBatchNo($notifBatchNo);
                    $newUserNotif->setRef('purchase_order');
                    $newUserNotif->setRefId($purchaseOrder->getId());
                    $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now ready for sending.');
                    $em->persist($newUserNotif);

                    $newUserNotif = new UserNotifEntity();
                    $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                    $newUserNotif->setBatchNo($notifBatchNo);
                    $newUserNotif->setRef('purchase_order');
                    $newUserNotif->setRefId($purchaseOrder->getId());
                    $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been approved and is now ready for sending.');
                    $em->persist($newUserNotif);

                    $em->flush();
                }

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

            } else {

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

                //$em->flush();

                foreach($purchaseOrder->getPurchaseOrderStatuses() as $purchaseOrderStatus) {
                    if($purchaseOrderStatus->getBatchNo() === $purchaseOrderStatus->getApprovalBatchNo() && $purchaseOrderStatus->getApprovalDescription() === 'Pending'){
                        $purchaseOrderStatus->setApprovalDescription('Cancelled');
                    }
                }

                $notifBatchNo = $em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo();

                $newUserNotif = new UserNotifEntity();
                $newUserNotif->setUser($purchaseOrder->getMaterialRequisition()->getUser());
                $newUserNotif->setBatchNo($notifBatchNo);
                $newUserNotif->setRef('purchase_order');
                $newUserNotif->setRefId($purchaseOrder->getId());
                $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been rejected and is for supplier canvassing again.');
                $em->persist($newUserNotif);

                $newUserNotif = new UserNotifEntity();
                $newUserNotif->setUser($purchaseOrder->getCanvass()->getUserWhoSent());
                $newUserNotif->setBatchNo($notifBatchNo);
                $newUserNotif->setRef('purchase_order');
                $newUserNotif->setRefId($purchaseOrder->getId());
                $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been rejected and is for supplier canvassing again.');
                $em->persist($newUserNotif);

                // Notify finance department if rejected
                $mr = $purchaseOrder->getMaterialRequisition();
                $branchId = $mr->getBranch()->getId();
                $departmentId = $mr->getDepartment()->getId();
                $notifiedUserIds = array();
                if('Pending Final Admin Approval For PO' === $purchaseOrder->getStatus()) {
                    if($statusApprovalPendingFinanceOfficerSignatureForPo->getLevel() > 0) {
                        foreach($statusApprovalPendingFinanceOfficerSignatureForPo->getStatusApprovalUsers() as $statusApprovalUser) {
                            $userApprover = $statusApprovalUser->getUser();
                            if(in_array($userApprover->getId(), $notifiedUserIds) ||
                                !in_array($branchId, $statusApprovalUser->getBranchIds()) ||
                                !in_array($departmentId, $statusApprovalUser->getDepartmentIds())) {
                                continue;
                            }
                            $notifiedUserIds[] = $userApprover->getId();
                            $newUserNotif = new UserNotifEntity();
                            $newUserNotif->setUser($userApprover);
                            $newUserNotif->setBatchNo($notifBatchNo);
                            $newUserNotif->setRef('purchase_order');
                            $newUserNotif->setRefId($purchaseOrder->getId());
                            $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been rejected and is for supplier canvassing again.');
                            $em->persist($newUserNotif);
                        }
                    }
                    if($statusApprovalPendingOperationsDivisionManagerSignatureForPo->getLevel() > 0) {
                        foreach($statusApprovalPendingOperationsDivisionManagerSignatureForPo->getStatusApprovalUsers() as $statusApprovalUser) {
                            $userApprover = $statusApprovalUser->getUser();
                            if(in_array($userApprover->getId(), $notifiedUserIds) ||
                                !in_array($branchId, $statusApprovalUser->getBranchIds()) ||
                                !in_array($departmentId, $statusApprovalUser->getDepartmentIds())) {
                                continue;
                            }
                            $notifiedUserIds[] = $userApprover->getId();
                            $newUserNotif = new UserNotifEntity();
                            $newUserNotif->setUser($userApprover);
                            $newUserNotif->setBatchNo($notifBatchNo);
                            $newUserNotif->setRef('purchase_order');
                            $newUserNotif->setRefId($purchaseOrder->getId());
                            $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been rejected and is for supplier canvassing again.');
                            $em->persist($newUserNotif);
                        }
                    }
                } else if('Pending Finance Officer Signature For PO' === $purchaseOrder->getStatus() && $statusApprovalPendingOperationsDivisionManagerSignatureForPo->getLevel() > 0) {
                    foreach($statusApprovalPendingOperationsDivisionManagerSignatureForPo->getStatusApprovalUsers() as $statusApprovalUser) {
                        $userApprover = $statusApprovalUser->getUser();
                        if(in_array($userApprover->getId(), $notifiedUserIds) ||
                            !in_array($branchId, $statusApprovalUser->getBranchIds()) ||
                            !in_array($departmentId, $statusApprovalUser->getDepartmentIds())) {
                            continue;
                        }
                        $notifiedUserIds[] = $userApprover->getId();
                        $newUserNotif = new UserNotifEntity();
                        $newUserNotif->setUser($userApprover);
                        $newUserNotif->setBatchNo($notifBatchNo);
                        $newUserNotif->setRef('purchase_order');
                        $newUserNotif->setRefId($purchaseOrder->getId());
                        $newUserNotif->setDetail('Purchase Order Batch No. ' . $purchaseOrder->getBatchNo() . ' has been rejected and is for supplier canvassing again.');
                        $em->persist($newUserNotif);
                    }
                }

                $purchaseOrder->setStatus('Rejected');
                $purchaseOrder->getCanvass()->setStatus('Supplier Canvassing');

                $em->flush();

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

            return $this->redirect($this->generateUrl('material_requisition_purchase_order_view', array(
                'purchaseOrder_id' => $purchaseOrder_id
            )), 302);

        } else {

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

    /**
     * @Route("/purchase_order/add_quantity", name="material_requisition_purchase_order_add_quantity")
     */
    public function purchase_order_add_quantityAction(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 Purchase Order Add Quantity'))) $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();
            $purchaseOrder_id = $request->query->get('purchaseOrder_id');

            $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_add_quantity.html.twig', array(
                'page_title' => 'Add Quantity',
                'purchaseOrder_id' => $purchaseOrder_id,
                'purchaseOrder' => $purchaseOrder
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/add_quantity_action", name="material_requisition_purchase_order_add_quantity_action")
     */
    public function purchase_order_add_quantity_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 Purchase Order Add Quantity'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';
        $em = $this->getDoctrine()->getManager();
        $purchaseOrder_id = $request->get('purchaseOrder_id');
        $purchaseOrderItems_form = $request->get('purchaseOrderItems');
        $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));

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

            foreach($purchaseOrderItems_form as $purchaseOrderItem_form) {
                foreach($purchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                    if($purchaseOrderItem_form['id'] === $purchaseOrderItem->getId()) {
                        $purchaseOrderItem->setQuantityAdded($purchaseOrderItem_form['quantityAdded']);
                        $em->flush();
                    }
                }
            }

            $em->refresh($purchaseOrder);
            $purchaseOrder->doAddQuantity();
            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/void", name="material_requisition_purchase_order_void")
     */
    public function purchase_order_voidAction(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 Purchase Order Void'))) $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();
            $purchaseOrder_id = $request->query->get('purchaseOrder_id');

            $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_void.html.twig', array(
                'page_title' => 'Void Items',
                'purchaseOrder_id' => $purchaseOrder_id,
                'purchaseOrder' => $purchaseOrder
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/void_action", name="material_requisition_purchase_order_void_action")
     */
    public function purchase_order_void_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 Purchase Order Void'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $purchaseOrder_id = $request->get('purchaseOrder_id');
        $purchaseOrderItems_form = $request->get('purchaseOrderItems');
        $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));

        foreach($purchaseOrderItems_form as $purchaseOrderItem_form) {

            foreach($purchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                if($purchaseOrderItem_form['id'] === $purchaseOrderItem->getId() && $purchaseOrderItem->getQuantityWithPo() + str_replace(',', '', $purchaseOrderItem_form['quantityVoided']) > $purchaseOrderItem->getQuantity()) {
                    $result['errorMessages'][] = 'Item ' . $purchaseOrderItem->getMaterialRequisitionItem()->getItem()->getDescription() . ' already exceed its voidable quantity.';
                }
            }
        }

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

            foreach($purchaseOrderItems_form as $purchaseOrderItem_form) {
                foreach($purchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                    if($purchaseOrderItem_form['id'] === $purchaseOrderItem->getId()) {

                        $purchaseOrderItem->setQuantityVoided($purchaseOrderItem_form['quantityVoided']);
                        $em->flush();
                    }
                }
            }

            $em->refresh($purchaseOrder);
            $purchaseOrder->doVoid();
            $em->flush();

            $em->refresh($purchaseOrder);
            $purchaseOrder->updateStatus();
            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/dashboard_data", name="material_requisition_purchase_order_dashboard_data")
     */
    public function purchase_order_dashboard_dataAction() {

        $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 Purchase Order'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {
            $result['success'] = true;
            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_dashboard_data.html.twig', array(
                'pos' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PurchaseOrderEntity')->dashboardData($this->get('session')->get('userData'))
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/ajax_list", name="material_requisition_purchase_order_breakdown_ajax_list")
     */
    public function purchase_order_breakdown_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:PurchaseOrderBreakdownEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/details", name="material_requisition_purchase_order_breakdown_details")
     */
    public function purchase_order_breakdown_detailsAction(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 Purchase Order'))) $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();
            $purchaseOrderBreakdown_id = $request->query->get('purchaseOrderBreakdown_id');
            $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

            $title = 'Details';

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_details.html.twig', array(
                'page_title' => $title,
                'purchaseOrderBreakdown' => $purchaseOrderBreakdown
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/send", name="material_requisition_purchase_order_breakdown_send")
     */
    public function purchase_order_breakdown_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 Purchase Order Send'))) $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();
            $purchaseOrderBreakdown_id = $request->get('purchaseOrderBreakdown_id');
            $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

            $purchaseOrderBreakdown->setStatus('Sent');
            $em->flush();

            $purchaseInvoice = new PurchaseInvoiceEntity();
            $purchaseInvoice->setPurchaseOrderBreakDown($purchaseOrderBreakdown);
            $em->persist($purchaseInvoice);
            $em->flush();

            $purchaseOrderBreakdown->getPurchaseOrder()->updateStatus();
            $em->flush();

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


            $this->get('session')->getFlashBag()->set('success_messages', 'P.O. Successfully Sent.');
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/print/{purchaseOrderBreakdown_id}", name="material_requisition_purchase_order_breakdown_print")
     */
    public function purchase_order_printAction($purchaseOrderBreakdown_id) {

        $authService = $this->get('rx_connexion.authService');
        ini_set('memory_limit', '2048M');
        if(!$authService->isLoggedIn()){
            return $authService->redirectToLogin();
        }

        // if(!$authService->isUserHasAccesses(array('Admin Purchase Order Print'))) return $authService->redirectToHome();

        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));


        $page_title = 'Patient Report';
        $content = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_print.wkpdf.twig', array(
            'purchaseOrderBreakdown' => $purchaseOrderBreakdown,
            'userData' => $authService->getUser()
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));
        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="PO No ' . $purchaseOrderBreakdown->getPoNo() . ' Details.pdf"'
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('material_requisition_purchase_order_view', array(
                'purchaseOrder_id' => $purchaseOrderBreakdown->getPurchaseOrder()->getIdEncoded(),
            ), 302));
        }
    }
    public function purchase_order_printAction__old($purchaseOrderBreakdown_id) {

        $authService = $this->get('rx_connexion.authService');
        ini_set('memory_limit', '2048M');
        if(!$authService->isLoggedIn()){
            return $authService->redirectToLogin();
        }

        // if(!$authService->isUserHasAccesses(array('Admin Purchase Order Print'))) return $authService->redirectToHome();

        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

        $facade = $this->get('ps_pdf.facade');
        $response = new Response();
        $this->render('@RxConnexion/MaterialRequisition/purchase_order_print.pdf.twig', array(
            'purchaseOrderBreakdown' => $purchaseOrderBreakdown,
            'userData' => $authService->getUser()
        ), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);

        return new Response($content, 200, array(
            'Content-Type' => 'application/pdf'
        ));
    }

    /**
     * @Route("/purchase_order/breakdown/form", name="material_requisition_purchase_order_breakdown_form")
     */
    public function purchase_order_breakdown_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 Purchase Order New'))) $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();
            $purchaseOrder_id = $request->query->get('purchaseOrder_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find(base64_decode($purchaseOrder_id));
            $purchaseOrderBreakdown_obj = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($id));
            $purchaseOrderBreakdown = new PurchaseOrderBreakdownEntity($purchaseOrderBreakdown_obj);

            $formOptions = array('action' => $action);
            $form = $this->createForm(new PurchaseOrderBreakdownForm($purchaseOrder, $purchaseOrderBreakdown_obj, $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->getNextPurchaseOrderNo()), $purchaseOrderBreakdown, $formOptions);

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/form_action", name="material_requisition_purchase_order_breakdown_form_action")
     */
    public function purchase_order_breakdown_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 Purchase Order New', 'Admin Purchase Order 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();
            $purchaseOrderBreakdown_form = $request->get('purchaseOrderBreakdown');

            $purchaseOrder = $em->getRepository('RxConnexionBundle:PurchaseOrderEntity')->find($purchaseOrderBreakdown_form['purchaseOrder_id']);
            $purchaseOrderBreakdown_obj = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find($purchaseOrderBreakdown_form['id']);
            $purchaseOrderBreakdown = new PurchaseOrderBreakdownEntity($purchaseOrderBreakdown_obj);

            $formOptions = array('action' => $purchaseOrderBreakdown_form['action']);
            $form = $this->createForm(new PurchaseOrderBreakdownForm($purchaseOrder, $purchaseOrderBreakdown_obj), $purchaseOrderBreakdown, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->validate($purchaseOrderBreakdown_form, $request);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $purchaseOrderBreakdown->setPurchaseOrder($purchaseOrder);
                            $em->persist($purchaseOrderBreakdown);
                            $em->flush();

                            $this->processPurchaseOrderBreakdownItem($purchaseOrderBreakdown, $request);

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

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

                        break;

                    case 'u': // update

                        $purchaseOrderBreakdown_obj = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find($purchaseOrderBreakdown_form['id']);

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

                        $purchaseOrderBreakdown_obj->setPurchaseOrderNo($purchaseOrderBreakdown_form['purchase_order_no']);
                        $purchaseOrderBreakdown_obj->setPaymentMethod($purchaseOrderBreakdown_form['payment_method']);

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

                        $em->flush();

                        $this->processPurchaseOrderBreakdownItem($purchaseOrderBreakdown_obj, $request);

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

                        break;

                    case 'd': // delete

                        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find($purchaseOrderBreakdown_form['id']);
                        $em->remove($purchaseOrderBreakdown);

                        $purchaseOrder = $purchaseOrderBreakdown->getPurchaseOrder();

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

                        $em->flush();

                        $em->refresh($purchaseOrder);

                        foreach($purchaseOrder->getPurchaseOrderItems() as $purchaseOrderItem) {
                            $purchaseOrderItem->updateQuantityWithPo();
                        }

                        $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);
    }

    private function processPurchaseOrderBreakdownItem(PurchaseOrderBreakdownEntity $purchaseOrderBreakdown, Request $request) {

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderItems_form = $request->get('purchaseOrderItems');

        foreach($purchaseOrderItems_form as $purchaseOrderItem_form) {

            $quantity = str_replace(',', '', $purchaseOrderItem_form['quantity']);
            $purchaseOrderItem = $em->getRepository('RxConnexionBundle:PurchaseOrderItemEntity')->find($purchaseOrderItem_form['id']);

            if($quantity > 0 && $purchaseOrderBreakdown->getHasPurchaseOrderItem($purchaseOrderItem)) {

                foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
                    if($purchaseOrderBreakdownItem->getPurchaseOrderItem() === $purchaseOrderItem) {

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

                        $purchaseOrderBreakdownItem->setQuantity($quantity);

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

                        $em->flush();
                    }
                }

            } else if($quantity > 0 && !$purchaseOrderBreakdown->getHasPurchaseOrderItem($purchaseOrderItem)) {
                $purchaseOrderItem = $em->getRepository('RxConnexionBundle:PurchaseOrderItemEntity')->find($purchaseOrderItem_form['id']);

                $newPurchaseOrderBreakdownItem = new PurchaseOrderBreakdownItemEntity();
                $newPurchaseOrderBreakdownItem->setPurchaseOrderBreakdown($purchaseOrderBreakdown);
                $newPurchaseOrderBreakdownItem->setPurchaseOrderItem($purchaseOrderItem);
                $newPurchaseOrderBreakdownItem->setQuantity($quantity);
                $newPurchaseOrderBreakdownItem->setItemUnitMeasurement($purchaseOrderItem->getItemUnitMeasurement());
                $em->persist($newPurchaseOrderBreakdownItem);
                $em->flush();

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

            } else if($purchaseOrderBreakdown->getHasPurchaseOrderItem($purchaseOrderItem)) {

                foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
                    if($purchaseOrderBreakdownItem->getPurchaseOrderItem() === $purchaseOrderItem) {

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

                        $em->flush();
                    }
                }
            }
        }

        foreach($purchaseOrderBreakdown->getPurchaseOrder()->getPurchaseOrderItems() as $purchaseOrderItem) {
            $purchaseOrderItem->updateQuantityWithPo();
        }

        $em->flush();

        return true;
    }

    /**
     * @Route("/purchase_order/breakdown/dashboard_data", name="material_requisition_purchase_order_breakdown_dashboard_data")
     */
    public function purchase_order_breakdown_dashboard_dataAction() {

        $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 Purchase Order Receive'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        if(!count($result['errorMessages'])) {
            $result['success'] = true;
            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_dashboard_data.html.twig', array(
                'pobs' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->dashboardData($this->get('session')->get('userData'))
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_invoice", name="material_requisition_purchase_invoice")
     */
    public function purchase_invoiceAction(Request $request) {

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

        return $this->render('@RxConnexion/MaterialRequisition/purchase_invoice.html.twig', array(
            'title' => 'Purchase Invoice',
            'page_title' => 'Purchase Invoice',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseInvoice.js?v=1.0.1'),
            'status' => $request->query->get('status'),
        ));
    }

    /**
     * @Route("/purchase_invoice/ajax_list", name="material_requisition_purchase_invoice_ajax_list")
     */
    public function purchase_invoice_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:PurchaseInvoiceEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_invoice/print/{purchase_invoice_id}", name="material_requisition_purchase_invoice_print")
     */
    public function purchase_invoice_printAction($purchase_invoice_id) {

        $authService = $this->get('rx_connexion.authService');
        ini_set('memory_limit', '2048M');
        if(!$authService->isLoggedIn()){
            return $authService->redirectToLogin();
        }

        //if(!$authService->isUserHasAccesses(array('Admin Purchase Invoice Print'))) return $authService->redirectToHome();
        set_time_limit(0);
        $em = $this->getDoctrine()->getManager();
        $purchaseInvoice = $em->getRepository('RxConnexionBundle:PurchaseInvoiceEntity')->find(base64_decode($purchase_invoice_id));

        $facade = $this->get('ps_pdf.facade');
        $response = new Response();
        $this->render('@RxConnexion/MaterialRequisition/purchase_invoice_print.pdf.twig', array(
            'purchaseInvoice' => $purchaseInvoice,
            'userData' => $authService->getUser()
        ), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);

        return new Response($content, 200, array(
            'Content-Type' => 'application/pdf'
        ));
    }

    /**
     * @Route("/purchase_invoice/view/{id}", name="material_requisition_purchase_invoice_view")
     */
    public function purchase_invoice_viewAction($id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $purchaseInvoice = $em->getRepository('RxConnexionBundle:PurchaseInvoiceEntity')->find(base64_decode($id));

        return $this->render('@RxConnexion/MaterialRequisition/purchase_invoice_view.html.twig', array(
            'title' => 'Purchase Invoice',
            'page_title' => 'Purchase Invoice',
            'purchaseInvoice' => $purchaseInvoice,
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseInvoice_view.js?v=1.0.1')
        ));
    }

    /**
     * @Route("/purchase_invoice/payment/form/{purchaseInvoice_id}/{action}/{id}",
     *     defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name="material_requisition_purchase_invoice_payment_form")
     */
    public function purchase_invoice_payment_formAction($purchaseInvoice_id, $action, $id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $purchaseInvoice_obj = $em->getRepository('RxConnexionBundle:PurchaseInvoiceEntity')->find(base64_decode($purchaseInvoice_id));

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

        $formOptions = array(
            'action' => $action,
            'purchaseInvoice_id' => $purchaseInvoice_obj->getId()
        );
        $form = $this->createForm(PurchaseInvoicePaymentForm::class, $purchaseInvoicePayment, $formOptions);
        $otherForm = $request->get('otherForm');

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

            $purchaseInvoicePayment_form = $request->get($form->getName());
            $result = $this->processPurchaseInvoicePaymentForm($purchaseInvoicePayment_form, $otherForm, $purchaseInvoicePayment, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('purchase_invoice'), 302);
                } else if($result['redirect'] === 'view') {
                    return $this->redirect($this->generateUrl('material_requisition_purchase_invoice_view', array(
                        'id' => $purchaseInvoice_id
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('material_requisition_purchase_invoice_payment_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id']),
                        'purchaseOrder_id' => $purchaseInvoice_id
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('material_requisition_purchase_invoice_payment_form',array(
                        'purchaseOrder_id' => $purchaseInvoice_id
                    )), 302);
                }
            } else {
                $form->submit($purchaseInvoicePayment_form, false);
            }
        }

        return $this->render('@RxConnexion/MaterialRequisition/purchase_invoice_payment_form.html.twig', array(
            'id' => $id,
            'action' => $action,
            'purchaseInvoice_id' => $purchaseInvoice_id,
            'title' => 'Purchase Invoice Payment',
            'page_title' => 'Purchase Invoice Payment',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseInvoicePayment_form.js?v=1.0.1'),
            'form' => $form->createView(),
            'otherForm' => $otherForm,
            'purchaseInvoice' => $purchaseInvoice_obj,
            'purchaseInvoicePayment' => $purchaseInvoicePayment
        ));
    }

    public function processPurchaseInvoicePaymentForm($purchaseInvoicePayment_form, $otherForm, $purchaseInvoicePayment, $form, $request){

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

        $errors = $em->getRepository('RxConnexionBundle:PurchaseInvoicePaymentEntity')->validate($purchaseInvoicePayment_form, $otherForm);

        if(!count($errors)) {

            switch($purchaseInvoicePayment_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

                    } else {

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

                    break;

                case 'u': // update


                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $em->flush();

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

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

                    } else {

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

                    break;

                case 'd': // delete

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

                    } else {

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


                    $em->flush();

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

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

                    break;
            }

            $result['success'] = true;

        } else {

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

            $result['success'] = false;
        }

        return $result;
    }

    private function purchaseInvoicePayment_recordAccounting(ObjectManager $em, PurchaseInvoicePaymentEntity $purchaseInvoicePayment, $otherForm) {

        $branch = $em->getRepository('RxConnexionBundle:BranchEntity')->findOneBy(array('isMain' => true));
        $supplier = $purchaseInvoicePayment->getPurchaseInvoice()->getPurchaseOrderBreakdown()->getPurchaseOrder()->getSupplier();
        $bank = $purchaseInvoicePayment->getBank();
        $tranLink = $purchaseInvoicePayment->getTransactionLink();
        $tranLinkReverse = $purchaseInvoicePayment->getTransactionLinkReverse();
        $amount = $purchaseInvoicePayment->getAmount();
        $amountWhTax = $purchaseInvoicePayment->getWhTaxAmount();
        $totalAmount = $amount + $amountWhTax;
        $payDate = $purchaseInvoicePayment->getPaymentDateAsString();

        if($tranLinkReverse) {

            $tran = $tranLinkReverse->getTransaction();
            $tranJEs = $tran->getTransactionJournalEntries();

            $tran->setTransactionDate($payDate);
            $tran->setAmount($totalAmount);

            foreach($tranJEs as $tranJE) {
                if($tranJE->getDebitAmount() > 0) {
                    $exist = false;
                    $slId = $tranJE->getSubsidiaryLedgerAccount()->getId();
                    foreach($otherForm['drAccounts'] as $key => $drAcctForm) {
                        if(isset($drAcctForm['valid']) && $slId == $drAcctForm['slId']) {
                            $tranJE->setDebitAmount($drAcctForm['amt']);
                            $exist = true;
                            $otherForm['drAccounts'][$key]['exist'] = $exist;
                            break;
                        }
                    }
                    if(!$exist) {
                        $em->remove($tranJE);
                    }
                } else {
                    $tranJE->setCreditAmount($totalAmount);
                }
            }

            if(count($otherForm['drAccounts'])){
                foreach($otherForm['drAccounts'] as $drAcctForm) {
                    if(!isset($drAcctForm['valid']) || isset($drAcctForm['exist'])) {
                        continue;
                    }
                    $newTranJE = new TransactionJournalEntryEntity();
                    $newTranJE->setTransaction($tran);
                    $newTranJE->setDebitAmount($drAcctForm['amt']);
                    $newTranJE->setSubsidiaryLedgerAccount($em->getReference('RxConnexionBundle:SubsidiaryLedgerAccountEntity', $drAcctForm['slId']));
                    $em->persist($newTranJE);
                }
            }

        } else {

            $accTran = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Order - Receive - Reverse'));
            $slAccount_credit = $accTran->getSubsidiaryLedgerAccountCredit();

            $newTran = new TransactionEntity();
            $newTran->setIsPosted(true);
            $newTran->setTransactionType($accTran->getTransactionType());
            $newTran->setBranch($branch);
            $newTran->setTransactionDate($payDate);
            $newTran->setTransactionNo($em->getRepository('RxConnexionBundle:TransactionEntity')->getNextTransactionNo($branch->getId(), $branch->getCode(), $accTran->getTransactionType()->getId(), $accTran->getTransactionType()->getCode()));
            $newTran->setAmount($totalAmount);
            $em->persist($newTran);

            foreach($otherForm['drAccounts'] as $drAcctForm) {
                if(isset($drAcctForm['valid'])) {
                    $newTranJE = new TransactionJournalEntryEntity();
                    $newTranJE->setTransaction($newTran);
                    $newTranJE->setDebitAmount($drAcctForm['amt']);
                    $newTranJE->setSubsidiaryLedgerAccount($em->getReference('RxConnexionBundle:SubsidiaryLedgerAccountEntity', $drAcctForm['slId']));
                    $em->persist($newTranJE);
                }
            }

            $newTranJE = new TransactionJournalEntryEntity();
            $newTranJE->setTransaction($newTran);
            $newTranJE->setCreditAmount($totalAmount);
            $newTranJE->setSubsidiaryLedgerAccount($slAccount_credit);
            $em->persist($newTranJE);

            $newTranLink = new TransactionLinkEntity();
            $newTranLink->setTransaction($newTran);
            $newTranLink->setPurchaseInvoicePaymentReverse($purchaseInvoicePayment);
            $em->persist($newTranLink);
        }

        $accTranWhTax = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice Payment - W/H Tax'));
        $slAccountWhTax_credit = $accTranWhTax->getSubsidiaryLedgerAccountCredit();

        if($tranLink) {

            $tran = $tranLink->getTransaction();

            $tran->setTransactionDate($payDate);
            $tran->setAmount($totalAmount);
            $tran->setNotes($purchaseInvoicePayment->getRemark());

            foreach($tran->getTransactionJournalEntries() as $tranJE) {
                if($tranJE->getDebitAmount() > 0) {
                    $tranJE->setAmount($totalAmount);
                    $tranJE->setDebitAmount($totalAmount);
                } else {
                    if($tranJE->getSubsidiaryLedgerAccount() == $slAccountWhTax_credit) {
                        if($amountWhTax > 0) {
                            $tranJE->setAmount($amountWhTax);
                            $tranJE->setCreditAmount($amountWhTax);
                        } else {
                            $em->remove($tranJE);
                        }
                    } else {
                        $tranJE->setAmount($amount);
                        $tranJE->setCreditAmount($amount);
                        $checkTran = $tranJE->getCheckTran();
                        if(PurchaseInvoicePaymentEntity::PAYMENT_METHOD_CHECK === $purchaseInvoicePayment->getPaymentMethod()) {
                            if(!$checkTran) {
                                $checkTran = new CheckTranEntity();
                                $checkTran->setTransactionJournalEntry($tranJE);
                                $checkTran->setBranch($branch);
                                $checkTran->setBank($bank);
                                $checkTran->setStatus('Pending');
                                $em->persist($checkTran);
                            }
                            $checkTran->setCheckNo($purchaseInvoicePayment->getCheckNo());
                            $checkTran->setCheckDate($purchaseInvoicePayment->getCheckDateAsString());
                            $checkTran->setAmt($amount);
                        } else if($checkTran) {
                            $em->remove($checkTran);
                        }
                    }
                }
            }

        } else {

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

            if(PurchaseInvoicePaymentEntity::PAYMENT_METHOD_CHECK === $purchaseInvoicePayment->getPaymentMethod()) {
                $accTran = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice Payment - Check'));
                $glAccount_debit = $accTran->getGeneralLedgerAccountDebit();
                $slAccount_debit = $glAccount_debit->getSlAccountLinkedBySupplier($supplier);
                if(!$slAccount_debit) {
                    $slAccount_debit = $glAccountService->processCmsSlByGl('Supplier', $glAccount_debit, $supplier);
                }
                $glAccount_credit = $accTran->getGeneralLedgerAccountCredit();
                $slAccount_credit = $glAccount_credit->getSlAccountLinkedByBank($bank);
                if(!$slAccount_credit) {
                    $slAccount_credit = $glAccountService->processCmsSlByGl('Bank', $glAccount_credit, $supplier);
                }
            } else { // Cash
                $accTran = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice Payment - Cash'));
                $glAccount_debit = $accTran->getGeneralLedgerAccountDebit();
                $slAccount_debit = $glAccount_debit->getSlAccountLinkedBySupplier($supplier);
                if(!$slAccount_debit) {
                    $slAccount_debit = $glAccountService->processCmsSlByGl('Supplier', $glAccount_debit, $supplier);
                }
                $slAccount_credit = $accTran->getSubsidiaryLedgerAccountCredit();
            }

            $tranType = $accTran->getTransactionType();

            $newTran = new TransactionEntity();
            $newTran->setIsPosted(true);
            $newTran->setTransactionType($tranType);
            $newTran->setBranch($branch);
            $newTran->setSupplier($supplier);
            $newTran->setTransactionDate($payDate);
            $newTran->setTransactionNo($em->getRepository('RxConnexionBundle:TransactionEntity')->getNextTransactionNo($branch->getId(), $branch->getCode(), $accTran->getTransactionType()->getId(), $accTran->getTransactionType()->getCode()));
            $newTran->setAmount($totalAmount);
            $newTran->setNotes($purchaseInvoicePayment->getRemark());
            $em->persist($newTran);

            $newTranJE = new TransactionJournalEntryEntity();
            $newTranJE->setTransaction($newTran);
            $newTranJE->setAmount($totalAmount);
            $newTranJE->setDebitAmount($totalAmount);
            $newTranJE->setSubsidiaryLedgerAccount($slAccount_debit);
            $em->persist($newTranJE);

            $newTranJE = new TransactionJournalEntryEntity();
            $newTranJE->setTransaction($newTran);
            $newTranJE->setAmount($amount);
            $newTranJE->setCreditAmount($amount);
            $newTranJE->setSubsidiaryLedgerAccount($slAccount_credit);
            $em->persist($newTranJE);

            if($amountWhTax > 0) {
                $newTranJE = new TransactionJournalEntryEntity();
                $newTranJE->setTransaction($newTran);
                $newTranJE->setAmount($amountWhTax);
                $newTranJE->setCreditAmount($amountWhTax);
                $newTranJE->setSubsidiaryLedgerAccount($slAccountWhTax_credit);
                $em->persist($newTranJE);
            }

            $newTranLink = new TransactionLinkEntity();
            $newTranLink->setTransaction($newTran);
            $newTranLink->setPurchaseInvoicePayment($purchaseInvoicePayment);
            $em->persist($newTranLink);

            if(PurchaseInvoicePaymentEntity::PAYMENT_METHOD_CHECK === $purchaseInvoicePayment->getPaymentMethod()) {

                $checkTran = new CheckTranEntity();
                $checkTran->setTransactionJournalEntry($newTranJE);
                $checkTran->setBranch($branch);
                $checkTran->setBank($bank);
                $checkTran->setCheckNo($purchaseInvoicePayment->getCheckNo());
                $checkTran->setCheckDate($purchaseInvoicePayment->getCheckDateAsString());
                $checkTran->setAmt($amount);
                $checkTran->setStatus('Pending');
                $em->persist($checkTran);
            }

            if($tranType->getHasVoucher()) {
                $newTran->setVoucherNo($em->getRepository('RxConnexionBundle:TransactionEntity')->getNextVoucherNoByTranType($tranType->getId()));
            }
        }

        $em->flush();
    }

    /**
     * @Route("/purchase_invoice/credit_payment/form/{purchaseInvoice_id}/{action}/{id}",
     *     defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name="material_requisition_purchase_invoice_credit_payment_form")
     */
    public function purchase_invoice_credit_payment_formAction($purchaseInvoice_id, $action, $id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $purchaseInvoice_obj = $em->getRepository('RxConnexionBundle:PurchaseInvoiceEntity')->find(base64_decode($purchaseInvoice_id));
        $purchaseInvoiceCreditPayment_obj = $em->getRepository('RxConnexionBundle:PurchaseInvoiceCreditPaymentEntity')->find(base64_decode($id));
        $purchaseInvoiceCreditPayment = new PurchaseInvoiceCreditPaymentEntity($purchaseInvoiceCreditPayment_obj);

        $formOptions = array(
            'action' => $action,
            'purchaseInvoice_id' => $purchaseInvoice_id
        );
        $form = $this->createForm(new PurchaseInvoiceCreditPaymentForm($purchaseInvoiceCreditPayment_obj), $purchaseInvoiceCreditPayment, $formOptions);

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

            $purchaseInvoiceCreditPayment_form = $request->get($form->getName());
            $result = $this->processPurchaseInvoiceCreditPaymentForm($purchaseInvoiceCreditPayment_form, $purchaseInvoiceCreditPayment, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('purchase_invoice'), 302);
                } else if($result['redirect'] === 'view') {
                    return $this->redirect($this->generateUrl('material_requisition_purchase_invoice_view', array(
                        'id' => $purchaseInvoice_id
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('material_requisition_purchase_invoice_credit_payment_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id']),
                        'purchaseOrder_id' => $purchaseInvoice_id
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('material_requisition_purchase_invoice_credit_payment_form',array(
                        'purchaseOrder_id' => $purchaseInvoice_id
                    )), 302);
                }
            }
        }

        return $this->render('@RxConnexion/MaterialRequisition/purchase_invoice_credit_payment_form.html.twig', array(
            'id' => $id,
            'action' => $action,
            'purchaseInvoice_id' => $purchaseInvoice_id,
            'title' => 'Purchase Invoice Credit Payment',
            'page_title' => 'Purchase Invoice Credit Payment',
            'purchaseInvoice' => $purchaseInvoice_obj,
            'form' => $form->createView(),
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseInvoiceCreditPayment_form.js')
        ));
    }

    public function processPurchaseInvoiceCreditPaymentForm($purchaseInvoiceCreditPayment_form, $purchaseInvoiceCreditPayment, $form, $request){

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

        $errors = $em->getRepository('RxConnexionBundle:PurchaseInvoiceCreditPaymentEntity')->validate($purchaseInvoiceCreditPayment_form);

        if(!count($errors)) {

            switch($purchaseInvoiceCreditPayment_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $purchaseInvoiceCreditPayment->setPurchaseInvoice($em->getReference('RxConnexionBundle:PurchaseInvoiceEntity', base64_decode($purchaseInvoiceCreditPayment_form['purchaseInvoice_id'])));
                        $purchaseInvoiceCreditPayment->setBank($purchaseInvoiceCreditPayment_form['bank_id'] > 0 ? $em->getReference('RxConnexionBundle:BankEntity', $purchaseInvoiceCreditPayment_form['bank_id']) : null);
                        $em->persist($purchaseInvoiceCreditPayment);
                        $em->flush();

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


                  /*      if($purchaseInvoiceCreditPayment_form['bank_id'] > 0 && $purchaseInvoiceCreditPayment_form['payment_method'] == 'Check'){

                            $checkTran = new CheckTranEntity();
                            $checkTran->setCheckNo($purchaseInvoiceCreditPayment_form['check_no']);
                            $checkTran->setCheckDate($purchaseInvoiceCreditPayment_form['check_date']);
                            $checkTran->setAmt($purchaseInvoiceCreditPayment_form['amount']);
                            $checkTran->setClearedDate($purchaseInvoiceCreditPayment_form['cleared_date']);
                            if($purchaseInvoiceCreditPayment_form['cleared_date']){
                                $checkTran->setStatus('Cleared');
                            } else {
                                $checkTran->setStatus('Pending');
                            }
                            $checkTran->setBank($em->getReference('RxConnexionBundle:BankEntity', $purchaseInvoiceCreditPayment_form['bank_id']));
                            $checkTran->setBranch($purchaseInvoiceCreditPayment->getPurchaseInvoice()->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                            $checkTran->setPurchaseInvoiceCreditPayment($purchaseInvoiceCreditPayment);
                            $em->persist($checkTran);

                            $em->flush();
                        }*/

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

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

                    } else {

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

                    break;

                case 'u': // update

                    $purchaseInvoiceCreditPayment_obj = $em->getRepository('RxConnexionBundle:PurchaseInvoiceCreditPaymentEntity')->find($purchaseInvoiceCreditPayment_form['id']);

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

                    $purchaseInvoiceCreditPayment_obj->setBank($purchaseInvoiceCreditPayment_form['bank_id'] > 0 ? $em->getReference('RxConnexionBundle:BankEntity', $purchaseInvoiceCreditPayment_form['bank_id']) : null);
                    $purchaseInvoiceCreditPayment_obj->setPaymentDate($purchaseInvoiceCreditPayment_form['payment_date']);
                    $purchaseInvoiceCreditPayment_obj->setPaymentMethod($purchaseInvoiceCreditPayment_form['payment_method']);
                    $purchaseInvoiceCreditPayment_obj->setAmount($purchaseInvoiceCreditPayment_form['amount']);
                    $purchaseInvoiceCreditPayment_obj->setRemark($purchaseInvoiceCreditPayment_form['remark']);
                    $purchaseInvoiceCreditPayment_obj->setCheckNo($purchaseInvoiceCreditPayment_form['check_no']);
                    $purchaseInvoiceCreditPayment_obj->setCheckDate($purchaseInvoiceCreditPayment_form['check_date']);
                    $purchaseInvoiceCreditPayment_obj->setClearedDate($purchaseInvoiceCreditPayment_form['cleared_date']);

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

                    $em->flush();

         /*           if($purchaseInvoiceCreditPayment_form['bank_id'] > 0 && $purchaseInvoiceCreditPayment_form['payment_method'] == 'Check'){

                        $checkTran = $purchaseInvoiceCreditPayment_obj->getCheckTran();

                        if($checkTran){

                            if($purchaseInvoiceCreditPayment_form['cleared_date']){
                                $checkTran->setStatus('Cleared');
                            } else {
                                $checkTran->setStatus('Pending');
                            }
                            $checkTran->setClearedDate($purchaseInvoiceCreditPayment_form['cleared_date']);
                            $checkTran->setCheckNo($purchaseInvoiceCreditPayment_form['check_no']);
                            $checkTran->setCheckDate($purchaseInvoiceCreditPayment_form['check_date']);
                            $checkTran->setAmt($purchaseInvoiceCreditPayment_form['amount']);
                            $checkTran->setBank($em->getReference('RxConnexionBundle:BankEntity', $purchaseInvoiceCreditPayment_form['bank_id']));

                        } else {

                            $checkTran = new CheckTranEntity();
                            $checkTran->setCheckNo($purchaseInvoiceCreditPayment_form['check_no']);
                            $checkTran->setCheckDate($purchaseInvoiceCreditPayment_form['check_date']);
                            $checkTran->setAmt($purchaseInvoiceCreditPayment_form['amount']);
                            if($purchaseInvoiceCreditPayment_form['cleared_date']){
                                $checkTran->setStatus('Cleared');
                            } else {
                                $checkTran->setStatus('Pending');
                            }
                            $checkTran->setClearedDate($purchaseInvoiceCreditPayment_form['cleared_date']);
                            $checkTran->setBank($em->getReference('RxConnexionBundle:BankEntity', $purchaseInvoiceCreditPayment_form['bank_id']));
                            $checkTran->setBranch($purchaseInvoiceCreditPayment_obj->getPurchaseInvoice()->getPurchaeOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                            $checkTran->setPurchaseInvoiceCreditPayment($purchaseInvoiceCreditPayment_obj);
                            $em->persist($checkTran);

                        }

                        $em->flush();
                    }*/

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

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

                    break;

                case 'd': // delete

                    $purchaseInvoiceCreditPayment = $em->getRepository('RxConnexionBundle:PurchaseInvoiceCreditPaymentEntity')->find($purchaseInvoiceCreditPayment_form['id']);
                    $em->remove($purchaseInvoiceCreditPayment);

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

                    $em->flush();

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

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

                    break;
            }

            $result['success'] = true;

        } else {

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

            $result['success'] = false;
        }

        return $result;
    }

    /**
     * @Route("/purchase_invoice/send", name="material_requisition_purchase_invoice_send")
     */
    public function purchase_invoice_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 Purchase Invoice Send'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $purchaseInvoice_id = $request->get('purchaseInvoice_id');
        $purchaseInvoice = $em->getRepository('RxConnexionBundle:PurchaseInvoiceEntity')->find(base64_decode($purchaseInvoice_id));
        $purchaseOrderBreakdown = $purchaseInvoice->getPurchaseOrderBreakdown();

        //if($purchaseInvoice->getTotalPayment() != $purchaseOrderBreakdown->getTotalAmount()) {
        if($purchaseInvoice->getBalanceAmount() > 0) {
            $result['errorMessages'][] = 'Invoice not yet fully paid.';
        }

        if(PurchaseOrderEntity::PAYMENT_MODE_COD !== $purchaseOrderBreakdown->getPurchaseOrder()->getPaymentMode() &&
            !$purchaseOrderBreakdown->getIsAllQuantityReceived()) {
            $result['errorMessages'][] = 'There is/are item(s) still for receiving.';
        }

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

            /*if($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Main') {
                $branch = $em->getRepository('RxConnexionBundle:BranchEntity')->findOneBy(array('isMain' => true));
            } else {
                $branch = $purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getBranch();
            }
            $supplier = $purchaseOrderBreakdown->getPurchaseOrder()->getSupplier();*/

            if($purchaseInvoice->hasCredit()){
                $purchaseInvoice->setStatus('Pending Payment');
            } else {
                $purchaseInvoice->setStatus('Completed');
            }

            /*foreach($purchaseInvoice->getPurchaseInvoicePayments() as $purchaseInvoicePayment) {

                $payAmt = $purchaseInvoicePayment->getAmount();

                $payDate = $purchaseInvoicePayment->getPaymentDateAsString();
                $refPayAmt = $purchaseInvoice->getTotalPaymentBelowAndEqualToDate($payDate) - $payAmt;
                $refReceiveAmt = $purchaseOrderBreakdown->getTotalAmountReceivedBelowAndEqualToDate($payDate) - $refPayAmt;

                if($payAmt > $refReceiveAmt) {

                    if($refReceiveAmt > 0) {

                        switch($purchaseInvoicePayment->getPaymentMethod()) {
                            case 'Check':
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Check'));
                                $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoicePayment->getBank());
                                break;
                            case 'Credit':
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Credit'));
                                $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedBySupplier($supplier);
                                break;
                            case 'Cash On Bank':
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Cash On Bank'));
                                $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedBySupplier($supplier);
                                break;
                            default:
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Cash'));
                                $slAccount_credit = $accountingTransaction->getSubsidiaryLedgerAccountCredit();
                                break;
                        }

                        $newTransaction = new TransactionEntity();
                        $newTransaction->setTransactionType($accountingTransaction->getTransactionType());
                        $newTransaction->setBranch($branch);
                        $newTransaction->setTransactionDate($payDate);
                        $newTransaction->setTransactionNo('001');
                        $newTransaction->setAmount($refReceiveAmt);
                        $em->persist($newTransaction);
                        $em->flush();

                        $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                        $newTransactionJournalEntry->setTransaction($newTransaction);
                        $newTransactionJournalEntry->setDebitAmount($refReceiveAmt);
                        $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransaction->getSubsidiaryLedgerAccountDebit());
                        $em->persist($newTransactionJournalEntry);

                        $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                        $newTransactionJournalEntry->setTransaction($newTransaction);
                        $newTransactionJournalEntry->setCreditAmount($refReceiveAmt);
                        $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccount_credit);
                        $em->persist($newTransactionJournalEntry);

                        $newTransactionLink = new TransactionLinkEntity();
                        $newTransactionLink->setTransaction($newTransaction);
                        $newTransactionLink->setPurchaseInvoicePayment($purchaseInvoicePayment);
                        $em->persist($newTransactionLink);

                        $em->flush();

                        $payAmt -= $refReceiveAmt;
                    }

                    switch($purchaseInvoicePayment->getPaymentMethod()) {
                        case 'Check':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Check - Advance'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoicePayment->getBank());
                            break;
                        case 'Credit':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Credit - Advance'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedBySupplier($supplier);
                            break;
                        case 'Cash On Bank':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Credit - Cash On Bank'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedBySupplier($supplier);
                            break;
                        default:
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Cash - Advance'));
                            $slAccount_credit = $accountingTransaction->getSubsidiaryLedgerAccountCredit();
                            break;
                    }

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransaction->getTransactionType());
                    $newTransaction->setBranch($branch);
                    $newTransaction->setTransactionDate($payDate);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($payAmt);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransaction->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    if($purchaseInvoicePayment->getPaymentMethod() == 'Check'){

                        $checkTran = new CheckTranEntity();
                        $checkTran->setCheckNo($purchaseInvoicePayment->getCheckNo());
                        $checkTran->setCheckDate($purchaseInvoicePayment->getCheckDate()->format('m/d/Y'));
                        $checkTran->setAmt($purchaseInvoicePayment->getAmount());
                        $checkTran->setBank($purchaseInvoicePayment->getBank());
                        $checkTran->setBranch($purchaseInvoicePayment->getPurchaseInvoice()->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                        $checkTran->setPurchaseInvoicePayment($purchaseInvoicePayment);
                        $checkTran->setClearedDate($purchaseInvoicePayment->getClearedDate()->format('m/d/Y'));
                        $checkTran->setTransactionJournalEntry($newTransactionJournalEntry);
                        $checkTran->setStatus(($purchaseInvoicePayment->getClearedDate()) ? 'Cleared' : 'Pending');
                        $em->persist($checkTran);
                    }

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccount_credit);
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionLink = new TransactionLinkEntity();
                    $newTransactionLink->setTransaction($newTransaction);
                    $newTransactionLink->setPurchaseInvoicePaymentAdvance($purchaseInvoicePayment);
                    $em->persist($newTransactionLink);

                    $em->flush();


                } else {

                    switch($purchaseInvoicePayment->getPaymentMethod()) {
                        case 'Check':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Check'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoicePayment->getBank());
                            break;
                        case 'Credit':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Credit'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedBySupplier($supplier);
                            break;
                        case 'Cash On Bank':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Cash On Bank'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedBySupplier($supplier);
                            break;
                        default:
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - Cash'));
                            $slAccount_credit = $accountingTransaction->getSubsidiaryLedgerAccountCredit();
                            break;
                    }

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransaction->getTransactionType());
                    $newTransaction->setBranch($branch);
                    $newTransaction->setTransactionDate($payDate);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($payAmt);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransaction->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    if($purchaseInvoicePayment->getPaymentMethod() == 'Check'){

                        $checkTran = new CheckTranEntity();
                        $checkTran->setCheckNo($purchaseInvoicePayment->getCheckNo());
                        $checkTran->setCheckDate($purchaseInvoicePayment->getCheckDate()->format('m/d/Y'));
                        $checkTran->setAmt($purchaseInvoicePayment->getAmount());
                        $checkTran->setBank($purchaseInvoicePayment->getBank());
                        $checkTran->setBranch($purchaseInvoicePayment->getPurchaseInvoice()->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                        $checkTran->setPurchaseInvoicePayment($purchaseInvoicePayment);
                        $checkTran->setClearedDate($purchaseInvoicePayment->getClearedDate()->format('m/d/Y'));
                        $checkTran->setTransactionJournalEntry($newTransactionJournalEntry);
                        $checkTran->setStatus(($purchaseInvoicePayment->getClearedDate()) ? 'Cleared' : 'Pending');
                        $em->persist($checkTran);
                    }

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccount_credit);
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionLink = new TransactionLinkEntity();
                    $newTransactionLink->setTransaction($newTransaction);
                    $newTransactionLink->setPurchaseInvoicePayment($purchaseInvoicePayment);
                    $em->persist($newTransactionLink);

                    $em->flush();

                }
            }*/

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

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

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_invoice/send_after_credit", name="material_requisition_purchase_invoice_send_after_credit")
     */
    public function purchase_invoice_send_after_creditAction(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 Purchase Invoice Send'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $purchaseInvoice_id = $request->get('purchaseInvoice_id');
        $purchaseInvoice = $em->getRepository('RxConnexionBundle:PurchaseInvoiceEntity')->find(base64_decode($purchaseInvoice_id));
        $purchaseOrderBreakdown = $purchaseInvoice->getPurchaseOrderBreakdown();

        if($purchaseInvoice->getStatus() == 'Pending Payment' && $purchaseInvoice->getTotalCredit() != $purchaseInvoice->getTotalCreditPayment()) {
            $result['errorMessages'][] = 'Credit not fully paid.';
        }

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

            if($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Main') {
                $branch = $em->getRepository('RxConnexionBundle:BranchEntity')->findOneBy(array('isMain' => true));
            } else {
                $branch = $purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getBranch();
            }
            $supplier = $purchaseOrderBreakdown->getPurchaseOrder()->getSupplier();

            $purchaseInvoice->setStatus('Completed');

            foreach($purchaseInvoice->getPurchaseInvoiceCreditPayments() as $purchaseInvoiceCreditPayment) {

                $payAmt = $purchaseInvoiceCreditPayment->getAmount();

                $payDate = $purchaseInvoiceCreditPayment->getPaymentDateAsString();
                $refPayAmt = $purchaseInvoice->getTotalPaymentBelowAndEqualToDate($payDate) - $payAmt;
                $refReceiveAmt = $purchaseOrderBreakdown->getTotalAmountReceivedBelowAndEqualToDate($payDate) - $refPayAmt;

                if($payAmt > $refReceiveAmt) {

                    if($refReceiveAmt > 0) {

                        switch($purchaseInvoiceCreditPayment->getPaymentMethod()) {
                            case 'Check':
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Check'));
                                $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoiceCreditPayment->getBank());
                                break;
                            case 'Cash On Bank':
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Cash On Bank'));
                                $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoiceCreditPayment->getBank());
                                break;
                            default:
                                $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Cash'));
                                $slAccount_credit = $accountingTransaction->getSubsidiaryLedgerAccountCredit();
                                break;
                        }

                        $newTransaction = new TransactionEntity();
                        $newTransaction->setTransactionType($accountingTransaction->getTransactionType());
                        $newTransaction->setBranch($branch);
                        $newTransaction->setTransactionDate($payDate);
                        $newTransaction->setTransactionNo('001');
                        $newTransaction->setAmount($refReceiveAmt);
                        $em->persist($newTransaction);
                        $em->flush();

                        $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                        $newTransactionJournalEntry->setTransaction($newTransaction);
                        $newTransactionJournalEntry->setDebitAmount($refReceiveAmt);
                        $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransaction->getSubsidiaryLedgerAccountDebit());
                        $em->persist($newTransactionJournalEntry);

                        $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                        $newTransactionJournalEntry->setTransaction($newTransaction);
                        $newTransactionJournalEntry->setCreditAmount($refReceiveAmt);
                        $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccount_credit);
                        $em->persist($newTransactionJournalEntry);

                        $newTransactionLink = new TransactionLinkEntity();
                        $newTransactionLink->setTransaction($newTransaction);
                        $newTransactionLink->setPurchaseInvoicePayment($purchaseInvoiceCreditPayment);
                        $em->persist($newTransactionLink);

                        $em->flush();

                        $payAmt -= $refReceiveAmt;
                    }

                    switch($purchaseInvoiceCreditPayment->getPaymentMethod()) {
                        case 'Check':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Check - Advance'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoiceCreditPayment->getBank());
                            break;
                        case 'Cash On Bank':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Cash On Bank - Advance'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoiceCreditPayment->getBank());
                            break;
                        default:
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Cash - Advance'));
                            $slAccount_credit = $accountingTransaction->getSubsidiaryLedgerAccountCredit();
                            break;
                    }

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransaction->getTransactionType());
                    $newTransaction->setBranch($branch);
                    $newTransaction->setTransactionDate($payDate);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($payAmt);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransaction->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    if($purchaseInvoiceCreditPayment->getPaymentMethod() == 'Check'){

                        $checkTran = new CheckTranEntity();
                        $checkTran->setCheckNo($purchaseInvoiceCreditPayment->getCheckNo());
                        $checkTran->setCheckDate($purchaseInvoiceCreditPayment->getCheckDate()->format('m/d/Y'));
                        $checkTran->setAmt($purchaseInvoiceCreditPayment->getAmount());
                        $checkTran->setBank($purchaseInvoiceCreditPayment->getBank());
                        $checkTran->setBranch($purchaseInvoiceCreditPayment->getPurchaseInvoice()->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                        $checkTran->setPurchaseInvoiceCreditPayment($purchaseInvoiceCreditPayment);
                        $checkTran->setClearedDate($purchaseInvoiceCreditPayment->getClearedDate()->format('m/d/Y'));
                        $checkTran->setTransactionJournalEntry($newTransaction);
                        $checkTran->setStatus(($purchaseInvoiceCreditPayment->getClearedDate()) ? 'Cleared' : 'Pending');
                        $em->persist($newTransactionJournalEntry);
                    }

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccount_credit);
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionLink = new TransactionLinkEntity();
                    $newTransactionLink->setTransaction($newTransaction);
                    $em->persist($newTransactionLink);

                    $em->flush();

                } else {

                    switch($purchaseInvoiceCreditPayment->getPaymentMethod()) {
                        case 'Check':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Check'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoiceCreditPayment->getBank());
                            break;
                        case 'Cash On Bank':
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Cash On Bank'));
                            $slAccount_credit = $accountingTransaction->getGeneralLedgerAccountCredit()->getSlAccountLinkedByBank($purchaseInvoiceCreditPayment->getBank());
                            break;
                        default:
                            $accountingTransaction = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Invoice - Complete - After Credit - Cash'));
                            $slAccount_credit = $accountingTransaction->getSubsidiaryLedgerAccountCredit();
                            break;
                    }

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransaction->getTransactionType());
                    $newTransaction->setBranch($branch);
                    $newTransaction->setTransactionDate($payDate);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($payAmt);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransaction->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    if($purchaseInvoiceCreditPayment->getPaymentMethod() == 'Check'){

                        $checkTran = new CheckTranEntity();
                        $checkTran->setCheckNo($purchaseInvoiceCreditPayment->getCheckNo());
                        $checkTran->setCheckDate($purchaseInvoiceCreditPayment->getCheckDate()->format('m/d/Y'));
                        $checkTran->setAmt($purchaseInvoiceCreditPayment->getAmount());
                        $checkTran->setBank($purchaseInvoiceCreditPayment->getBank());
                        $checkTran->setBranch($purchaseInvoiceCreditPayment->getPurchaseInvoice()->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                        $checkTran->setPurchaseInvoiceCreditPayment($purchaseInvoiceCreditPayment);
                        $checkTran->setClearedDate($purchaseInvoiceCreditPayment->getClearedDate()->format('m/d/Y'));
                        $checkTran->setTransactionJournalEntry($newTransactionJournalEntry);
                        $checkTran->setStatus(($purchaseInvoiceCreditPayment->getClearedDate()) ? 'Cleared' : 'Pending');
                        $em->persist($checkTran);
                    }

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($payAmt);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccount_credit);
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionLink = new TransactionLinkEntity();
                    $newTransactionLink->setTransaction($newTransaction);
                    $newTransactionLink->setPurchaseInvoiceCreditPayment($purchaseInvoiceCreditPayment);
                    $em->persist($newTransactionLink);

                    $em->flush();

                }
            }

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

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

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/purchase_order/breakdown/item/delivery",
     *      name = "material_requisition_purchase_order_breakdown_item_delivery"
     * )
     */
    public function purchase_order_breakdown_receiveAction(Request $request) {

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

        return $this->render('@RxConnexion/MaterialRequisition/purchase_order_breakdown_item_delivery.html.twig', array(
            'title' => 'Receive Order',
            'page_title' => 'Receive Order',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseOrderBreakdownItemDelivery.js'),
            'status' => $request->query->get('status')
        ));
    }

    /**
     * @Route("/purchase_order/breakdown/receive_ajax_list", name="material_requisition_purchase_order_breakdown_receive_ajax_list")
     */
    public function purchase_order_breakdown_receive_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:PurchaseOrderBreakdownEntity')->receive_ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/purchase_order/breakdown/item/delivery/view/{purchaseOrderBreakdown_id}",
     *      name = "material_requisition_purchase_order_breakdown_item_delivery_view"
     * )
     */
    public function purchase_order_breakdown_item_delivery_viewAction($purchaseOrderBreakdown_id) {

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

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

        return $this->render('@RxConnexion/MaterialRequisition/purchase_order_breakdown_item_delivery_view.html.twig', array(
            'title' => 'Receive Order',
            'page_title' => 'Receive Order',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/purchaseOrderBreakdownItemDelivery_view.js?v=1.0.2'),
            'purchaseOrderBreakdown_id' => $purchaseOrderBreakdown_id,
            'purchaseOrderBreakdown' => $purchaseOrderBreakdown
        ));
    }

    /**
     * @Route("/purchase_order/breakdown/item/delivery/ajax_list", name="material_requisition_purchase_order_breakdown_item_delivery_ajax_list")
     */
    public function purchase_order_breakdown_item_delivery_ajax_listAction(Request $request) {

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

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

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

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Purchase Order Receive Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->ajax_list($get, $this->get('session')->get('userData'));

            foreach($data['results'] as $row) {

                $id = base64_encode($row['id']);
                $purchaseOrderBreakdownItem_id = base64_encode($row['purchaseOrderBreakdownItem_id']);

                $action = '';

                if($hasUpdate) {
                    $action .= "<a href='javascript:void(0)' class='action-button-style href-purchaseOrderBreakdownItemDelivery-form' data-action='u' data-id='$id' data-ids='".$row['ids']."' data-ref-id='$purchaseOrderBreakdownItem_id'>Update</a>";
                }

                $values = array(
                    $row['receivedDate'],
                    $row['drDate'],
                    $row['dr_no'],
                    $row['invoiceDate'],
                    $row['invoice_no'],
                    $row['items'],
                    $action
                );

                $result['data'][] = $values;
            }

            $result['recordsTotal'] = $data['total'];
            $result['recordsFiltered'] = $data['total'];
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/item/delivery/form_all", name="material_requisition_purchase_order_breakdown_item_delivery_form_all")
     */
    public function purchase_order_breakdown_item_delivery_form_allAction(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 Purchase Order Receive New'))) $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();
            $purchaseOrderBreakdown_id = $request->query->get('purchaseOrderBreakdown_id');

            $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_item_delivery_form_all.html.twig', array(
                'page_title' => 'Receive Items',
                'purchaseOrderBreakdown_id' => $purchaseOrderBreakdown_id,
                'purchaseOrderBreakdown' => $purchaseOrderBreakdown
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/item/delivery/form_all_action", name="material_requisition_purchase_order_breakdown_item_delivery_form_all_action")
     */
    public function purchase_order_breakdown_item_delivery_form_all_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 Purchase Order Receive New'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderBreakdown_id = $request->get('purchaseOrderBreakdown_id');
        $purchaseOrderBreakdownItemDelivery_form = $request->get('purchaseOrderBreakdownItemDelivery');
        $purchaseOrderBreakdownItems_form = $request->get('purchaseOrderBreakdownItems');
        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));
        $quantity = 0;
        $emptySerialNo = 0;

        /*if(empty($purchaseOrderBreakdownItemDelivery_form['invoiceDate']))
            $result['errorMessages'][] = 'Invoice should not be blank.';

        if(empty($purchaseOrderBreakdownItemDelivery_form['invoiceNo']))
            $result['errorMessages'][] = 'Invoice no. should not be blank.';*/

        if(empty($purchaseOrderBreakdownItemDelivery_form['receivedDate']))
            $result['errorMessages'][] = 'Received Date should not be blank.';

        if(empty($purchaseOrderBreakdownItemDelivery_form['drDate']))
            $result['errorMessages'][] = 'DR Date should not be blank.';

        if(empty($purchaseOrderBreakdownItemDelivery_form['drNo']))
            $result['errorMessages'][] = 'DR No. should not be blank.';

        /*if($purchaseOrderBreakdownItemDelivery_form['paymentMethod'] === 'Check' && empty($purchaseOrderBreakdownItemDelivery_form['bank_id']))
            $result['errorMessages'][] = 'You have selected check as a payment option, Please enter bank.';*/

        foreach($purchaseOrderBreakdownItems_form as $purchaseOrderBreakdownItem_form) {

            $qty = str_replace(',', '', $purchaseOrderBreakdownItem_form['quantity']);

            if(!is_numeric($qty) || $qty <= 0) {
                continue;
            }

            $quantity += $qty;
            //$itemUnitMeasurement = $em->getRepository('RxConnexionBundle:ItemUnitMeasurementEntity')->find($purchaseOrderBreakdownItem_form['unitOfMeasurement']);

            foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {

                //        if($purchaseOrderBreakdownItem->getItemUnitMeasurement()->getId() != $itemUnitMeasurement->getId()){
                //          $qtyConversion = round(($qty * $itemUnitMeasurement->getUnitCost()) / $purchaseOrderBreakdownItem->getItemUnitMeasurement()->getUnitCost(),2);
                //    } else {
                $qtyConversion = $qty;
                //  }

                if($purchaseOrderBreakdownItem_form['id'] === $purchaseOrderBreakdownItem->getId() && $purchaseOrderBreakdownItem->getQuantityReceived() + $qtyConversion >  $purchaseOrderBreakdown->getTotalQuantityForReceiving())   {
                    $result['errorMessages'][] = 'Item ' . $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getDescription() . ' already exceed its quantity in P.O.';
                }
            }


            if(isset($purchaseOrderBreakdownItem_form['serialNo'])) {
                foreach ($purchaseOrderBreakdownItem_form['serialNo'] as $serialNo) {
                    if(empty($serialNo)){
                        $emptySerialNo++;
                    }
                }
            }
        }

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

        if($emptySerialNo > 0) {
            $result['errorMessages'][] = 'Serial No/s should not be blank';
        }

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

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

            $amount = 0;
            //$bank = $em->getRepository('RxConnexionBundle:BankEntity')->find($purchaseOrderBreakdownItemDelivery_form['bank_id']);


            foreach($purchaseOrderBreakdownItems_form as $purchaseOrderBreakdownItem_form) {
                $qty = str_replace(',', '', $purchaseOrderBreakdownItem_form['quantity']);
                if($qty > 0) {
                    foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
                        //$itemUnitMeasurement = $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getSmallestItemUnitMeasurement();
                        if($purchaseOrderBreakdownItem_form['id'] === $purchaseOrderBreakdownItem->getId()) {

                            if(!empty($purchaseOrderBreakdownItemDelivery_form['invoiceNo'])) {
                                $purchaseOrderBreakdownInvoice = $purchaseOrderBreakdown->getPurchaseOrderBreakdownInvoiceByInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoiceNo']);
                                if($purchaseOrderBreakdownInvoice) {
                                    $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                                } else {
                                    $purchaseOrderBreakdownInvoice = new PurchaseOrderBreakdownInvoiceEntity();
                                    $purchaseOrderBreakdownInvoice->setPurchaseOrderBreakdown($purchaseOrderBreakdown);
                                    $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                                    $purchaseOrderBreakdownInvoice->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoiceNo']);
                                    $em->persist($purchaseOrderBreakdownInvoice);
                                }
                            } else {
                                $purchaseOrderBreakdownInvoice = null;
                            }

                            //$itemUnitMeasurement = $em->getRepository('RxConnexionBundle:ItemUnitMeasurementEntity')->find($purchaseOrderBreakdownItem_form['unitOfMeasurement']);
                            $amount += $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getPrice() * $qty;

                            $newPurchaseOrderBreakdownItemDelivery_obj = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->findOneBy(array(
                                'purchaseOrderBreakdownItem' => $purchaseOrderBreakdownItem,
                                'drNo' => $purchaseOrderBreakdownItemDelivery_form['drNo'],
                                //'itemUnitMeasurement' => $itemUnitMeasurement,
                                'drDate' => new \Datetime($purchaseOrderBreakdownItemDelivery_form['drDate'])
                            ));

                            if(!$newPurchaseOrderBreakdownItemDelivery_obj){
                                $newPurchaseOrderBreakdownItemDelivery_obj = new PurchaseOrderBreakdownItemDeliveryEntity();
                                $newPurchaseOrderBreakdownItemDelivery_obj->setPurchaseOrderBreakdownInvoice($purchaseOrderBreakdownInvoice);
                                $newPurchaseOrderBreakdownItemDelivery_obj->setPurchaseOrderBreakdownItem($purchaseOrderBreakdownItem);
                                //$newPurchaseOrderBreakdownItemDelivery_obj->setDocNo($em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->nextDocNo());
                                $newPurchaseOrderBreakdownItemDelivery_obj->setReceivedDate($purchaseOrderBreakdownItemDelivery_form['receivedDate']);
                                $newPurchaseOrderBreakdownItemDelivery_obj->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                                $newPurchaseOrderBreakdownItemDelivery_obj->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoiceNo']);
                                $newPurchaseOrderBreakdownItemDelivery_obj->setDrDate($purchaseOrderBreakdownItemDelivery_form['drDate']);
                                $newPurchaseOrderBreakdownItemDelivery_obj->setDrNo($purchaseOrderBreakdownItemDelivery_form['drNo']);
                                $newPurchaseOrderBreakdownItemDelivery_obj->setQuantity($purchaseOrderBreakdownItem_form['quantity']);
                                //$newPurchaseOrderBreakdownItemDelivery_obj->setItemUnitMeasurement($itemUnitMeasurement);
                                //$newPurchaseOrderBreakdownItemDelivery->setPaymentMethod($purchaseOrderBreakdownItemDelivery_form['paymentMethod']);
                                //$newPurchaseOrderBreakdownItemDelivery->setBank($bank);
                                //$newPurchaseOrderBreakdownItemDelivery->setLocation(isset($purchaseOrderBreakdownItem_form['location_id']) ? $em->getReference('RxConnexionBundle:LocationEntity', $purchaseOrderBreakdownItem_form['location_id']) : null);
                                $em->persist($newPurchaseOrderBreakdownItemDelivery_obj);
                            } else {
                                $newPurchaseOrderBreakdownItemDelivery_obj->setQuantity($newPurchaseOrderBreakdownItemDelivery_obj->getQuantity() + $purchaseOrderBreakdownItem_form['quantity']);
                            }


                            if(isset($purchaseOrderBreakdownItem_form['serialNo'])) {
                                foreach ($purchaseOrderBreakdownItem_form['serialNo'] as $serialNo) {
                                    $newSerialNo = new PurchaseOrderBreakdownItemDeliverySerialNoEntity();
                                    $newSerialNo->setSerialNo($serialNo['serialNo']);
                                    $newSerialNo->setPurchaseOrderBreakdownItemDelivery($newPurchaseOrderBreakdownItemDelivery_obj);
                                    $em->persist($newSerialNo);
                                    $newPurchaseOrderBreakdownItemDelivery_obj->addPurchaseOrderBreakdownItemDeliverySerialNo($newSerialNo);
                                }
                            }


                            //if($purchaseOrderBreakdownItem->getItemUnitMeasurement()->getId() != $itemUnitMeasurement->getId()){
                            //    $qtyConversion = round(($qty * $itemUnitMeasurement->getUnitCost()) / $purchaseOrderBreakdownItem->getItemUnitMeasurement()->getUnitCost(),2);
                            //} else {
                            $qtyConversion = $qty;
                            //}

                            $purchaseOrderBreakdownItem->setQuantityReceived($qtyConversion + $purchaseOrderBreakdownItem->getQuantityReceived());

                            $em->flush();

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

                            $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                                'action' => 'New',
                                'purchaseOrderBreakdownItemDelivery' => $newPurchaseOrderBreakdownItemDelivery_obj
                            ));
                        }
                    }
                }
            }

            $em->refresh($purchaseOrderBreakdown);
            $purchaseOrderBreakdown->updateStatus();
            $em->flush();

            $em->refresh($purchaseOrderBreakdown);
            $purchaseOrderBreakdown->getPurchaseOrder()->updateStatus();
            $em->flush();

            // This is due to transmittal is not applicable to them
            //if($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
            $em->refresh($purchaseOrderBreakdown);
            $purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
            $em->flush();
            //}

//            $inventoryService->recordAccountingPurchaseOrderReceive($purchaseOrderBreakdown);

            if($amount > 0) {
//                $newUserNotif = new UserNotifEntity();
//                $newUserNotif->setUser($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getUser());
//                $newUserNotif->setBatchNo($em->getRepository('RxConnexionBundle:UserNotifEntity')->getNextBatchNo());
//                $newUserNotif->setRef('purchase_order_breakdown');
//                $newUserNotif->setRefId($purchaseOrderBreakdown->getId());
//                $newUserNotif->setDetail('Item(s) in P.O. batch no. ' . $purchaseOrderBreakdown->getPurchaseOrder()->getBatchNo() . ' (P.O. # ' . $purchaseOrderBreakdown->getPoNo() . ') has been received.');
//                $em->persist($newUserNotif);
//                $em->flush();
            }

            /*switch($purchaseOrderBreakdownItemDelivery_form['paymentMethod']) {

                case 'Cash':

                    $accountingTransactionPOReceiveCashPayment = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Order - Receive - Cash Payment'));

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransactionPOReceiveCashPayment->getTransactionType());
                    $newTransaction->setBranch($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                    $newTransaction->setTransactionDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($amount);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($amount);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransactionPOReceiveCashPayment->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($amount);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransactionPOReceiveCashPayment->getSubsidiaryLedgerAccountCredit());
                    $em->persist($newTransactionJournalEntry);

                    $em->flush();

                    break;

                case 'Check':

                    $accountingTransactionPOReceiveCheckPayment = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Order - Receive - Check Payment'));

                    $slAccountCashInBank = $em->getRepository('RxConnexionBundle:SubsidiaryLedgerAccountEntity')->findOneBy(array(
                        'generalLedgerAccount' => $accountingTransactionPOReceiveCheckPayment->getGeneralLedgerAccountCredit(),
                        'name' => $accountingTransactionPOReceiveCheckPayment->getGeneralLedgerAccountCredit()->getName() . ' ' . $bank->getDescription()
                    ));

                    if(!$slAccountCashInBank) {

                        $slAccountCashInBank = new SubsidiaryLedgerAccountEntity();
                        $slAccountCashInBank->setGeneralLedgerAccount($accountingTransactionPOReceiveCheckPayment->getGeneralLedgerAccountCredit());
                        $slAccountCashInBank->setName($accountingTransactionPOReceiveCheckPayment->getGeneralLedgerAccountCredit()->getName() . ' ' . $bank->getDescription());
                        $slAccountCashInBank->setCode($accountingTransactionPOReceiveCheckPayment->getGeneralLedgerAccountCredit()->getName() . ' ' . $bank->getDescription());
                        $slAccountCashInBank->setIsMirrored(false);
                        $em->persist($slAccountCashInBank);
                        $em->flush();
                    }

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransactionPOReceiveCheckPayment->getTransactionType());
                    $newTransaction->setBranch($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                    $newTransaction->setTransactionDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($amount);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($amount);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransactionPOReceiveCheckPayment->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($amount);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccountCashInBank);
                    $em->persist($newTransactionJournalEntry);

                    $em->flush();

                    break;

                case 'Credit':

                    $accountingTransactionPOReceiveCreditPayment = $em->getRepository('RxConnexionBundle:AccountingTransactionEntity')->findOneBy(array('description' => 'Purchase Order - Receive - Credit Payment'));

                    $slAccountAccountsPayable = $em->getRepository('RxConnexionBundle:SubsidiaryLedgerAccountEntity')->findOneBy(array(
                        'generalLedgerAccount' => $accountingTransactionPOReceiveCreditPayment->getGeneralLedgerAccountCredit(),
                        'name' => $accountingTransactionPOReceiveCreditPayment->getGeneralLedgerAccountCredit()->getName() . ' ' . $purchaseOrderBreakdown->getPurchaseOrder()->getSupplier()->getDescription()
                    ));

                    if(!$slAccountAccountsPayable) {

                        $slAccountAccountsPayable = new SubsidiaryLedgerAccountEntity();
                        $slAccountAccountsPayable->setGeneralLedgerAccount($accountingTransactionPOReceiveCreditPayment->getGeneralLedgerAccountCredit());
                        $slAccountAccountsPayable->setName($accountingTransactionPOReceiveCreditPayment->getGeneralLedgerAccountCredit()->getName() . ' ' . $purchaseOrderBreakdown->getPurchaseOrder()->getSupplier()->getDescription());
                        $slAccountAccountsPayable->setCode($accountingTransactionPOReceiveCreditPayment->getGeneralLedgerAccountCredit()->getName() . ' ' . $purchaseOrderBreakdown->getPurchaseOrder()->getSupplier()->getDescription());
                        $slAccountAccountsPayable->setIsMirrored(false);
                        $em->persist($slAccountAccountsPayable);
                        $em->flush();
                    }

                    $newTransaction = new TransactionEntity();
                    $newTransaction->setTransactionType($accountingTransactionPOReceiveCreditPayment->getTransactionType());
                    $newTransaction->setBranch($purchaseOrderBreakdown->getPurchaseOrder()->getMaterialRequisition()->getBranch());
                    $newTransaction->setTransactionDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                    $newTransaction->setTransactionNo('001');
                    $newTransaction->setAmount($amount);
                    $em->persist($newTransaction);
                    $em->flush();

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setDebitAmount($amount);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($accountingTransactionPOReceiveCreditPayment->getSubsidiaryLedgerAccountDebit());
                    $em->persist($newTransactionJournalEntry);

                    $newTransactionJournalEntry = new TransactionJournalEntryEntity();
                    $newTransactionJournalEntry->setTransaction($newTransaction);
                    $newTransactionJournalEntry->setCreditAmount($amount);
                    $newTransactionJournalEntry->setSubsidiaryLedgerAccount($slAccountAccountsPayable);
                    $em->persist($newTransactionJournalEntry);

                    $em->flush();

                    break;
            }*/

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

            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/item_delivery/form", name="material_requisition_purchase_order_breakdown_item_delivery_form")
     */
    public function purchase_order_breakdown_item_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 Purchase Order Receive New', 'Admin Purchase Order Receive 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();
            $id = $request->query->get('id');
            $ids = explode(',', $request->query->get('ids'));
            $action = $request->query->get('action');

            $purchaseOrderBreakdownItemDeliveries = $em->getRepository(PurchaseOrderBreakdownItemDeliveryEntity::class)->findBy(array('id' => $ids));
            $purchaseOrderBreakdown = $purchaseOrderBreakdownItemDeliveries[0]->getPurchaseOrderBreakdownItem()->getPurchaseOrderBreakdown();

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

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_item_delivery_form.html.twig', array(
                'page_title' => $title,
                'id' => $id,
                'purchaseOrderBreakdownItemDeliveries' => $purchaseOrderBreakdownItemDeliveries,
                'purchaseOrderBreakdown_id' => $purchaseOrderBreakdown->getIdEncoded(),
                'purchaseOrderBreakdown' => $purchaseOrderBreakdown,
                'action' => 'u'
            ));
        }

        return new JsonResponse($result);
    }
    public function purchase_order_breakdown_item_delivery_formAction__old(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 Purchase Order Receive New', 'Admin Purchase Order Receive 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();
            $purchaseOrderBreakdownItem_id = $request->query->get('purchaseOrderBreakdownItem_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $purchaseOrderBreakdownItem = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemEntity')->find(base64_decode($purchaseOrderBreakdownItem_id));
            $purchaseOrderBreakdownItemDelivery = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->find(base64_decode($id));

            if(!$purchaseOrderBreakdownItemDelivery) {
                $purchaseOrderBreakdownItemDelivery = new PurchaseOrderBreakdownItemDeliveryEntity();
            }

            $formOptions = array(
                'action' => $action,
                'purchaseOrderBreakdownItem_id' => $purchaseOrderBreakdownItem_id,
                'branchId' => $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getBranch()->getId(),
                'isItemised' => $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getIsItemised(),
            );
            $form = $this->createForm(PurchaseOrderBreakdownItemDeliveryForm::class, $purchaseOrderBreakdownItemDelivery, $formOptions);

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

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_item_delivery_form_old.html.twig', array(
                'page_title' => $title,
                'form' => $form->createView(),
                'action' => $action,
                'id' => $id,
                'purchaseOrderBreakdownItem' => $purchaseOrderBreakdownItem,
                'isItemised' => $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getIsItemised(),
                'purchaseOrderBreakdown_id' => $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getIdEncoded(),
                'purchaseOrderBreakdown' => $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/item/delivery/form_action", name="material_requisition_purchase_order_breakdown_item_delivery_form_action")
     */
    public function purchase_order_breakdown_item_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 Purchase Order Receive New', 'Admin Purchase Order Receive Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

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

            $errors = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->validate($purchaseOrderBreakdownItemDelivery_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $purchaseOrderBreakdownInvoice = $purchaseOrderBreakdown->getPurchaseOrderBreakdownInvoiceByInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                            if($purchaseOrderBreakdownInvoice) {
                                $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                            } else {
                                $purchaseOrderBreakdownInvoice = new PurchaseOrderBreakdownInvoiceEntity();
                                $purchaseOrderBreakdownInvoice->setPurchaseOrderBreakdown($purchaseOrderBreakdown);
                                $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                                $purchaseOrderBreakdownInvoice->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                                $em->persist($purchaseOrderBreakdownInvoice);
                            }

                            //$bank = $em->getRepository('RxConnexionBundle:BankEntity')->find($purchaseOrderBreakdownItemDelivery_form['bank_id']);

                            $purchaseOrderBreakdownItemDelivery->setPurchaseOrderBreakdownInvoice($purchaseOrderBreakdownInvoice);
                            //$purchaseOrderBreakdownItemDelivery->setBank($bank);
                            $purchaseOrderBreakdownItemDelivery->setPurchaseOrderBreakdownItem($purchaseOrderBreakdownItem);
                            $em->persist($purchaseOrderBreakdownItemDelivery);
                            $em->flush();

                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->updateQuantityReceived();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->updateStatus();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->updateStatus();
                            $em->flush();

                            if($purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
                                $em->refresh($purchaseOrderBreakdownItem);
                                $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
                                $em->flush();
                            }

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

                            $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                                'action' => 'New',
                                'purchaseOrderBreakdownItemDelivery' => $purchaseOrderBreakdownItemDelivery
                            ));

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

                        break;

                    case 'u': // update

                        foreach ($purchaseOrderBreakdownItemDelivery_form['deliveries'] as $k => $delivery) {

                            /**@var PurchaseOrderBreakdownItemDeliveryEntity $purchaseOrderBreakdownItemDelivery_obj */
                            $purchaseOrderBreakdownItemDelivery_obj = $em->getRepository(PurchaseOrderBreakdownItemDeliveryEntity::class)->find($delivery['id']);
                            $purchaseOrderBreakdownItem = $purchaseOrderBreakdownItemDelivery_obj->getPurchaseOrderBreakdownItem();
                            $purchaseOrderBreakdown = $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown();
                            
                            $purchaseOrderBreakdownInvoice = $purchaseOrderBreakdown->getPurchaseOrderBreakdownInvoiceByInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                            if ($purchaseOrderBreakdownInvoice) {
                                $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                            } else {
                                $purchaseOrderBreakdownInvoice = new PurchaseOrderBreakdownInvoiceEntity();
                                $purchaseOrderBreakdownInvoice->setPurchaseOrderBreakdown($purchaseOrderBreakdown);
                                $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                                $purchaseOrderBreakdownInvoice->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                                $em->persist($purchaseOrderBreakdownInvoice);
                            }

                            $purchaseOrderBreakdownItemDelivery_obj->setPurchaseOrderBreakdownInvoice($purchaseOrderBreakdownInvoice);
                            $purchaseOrderBreakdownItemDelivery_obj->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                            $purchaseOrderBreakdownItemDelivery_obj->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                            $purchaseOrderBreakdownItemDelivery_obj->setDrNo($purchaseOrderBreakdownItemDelivery_form['dr_no']);
                            $purchaseOrderBreakdownItemDelivery_obj->setQuantity($delivery['quantity']);


                            $em->flush();

                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->updateQuantityReceived();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->updateStatus();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->updateStatus();
                            $em->flush();

                            if ($purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
                                $em->refresh($purchaseOrderBreakdownItem);
                                $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
                                $em->flush();
                            }


                            if(isset($delivery['serialNo']))  {
                                // CHECK FOR REMOVED ITEM AND
                                $serialNoIds = array_column($delivery['serialNo'], 'id');
                                foreach ($purchaseOrderBreakdownItemDelivery_obj->getPurchaseOrderBreakdownItemDeliverySerialNos() as $purchaseOrderBreakdownItemDeliverySerialNo) {
                                    if (!in_array($purchaseOrderBreakdownItemDeliverySerialNo->getId(), $serialNoIds)) {
                                        $em->remove($purchaseOrderBreakdownItemDeliverySerialNo);
                                        $purchaseOrderBreakdownItemDelivery_obj->removePurchaseOrderBreakdownItemDeliverySerialNo($purchaseOrderBreakdownItemDeliverySerialNo);
                                    }
                                }


                                foreach ($delivery['serialNo'] as $key => $item) {
                                    if (!isset($item['id']) || empty($item['id'])) {
                                        $newSerialNo = new PurchaseOrderBreakdownItemDeliverySerialNoEntity();
                                        $newSerialNo->setSerialNo($item['serialNo']);
                                        $newSerialNo->setPurchaseOrderBreakdownItemDelivery($purchaseOrderBreakdownItemDelivery_obj);
                                        $purchaseOrderBreakdownItemDelivery_obj->addPurchaseOrderBreakdownItemDeliverySerialNo($newSerialNo);
                                        $em->persist($newSerialNo);
                                    } else {
                                        $serialNo = $em->getRepository(PurchaseOrderBreakdownItemDeliverySerialNoEntity::class)->find($item['id']);
                                        $serialNo->setSerialNo($item['serialNo']);
                                    }
                                }
                                $em->flush();
                            }

                            $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                                'action' => 'Update',
                                'purchaseOrderBreakdownItemDelivery' => $purchaseOrderBreakdownItemDelivery_obj
                            ));


                        }




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

                        break;

                    case 'd': // delete


                        foreach ($purchaseOrderBreakdownItemDelivery_form['deliveries'] as $k => $delivery) {

                            /**@var PurchaseOrderBreakdownItemDeliveryEntity $purchaseOrderBreakdownItemDelivery */
                            $purchaseOrderBreakdownItemDelivery = $em->getRepository(PurchaseOrderBreakdownItemDeliveryEntity::class)->find($delivery['id']);
                            $purchaseOrderBreakdownItem = $purchaseOrderBreakdownItemDelivery->getPurchaseOrderBreakdownItem();
                            $purchaseOrderBreakdown = $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown();

                            $em->remove($purchaseOrderBreakdownItemDelivery);

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

                            $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                                'action' => 'Delete',
                                'purchaseOrderBreakdownItemDelivery' => $purchaseOrderBreakdownItemDelivery
                            ));

                            $em->flush();

                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->updateQuantityReceived();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->updateStatus();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->updateStatus();
                            $em->flush();

                            if ($purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
                                $em->refresh($purchaseOrderBreakdownItem);
                                $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
                                $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);
    }
    public function purchase_order_breakdown_item_delivery_form_actionAction__old(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 Purchase Order Receive New', 'Admin Purchase Order Receive Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

            $inventoryService = $this->get('rx_connexion.inventoryService');
            $em = $this->getDoctrine()->getManager();
            $purchaseOrderBreakdownItemDelivery_form = $request->get('purchaseOrderBreakdownItemDelivery');
            $purchaseOrderBreakdownItems_form = !is_null($request->get('purchaseOrderBreakdownItems')) ? $request->get('purchaseOrderBreakdownItems') : array();

            $purchaseOrderBreakdownItem = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemEntity')->find(base64_decode($purchaseOrderBreakdownItemDelivery_form['purchaseOrderBreakdownItem']));

            $purchaseOrderBreakdownItemDelivery = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->find($purchaseOrderBreakdownItemDelivery_form['id']);

            if($purchaseOrderBreakdownItemDelivery) {
                $purchaseOrderBreakdownItemDelivery = new PurchaseOrderBreakdownItemDeliveryEntity();
            }

            $purchaseOrderBreakdown = $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown();

            $formOptions = array(
                'action' => $purchaseOrderBreakdownItemDelivery_form['action'],
                'branchId' => $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getHealthFacility()->getId()
            );
            $form = $this->createForm(PurchaseOrderBreakdownItemDeliveryForm::class, $purchaseOrderBreakdownItemDelivery, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->validate($purchaseOrderBreakdownItemDelivery_form, $purchaseOrderBreakdownItems_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $purchaseOrderBreakdownInvoice = $purchaseOrderBreakdown->getPurchaseOrderBreakdownInvoiceByInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                            if($purchaseOrderBreakdownInvoice) {
                                $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                            } else {
                                $purchaseOrderBreakdownInvoice = new PurchaseOrderBreakdownInvoiceEntity();
                                $purchaseOrderBreakdownInvoice->setPurchaseOrderBreakdown($purchaseOrderBreakdown);
                                $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                                $purchaseOrderBreakdownInvoice->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                                $em->persist($purchaseOrderBreakdownInvoice);
                            }

                            //$bank = $em->getRepository('RxConnexionBundle:BankEntity')->find($purchaseOrderBreakdownItemDelivery_form['bank_id']);

                            $purchaseOrderBreakdownItemDelivery->setPurchaseOrderBreakdownInvoice($purchaseOrderBreakdownInvoice);
                            //$purchaseOrderBreakdownItemDelivery->setBank($bank);
                            $purchaseOrderBreakdownItemDelivery->setPurchaseOrderBreakdownItem($purchaseOrderBreakdownItem);
                            $em->persist($purchaseOrderBreakdownItemDelivery);
                            $em->flush();

                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->updateQuantityReceived();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->updateStatus();
                            $em->flush();
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->updateStatus();
                            $em->flush();

                            if($purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
                                $em->refresh($purchaseOrderBreakdownItem);
                                $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
                                $em->flush();
                            }

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

                            $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                                'action' => 'New',
                                'purchaseOrderBreakdownItemDelivery' => $purchaseOrderBreakdownItemDelivery
                            ));

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

                        break;

                    case 'u': // update

                        /**@var PurchaseOrderBreakdownItemDeliveryEntity $purchaseOrderBreakdownItemDelivery_obj*/
                        $purchaseOrderBreakdownItemDelivery_obj = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemDeliveryEntity')->find($purchaseOrderBreakdownItemDelivery_form['id']);

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

                        $purchaseOrderBreakdownInvoice = $purchaseOrderBreakdown->getPurchaseOrderBreakdownInvoiceByInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                        if($purchaseOrderBreakdownInvoice) {
                            $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                        } else {
                            $purchaseOrderBreakdownInvoice = new PurchaseOrderBreakdownInvoiceEntity();
                            $purchaseOrderBreakdownInvoice->setPurchaseOrderBreakdown($purchaseOrderBreakdown);
                            $purchaseOrderBreakdownInvoice->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                            $purchaseOrderBreakdownInvoice->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                            $em->persist($purchaseOrderBreakdownInvoice);
                        }

                        //$bank = $em->getRepository('RxConnexionBundle:BankEntity')->find($purchaseOrderBreakdownItemDelivery_form['bank_id']);

                        $purchaseOrderBreakdownItemDelivery_obj->setPurchaseOrderBreakdownInvoice($purchaseOrderBreakdownInvoice);
                        //$purchaseOrderBreakdownItemDelivery_obj->setBank($bank);
                        //$purchaseOrderBreakdownItemDelivery_obj->setLocation(isset($purchaseOrderBreakdownItemDelivery_form['location']) ? $em->getReference('RxConnexionBundle:LocationEntity', $purchaseOrderBreakdownItemDelivery_form['location']) : null);
                        $purchaseOrderBreakdownItemDelivery_obj->setInvoiceDate($purchaseOrderBreakdownItemDelivery_form['invoiceDate']);
                        $purchaseOrderBreakdownItemDelivery_obj->setInvoiceNo($purchaseOrderBreakdownItemDelivery_form['invoice_no']);
                        $purchaseOrderBreakdownItemDelivery_obj->setDrNo($purchaseOrderBreakdownItemDelivery_form['dr_no']);
                        $purchaseOrderBreakdownItemDelivery_obj->setQuantity($purchaseOrderBreakdownItemDelivery_form['quantity']);

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

                        $em->flush();

                        $em->refresh($purchaseOrderBreakdownItem);
                        $purchaseOrderBreakdownItem->updateQuantityReceived();
                        $em->flush();
                        $em->refresh($purchaseOrderBreakdownItem);
                        $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->updateStatus();
                        $em->flush();
                        $em->refresh($purchaseOrderBreakdownItem);
                        $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->updateStatus();
                        $em->flush();

                        if($purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
                            $em->flush();
                        }


                        if(!is_null($purchaseOrderBreakdownItems_form)) {
                            foreach ($purchaseOrderBreakdownItems_form as $k => $pobi) {
                                if(isset($pobi['serialNo'])) {
                                    $serialNoIds = array_column($pobi['serialNo'], 'id');
                                    foreach ($purchaseOrderBreakdownItemDelivery_obj->getPurchaseOrderBreakdownItemDeliverySerialNos() as $purchaseOrderBreakdownItemDeliverySerialNo) {
                                        if(!in_array($purchaseOrderBreakdownItemDeliverySerialNo->getId(), $serialNoIds)) {
                                            $em->remove($purchaseOrderBreakdownItemDeliverySerialNo);
                                            $purchaseOrderBreakdownItemDelivery_obj->removePurchaseOrderBreakdownItemDeliverySerialNo($purchaseOrderBreakdownItemDeliverySerialNo);
                                        }
                                    }
                                    foreach ($pobi['serialNo'] as $key => $item) {
                                        if(!isset($item['id']) || empty($item['id'])) {
                                            $newSerialNo = new PurchaseOrderBreakdownItemDeliverySerialNoEntity();
                                            $newSerialNo->setSerialNo($item['serialNo']);
                                            $newSerialNo->setPurchaseOrderBreakdownItemDelivery($purchaseOrderBreakdownItemDelivery_obj);
                                            $purchaseOrderBreakdownItemDelivery_obj->addPurchaseOrderBreakdownItemDeliverySerialNo($newSerialNo);
                                            $em->persist($newSerialNo);
                                        } else {
                                            $serialNo = $em->getRepository(PurchaseOrderBreakdownItemDeliverySerialNoEntity::class)->find($item['id']);
                                            $serialNo->setSerialNo($item['serialNo']);
                                        }
                                    }
                                    $em->flush();
                                }
                            }
                        }

                        $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                            'action' => 'Update',
                            'purchaseOrderBreakdownItemDelivery' => $purchaseOrderBreakdownItemDelivery_obj
                        ));


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

                        break;

                    case 'd': // delete

                        $purchaseOrderBreakdownItemDelivery = $em->getRepository(PurchaseOrderBreakdownItemDeliveryEntity::class)->find($purchaseOrderBreakdownItemDelivery_form['id']);
                        $em->remove($purchaseOrderBreakdownItemDelivery);

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

                        $inventoryService->recordMovement('Purchasing Purchase Order Receive', array(
                            'action' => 'Delete',
                            'purchaseOrderBreakdownItemDelivery' => $purchaseOrderBreakdownItemDelivery
                        ));

                        $em->flush();

                        $em->refresh($purchaseOrderBreakdownItem);
                        $purchaseOrderBreakdownItem->updateQuantityReceived();
                        $em->flush();
                        $em->refresh($purchaseOrderBreakdownItem);
                        $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->updateStatus();
                        $em->flush();
                        $em->refresh($purchaseOrderBreakdownItem);
                        $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->updateStatus();
                        $em->flush();

                        if($purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->getCanvassType() === 'Branch') {
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->getPurchaseOrderBreakdown()->getPurchaseOrder()->getMaterialRequisition()->updateStatus();
                            $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("/purchase_order/breakdown/item/delivery/add_quantity", name="material_requisition_purchase_order_breakdown_item_delivery_add_quantity")
     */
    public function purchase_order_breakdown_item_delivery_add_quantityAction(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 Purchase Order Receive Add Quantity'))) $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();
            $purchaseOrderBreakdown_id = $request->query->get('purchaseOrderBreakdown_id');

            $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_add_quantity.html.twig', array(
                'page_title' => 'Add Quantity',
                'purchaseOrderBreakdown_id' => $purchaseOrderBreakdown_id,
                'purchaseOrderBreakdown' => $purchaseOrderBreakdown
            ));
        }

        return new JsonResponse($result);
    }


    /**
     * @Route("/purchase_order/breakdown/item/delivery/void", name="material_requisition_purchase_order_breakdown_item_delivery_void")
     */
    public function purchase_order_breakdown_item_delivery_voidAction(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 Purchase Order Receive Void'))) $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();
            $purchaseOrderBreakdown_id = $request->query->get('purchaseOrderBreakdown_id');

            $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/purchase_order_breakdown_void.html.twig', array(
                'page_title' => 'Void Items',
                'purchaseOrderBreakdown_id' => $purchaseOrderBreakdown_id,
                'purchaseOrderBreakdown' => $purchaseOrderBreakdown
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/item/delivery/add_quantity_action", name="material_requisition_purchase_order_breakdown_item_delivery_add_quantity_action")
     */
    public function purchase_order_breakdown_item_delivery_add_quantity_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 Purchase Order Receive Add Quantity'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderBreakdown_id = $request->get('purchaseOrderBreakdown_id');
        $purchaseOrderBreakdownItems_form = $request->get('purchaseOrderBreakdownItems');
        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));


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

            foreach($purchaseOrderBreakdownItems_form as $purchaseOrderBreakdownItem_form) {
                foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
                    if($purchaseOrderBreakdownItem_form['id'] == $purchaseOrderBreakdownItem->getId()) {
                        $purchaseOrderBreakdownItem->setQuantityAdded($purchaseOrderBreakdownItem_form['addQuantity']);
                        $em->flush();
                    }
                }
            }


            $em->refresh($purchaseOrderBreakdown);
            $purchaseOrderBreakdown->updateStatus();
            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/purchase_order/breakdown/item/delivery/void_action", name="material_requisition_purchase_order_breakdown_item_delivery_void_action")
     */
    public function purchase_order_breakdown_item_delivery_void_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 Purchase Order Receive Void'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $purchaseOrderBreakdown_id = $request->get('purchaseOrderBreakdown_id');
        $purchaseOrderBreakdownItems_form = $request->get('purchaseOrderBreakdownItems');
        $purchaseOrderBreakdown = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownEntity')->find(base64_decode($purchaseOrderBreakdown_id));

        foreach($purchaseOrderBreakdownItems_form as $purchaseOrderBreakdownItem_form) {

            foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
                if(empty($purchaseOrderBreakdownItem_form['voidNotes'])) {
                    $result['errorMessages'][] = 'Void notes of Item ' . $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getDescription() . ' should not be blank.';
                }
                if(!empty($purchaseOrderBreakdownItem_form['quantityVoided'])) {
                    if ($purchaseOrderBreakdownItem_form['id'] === $purchaseOrderBreakdownItem->getId() && $purchaseOrderBreakdownItem->getQuantityReceived() + str_replace(',', '', $purchaseOrderBreakdownItem_form['quantityVoided']) > $purchaseOrderBreakdownItem->getQuantity()) {
                        $result['errorMessages'][] = 'Item ' . $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getDescription() . ' already exceed its voidable quantity.';
                    }
                    if (floatval($purchaseOrderBreakdownItem_form['quantityVoided']) <= 0) {
                        $result['errorMessages'][] = 'Voidable quantity of Item ' . $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getDescription() . ' should not be blank.';
                    }
                } else {
                    $result['errorMessages'][] = 'Voidable quantity of Item ' . $purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem()->getItem()->getDescription() . ' should not be blank.';
                }
            }
        }

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

            foreach($purchaseOrderBreakdownItems_form as $purchaseOrderBreakdownItem_form) {
                /**@var PurchaseOrderBreakdownItemEntity $purchaseOrderBreakdownItem*/
                foreach($purchaseOrderBreakdown->getPurchaseOrderBreakdownItems() as $purchaseOrderBreakdownItem) {
                    if($purchaseOrderBreakdownItem_form['id'] === $purchaseOrderBreakdownItem->getId()) {
                        $purchaseOrderBreakdownItem->setVoidNotes($purchaseOrderBreakdownItem_form['voidNotes']);
                        $purchaseOrderBreakdownItem->setQuantityVoided($purchaseOrderBreakdownItem_form['quantityVoided']);
                        $em->flush();
                    }
                }
            }

            $em->refresh($purchaseOrderBreakdown);
            $purchaseOrderBreakdown->doVoid();
            $em->flush();

            $em->refresh($purchaseOrderBreakdown);
            $purchaseOrderBreakdown->updateStatus();
            $em->flush();

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal", name="material_requisition_transmittal")
     */
    public function transmittalAction() {

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

        return $this->render('@RxConnexion/MaterialRequisition/transmittal.html.twig', array(
            'title' => 'Transmittal',
            'page_title' => 'Transmittal',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/transmittal.js')
        ));
    }

    /**
     * @Route("/transmittal/ajax_list", name="material_requisition_transmittal_ajax_list")
     */
    public function transmittal_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:TransmittalEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

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

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

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

        $transmittal_obj = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find(base64_decode($id));
        $transmittal = new TransmittalEntity($transmittal_obj);

        $formOptions = array(
            'action' => $action
        );
        $form = $this->createForm(new TransmittalForm($transmittal_obj), $transmittal, $formOptions);

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

            $transmittal_form = $request->get($form->getName());
            $result = $this->processTransmittalForm($transmittal_form, $transmittal, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('material_requisition_transmittal'), 302);
                } else if($result['redirect'] === 'item') {
                    return $this->redirect($this->generateUrl('material_requisition_transmittal_item', array(
                        'transmittal_id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('material_requisition_transmittal_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('material_requisition_transmittal_form'), 302);
                }
            }
        }

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

        return $this->render('@RxConnexion/MaterialRequisition/transmittal_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id
        ));
    }

    private function processTransmittalForm($transmittal_form, $transmittal, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:TransmittalEntity')->validate($transmittal_form);

        if(!count($errors)) {

            switch($transmittal_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

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

                    } else {

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

                    break;

                case 'u': // update

                    $transmittal_obj = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find($transmittal_form['id']);

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

                    $branchFrom = $em->getRepository('RxConnexionBundle:BranchEntity')->find($transmittal_form['branchFrom']);
                    $branchTo = $em->getRepository('RxConnexionBundle:BranchEntity')->find($transmittal_form['branchTo']);
                    $deliveryType = $em->getRepository('RxConnexionBundle:DeliveryTypeEntity')->find($transmittal_form['deliveryType']);

                    $transmittal_obj->setBranchFrom($branchFrom);
                    $transmittal_obj->setBranchTo($branchTo);
                    $transmittal_obj->setDeliveryType($deliveryType);
                    $transmittal_obj->setDeliveryNo($transmittal_form['delivery_no']);
                    $transmittal_obj->setDeliveryDate($transmittal_form['delivery_date']);
                    $transmittal_obj->setLoader($transmittal_form['loader']);
                    $transmittal_obj->setNote($transmittal_form['note']);

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

                    $em->flush();

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

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

                    break;

                case 'd': // delete

                    $transmittal = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find($transmittal_form['id']);
                    $em->remove($transmittal);

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

                    if(count($transmittal->getTransmittalItems())) {

                        $purchaseOrderBreakdownItems = array();

                        foreach($transmittal->getTransmittalItems() as $transmittalItem) {
                            $purchaseOrderBreakdownItems[] = $transmittalItem->getPurchaseOrderBreakdownItem();
                        }

                        $em->flush();

                        foreach($purchaseOrderBreakdownItems as $purchaseOrderBreakdownItem) {
                            $em->refresh($purchaseOrderBreakdownItem);
                            $purchaseOrderBreakdownItem->updateQuantityTransmittal();
                            $em->flush();
                        }

                    } else {

                        $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;
    }

    /**
     * @Route("/transmittal/send", name="material_requisition_transmittal_send")
     */
    public function transmittal_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 Transmittal Send'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

        $em = $this->getDoctrine()->getManager();
        $transmittal_id = $request->get('transmittal_id');
        $transmittal = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find(base64_decode($transmittal_id));

        if(!count($transmittal->getTransmittalItems()))
            $result['errorMessages'][] = 'Atleast one(1) loaded item is needed.';

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

            $transmittal->updateStatus();
            $em->flush();

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

            $inventoryService = $this->get('rx_connexion.inventoryService');
            $inventoryService->recordMovement('Purchasing Transmittal Send', array(
                'transmittal' => $transmittal
            ));

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/transmittal/item/index/{transmittal_id}",
     *      name = "material_requisition_transmittal_item"
     * )
     */
    public function transmittal_itemAction($transmittal_id) {

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

        $em = $this->getDoctrine()->getManager();
        $transmittal = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find(base64_decode($transmittal_id));

        return $this->render('@RxConnexion/MaterialRequisition/transmittal_item.html.twig', array(
            'title' => 'Transmittal Items',
            'page_title' => 'Transmittal Items',
            'javascripts' => array('rxconnexion/admin/js/materialRequisition/transmittalItem.js'),
            'transmittal_id' => $transmittal_id,
            'transmittal' => $transmittal
        ));
    }

    /**
     * @Route("/transmittal/item/ajax_list", name="material_requisition_transmittal_item_ajax_list")
     */
    public function transmittal_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:TransmittalItemEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/ajax_list_for_loading", name="material_requisition_transmittal_item_ajax_list_for_loading")
     */
    public function transmittal_item_ajax_list_for_loadingAction(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:TransmittalItemEntity')->ajax_list_for_loading($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/load", name="material_requisition_transmittal_item_load")
     */
    public function transmittal_item_loadAction(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 Transmittal Item Load'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $transmittal_id = $request->get('transmittal_id');
        $purchaseOrderBreakdownItem_id = $request->get('purchaseOrderBreakdownItem_id');
        $quantity = str_replace(',', '', $request->get('quantity'));
        $transmittal = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find(base64_decode($transmittal_id));
        $purchaseOrderBreakdownItem = $em->getRepository('RxConnexionBundle:PurchaseOrderBreakdownItemEntity')->find(base64_decode($purchaseOrderBreakdownItem_id));

        if(empty($quantity) || $quantity === 0)
            $result['errorMessages'][] = 'Quantity should be greater than zero(0).';

        if($purchaseOrderBreakdownItem->getQuantityTransmittal() > $purchaseOrderBreakdownItem->getQuantityReceived())
            $result['errorMessages'][] = 'Maximum quantity for the selected item has been loaded already.';
        else if($quantity > $purchaseOrderBreakdownItem->getQuantityReceived() - $purchaseOrderBreakdownItem->getQuantityTransmittal())
            $result['errorMessages'][] = 'Entered quantity exceeds quantity for loading.';

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

            $hasLoadedItem = false;

            if(count($transmittal->getTransmittalItems())) {
                foreach($transmittal->getTransmittalItems() as $transmittalItem) {
                    if($purchaseOrderBreakdownItem === $transmittalItem->getPurchaseOrderBreakdownItem()) {

                        $hasLoadedItem = true;

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

                        $transmittalItem->setQuantity($transmittalItem->getQuantity() + $quantity);

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

                        $em->flush();
                        break;
                    }
                }
            }

            if(!$hasLoadedItem) {

                $newTransmittalItem = new TransmittalItemEntity();
                $newTransmittalItem->setTransmittal($transmittal);
                $newTransmittalItem->setPurchaseOrderBreakdownItem($purchaseOrderBreakdownItem);
                $newTransmittalItem->setMaterialRequisitionItem($purchaseOrderBreakdownItem->getPurchaseOrderItem()->getMaterialRequisitionItem());
                $newTransmittalItem->setQuantity($quantity);
                $em->persist($newTransmittalItem);
                $em->flush();

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

            $em->refresh($purchaseOrderBreakdownItem);
            $purchaseOrderBreakdownItem->updateQuantityTransmittal();
            $em->flush();

            $result['success'] = true;
            $result['successMessages'] = array('Item Successfully Loaded.');
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/unload", name="material_requisition_transmittal_item_unload")
     */
    public function transmittal_item_unloadAction(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 Transmittal Item Unload'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $transmittalItem_id = $request->get('transmittalItem_id');
        $quantity = str_replace(',', '', $request->get('quantity'));
        $transmittalItem = $em->getRepository('RxConnexionBundle:TransmittalItemEntity')->find(base64_decode($transmittalItem_id));

        if(empty($quantity) || $quantity === 0)
            $result['errorMessages'][] = 'Quantity should be greater than zero(0).';

        if($quantity > $transmittalItem->getQuantity())
            $result['errorMessages'][] = 'Entered quantity exceeds loaded quantity.';

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

            $purchaseOrderBreakdownItem = $transmittalItem->getPurchaseOrderBreakdownItem();

            if($quantity == $transmittalItem->getQuantity()) {

                $em->remove($transmittalItem);

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

            } else {

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

                $transmittalItem->setQuantity($transmittalItem->getQuantity() - $quantity);

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

                $em->flush();
            }

            $em->refresh($purchaseOrderBreakdownItem);
            $purchaseOrderBreakdownItem->updateQuantityTransmittal();
            $em->flush();

            $result['success'] = true;
            $result['successMessages'] = array('Item Successfully Unloaded.');
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/delivery/ajax_list", name="material_requisition_transmittal_item_delivery_ajax_list")
     */
    public function transmittal_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:TransmittalItemDeliveryEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/delivery/form_all", name="material_requisition_transmittal_item_delivery_form_all")
     */
    public function transmittal_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 Transmittal Item Receive'))) return $authService->redirectToHome();

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

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

            $transmittal = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find(base64_decode($transmittal_id));

            $result['html'] = $this->renderView('@RxConnexion/MaterialRequisition/transmittal_item_delivery_form_all.html.twig', array(
                'page_title' => 'Receive Items',
                'transmittal_id' => $transmittal_id,
                'transmittal' => $transmittal
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/delivery/form_all_action", name="material_requisition_transmittal_item_delivery_form_all_action")
     */
    public function transmittal_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 Transmittal Item Receive'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $transmittal_id = $request->get('transmittal_id');
        $transmittalItemDelivery_form = $request->get('transmittalItemDelivery');
        $transmittalItems_form = $request->get('transmittalItems');
        $quantity = 0;
        $transmittal = $em->getRepository('RxConnexionBundle:TransmittalEntity')->find(base64_decode($transmittal_id));

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

        foreach($transmittalItems_form as $transmittalItem_form) {
            $quantity += str_replace(',', '', $transmittalItem_form['quantity']);

            foreach($transmittal->getTransmittalItems() as $transmittalItem) {
                if($transmittalItem_form['id'] === $transmittalItem->getId() && $transmittalItem->getQuantityReceived() + str_replace(',', '', $transmittalItem_form['quantity']) > $transmittalItem->getQuantity()) {
                    $result['errorMessages'][] = 'Item ' . $transmittalItem->getMaterialRequisitionItem()->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');
            $materialRequisitions = array();

            foreach($transmittalItems_form as $transmittalItem_form) {
                if(str_replace(',', '', $transmittalItem_form['quantity']) > 0) {
                    foreach($transmittal->getTransmittalItems() as $transmittalItem) {
                        if($transmittalItem_form['id'] === $transmittalItem->getId()) {

                            if(!in_array($transmittalItem->getMaterialRequisitionItem()->getMaterialRequisition(), $materialRequisitions))
                                $materialRequisitions[] = $transmittalItem->getMaterialRequisitionItem()->getMaterialRequisition();

                            $newTransmittalItemDelivery = new TransmittalItemDeliveryEntity();
                            $newTransmittalItemDelivery->setTransmittalItem($transmittalItem);
                            $newTransmittalItemDelivery->setReceiveDate($transmittalItemDelivery_form['receiveDate']);
                            $newTransmittalItemDelivery->setQuantity($transmittalItem_form['quantity']);
                            $newTransmittalItemDelivery->setLocation(isset($transmittalItem_form['location_id']) ? $em->getReference('RxConnexionBundle:LocationEntity', $transmittalItem_form['location_id']) : null);
                            $em->persist($newTransmittalItemDelivery);

                            $transmittalItem->setQuantityReceived($transmittalItem->getQuantityReceived() + str_replace(',', '', $transmittalItem_form['quantity']));

                            $em->flush();

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

                            $inventoryService->recordMovement('Purchasing Transmittal Receive', array(
                                'action' => 'New',
                                'transmittalItemDelivery' => $newTransmittalItemDelivery
                            ));
                        }
                    }
                }
            }

            $em->refresh($transmittal);
            $transmittal->updateStatus();
            $em->flush();

            foreach($materialRequisitions as $materialRequisition) {
                $em->refresh($materialRequisition);
                $materialRequisition->updateStatus();
                $em->flush();
            }

            if($transmittal->getStatus() === 'Received') {
                $inventoryService->recordAccountingTransferSupplies('Transmittal', array('transmittal' => $transmittal));
            }

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item_delivery/form", name="material_requisition_transmittal_item_delivery_form")
     */
    public function transmittal_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 Transmittal Item Receive Update'))) return $authService->redirectToHome();

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

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

            $transmittalItem = $em->getRepository('RxConnexionBundle:TransmittalItemEntity')->find(base64_decode($transmittalItem_id));
            $transmittalItemDelivery_obj = $em->getRepository('RxConnexionBundle:TransmittalItemDeliveryEntity')->find(base64_decode($id));
            $transmittalItemDelivery = new TransmittalItemDeliveryEntity($transmittalItemDelivery_obj);

            $formOptions = array(
                'action' => $action,
                'branchId' => $transmittalItem->getTransmittal()->getBranchTo()->getId()
            );
            $form = $this->createForm(new TransmittalItemDeliveryForm($transmittalItem, $transmittalItemDelivery_obj), $transmittalItemDelivery, $formOptions);

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/transmittal/item/delivery/form_action", name="material_requisition_transmittal_item_delivery_form_action")
     */
    public function transmittal_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 Transmittal Item Receive Update'))) return $authService->redirectToHome();

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

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

            $transmittalItem = $em->getRepository('RxConnexionBundle:TransmittalItemEntity')->find($transmittalItemDelivery_form['transmittalItem_id']);
            $transmittalItemDelivery_obj = $em->getRepository('RxConnexionBundle:TransmittalItemDeliveryEntity')->find($transmittalItemDelivery_form['id']);
            $transmittalItemDelivery = new TransmittalItemDeliveryEntity($transmittalItemDelivery_obj);

            $formOptions = array(
                'action' => $transmittalItemDelivery_form['action'],
                'branchId' => $transmittalItem->getTransmittal()->getBranchTo()->getId()
            );
            $form = $this->createForm(new TransmittalItemDeliveryForm($transmittalItem, $transmittalItemDelivery_obj), $transmittalItemDelivery, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:TransmittalItemDeliveryEntity')->validate($transmittalItemDelivery_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $transmittalItemDelivery->setTransmittalItem($transmittalItem);
                            $em->persist($transmittalItemDelivery);
                            $em->flush();

                            $em->refresh($transmittalItem);
                            $transmittalItem->updateQuantityReceived();
                            $em->flush();
                            $em->refresh($transmittalItem);
                            $transmittalItem->getTransmittal()->updateStatus();
                            $em->flush();
                            $em->refresh($transmittalItem);
                            $transmittalItem->getMaterialRequisitionItem()->getMaterialRequisition()->updateStatus();
                            $em->flush();

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

                            $inventoryService->recordMovement('Purchasing Transmittal Receive', array(
                                'action' => 'New',
                                'transmittalItemDelivery' => $transmittalItemDelivery
                            ));

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

                        break;

                    case 'u': // update

                        $transmittalItemDelivery_obj = $em->getRepository('RxConnexionBundle:TransmittalItemDeliveryEntity')->find($transmittalItemDelivery_form['id']);

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

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

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

                        $em->flush();

                        $em->refresh($transmittalItem);
                        $transmittalItem->updateQuantityReceived();
                        $em->flush();
                        $em->refresh($transmittalItem);
                        $transmittalItem->getTransmittal()->updateStatus();
                        $em->flush();
                        $em->refresh($transmittalItem);
                        $transmittalItem->getMaterialRequisitionItem()->getMaterialRequisition()->updateStatus();
                        $em->flush();

                        $inventoryService->recordMovement('Purchasing Transmittal Receive', array(
                            'action' => 'Update',
                            'transmittalItemDelivery' => $transmittalItemDelivery_obj
                        ));

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

                        break;

                    case 'd': // delete

                        $transmittalItemDelivery = $em->getRepository('RxConnexionBundle:TransmittalItemDeliveryEntity')->find($transmittalItemDelivery_form['id']);
                        $em->remove($transmittalItemDelivery);

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

                        $inventoryService->recordMovement('Purchasing Transmittal Receive', array(
                            'action' => 'Delete',
                            'transmittalItemDelivery' => $transmittalItemDelivery
                        ));

                        $em->flush();

                        $em->refresh($transmittalItem);
                        $transmittalItem->updateQuantityReceived();
                        $em->flush();
                        $em->refresh($transmittalItem);
                        $transmittalItem->getTransmittal()->updateStatus();
                        $em->flush();
                        $em->refresh($transmittalItem);
                        $transmittalItem->getMaterialRequisitionItem()->getMaterialRequisition()->updateStatus();
                        $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("/preview/{status}",
     *     defaults = {
     *          "status" : ""
     *     },
     *     name="material_requisition_preview")
     */
    public function previewAction(Request $request,$status) {

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

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

        if($status != 'all'){
            $materialRequisitions = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->findBy(array('status' => $status));
        } else {
            $materialRequisitions = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->findAll();
        }


        return $this->render('@RxConnexion/MaterialRequisition/preview.html.twig', array(
            'title' => 'Material Requisition Print',
            'page_title' => 'Material Requisition Print',
            'stylesheets' => array('rxconnexion/admin/css/report/report_preview.css'),
            'javascripts' => array('rxconnexion/admin/js/report/report_preview.js'),
            'materialRequisitions' => $materialRequisitions
        ));
    }


    /**
     * @Route("/note/form", name="material_requisition_note_form")
     */
    public function note_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 Material Requisition Note New', 'Admin Material Requisition Note 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();
            $materialRequisition_id = $request->query->get('materialRequisition_id');
            $id = $request->query->get('id');
            $action = $request->query->get('action');

            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find(base64_decode($materialRequisition_id));
            $materialRequisitionNote = $em->getRepository('RxConnexionBundle:MaterialRequisitionNoteEntity')->find(base64_decode($id));

            if(!$materialRequisitionNote) {
                $materialRequisitionNote = new MaterialRequisitionNoteEntity($materialRequisitionNote);
            }

            $formOptions = array(
                'materialRequisition_id' => $materialRequisition->getId(),
                'action' => $action,
            );
            $form = $this->createForm(MaterialRequisitionNoteForm::class, $materialRequisitionNote, $formOptions);

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/note/form_action", name="material_requisition_note_form_action")
     */
    public function note_form_actionAction(Request $request) {


        $result['success'] = false;
        $authService = $this->get('rx_connexion.authService');

        if($authService->isLoggedIn()) {

            $errors = array();
            $materialRequisitionNote_form = $request->get('materialRequisitionNote');
            $em = $this->getDoctrine()->getManager();
            $materialRequisition = $em->getRepository('RxConnexionBundle:MaterialRequisitionEntity')->find($materialRequisitionNote_form['materialRequisition_id']);
            $materialRequisitionNote = $em->getRepository('RxConnexionBundle:MaterialRequisitionNoteEntity')->find($materialRequisitionNote_form['id']);

            if(!$materialRequisitionNote) {
                $materialRequisitionNote = new MaterialRequisitionNoteEntity();
            }

            $formOptions = array(
                'materialRequisition_id' =>  $materialRequisition->getId(),
                'action' => $materialRequisitionNote_form['action'],
            );
            $form = $this->createForm(MaterialRequisitionNoteForm::class, $materialRequisitionNote, $formOptions);

            if($materialRequisitionNote_form['action'] != 'd'){

                if(empty($materialRequisitionNote_form['details'])){
                    $errors[] = 'Details is required.';
                }
            }

            if(!count($errors)) {

                switch($materialRequisitionNote_form['action']) {

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

                            $materialRequisitionNote->setMaterialRequisition($materialRequisition);
                            $em->persist($materialRequisitionNote);
                            $em->flush();

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

                        $result['success'] = true;
                        break;

                    case 'u': // update

                        $materialRequisitionNote_obj = $em->getRepository('RxConnexionBundle:MaterialRequisitionNoteEntity')->find($materialRequisitionNote_form['id']);

                        $materialRequisitionNote_obj->setSubject($materialRequisitionNote_form['subject']);
                        $materialRequisitionNote_obj->setQuantity($materialRequisitionNote_form['details']);
                        $em->flush();

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

                        break;

                        $result['success'] = true;

                    case 'd': // delete

                        $materialRequisitionNote_obj = $em->getRepository('RxConnexionBundle:MaterialRequisitionNoteEntity')->find($materialRequisitionNote_form['id']);
                        $em->remove($materialRequisitionNote_obj);
                        $em->flush();

                        $result['successMessages'] = array('Record Successfully Deleted.');
                        $result['success'] = true;
                        break;
                }



            } else {

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

        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/ajax_list_for_transfer", name="material_requisition_ajax_list_for_transfer")
     */
    public function ajax_list_for_transferAction(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:MaterialRequisitionEntity')->ajax_list_for_transfer($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    private function canvass_po_autoCreate($materialRequisition=null) {

        $canvass = $this->createCanvass($materialRequisition);
        $this->createPurchaseOrder($canvass);
    }
}
