<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ConvertInventoryItemBiEntity;
use RxConnexionBundle\Entity\ConvertInventoryItemInventorySerialNoEntity;
use RxConnexionBundle\Entity\InventorySerialNoEntity;
use RxConnexionBundle\Entity\ItemEntity;
use RxConnexionBundle\Form\ConvertInventoryItemBiForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

//use RxConnexionBundle\Entity\AuditTrailEntity;

use RxConnexionBundle\Entity\ConvertInventoryEntity;
use RxConnexionBundle\Form\ConvertInventoryForm;

use RxConnexionBundle\Entity\ConvertInventoryItemEntity;
use RxConnexionBundle\Form\ConvertInventoryItemForm;

//use RxConnexionBundle\Entity\ConvertInventoryItemBiEntity;
//use RxConnexionBundle\Form\ConvertInventoryItemBiForm;

use RxConnexionBundle\Entity\ConvertInventoryStatusEntity;

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

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

        return $this->render('@RxConnexion/ConvertInventory/index.html.twig', array(
            'title' => 'Convert Supplies',
            'page_title' => 'Convert Supplies',
            'javascripts' => array('rxconnexion/admin/js/convertInventory/convertInventory.js'),
            'status' => $request->query->get('status')
        ));
    }

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

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

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

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ConvertInventoryEntity')->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 = "convert_inventory_form"
     * )
     */
    public function formAction($action, $id, Request $request) {

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

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

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

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

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

            $convertInventory_form = $request->get($form->getName());
            $result = $this->processForm($convertInventory_form, $convertInventory, $form, $request);

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

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

        return $this->render('@RxConnexion/ConvertInventory/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'javascripts' => array('rxconnexion/admin/js/convertInventory/convertInventory_form.js'),
            'action' => $action,
            'id' => $id
        ));
    }

    private function processForm($convertInventory_form, $convertInventory, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->validate($convertInventory_form);

        if(!count($errors)) {

            switch($convertInventory_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

                        $result['id'] = $convertInventory->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

//                    $convertInventory_obj = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find($convertInventory_form['id']);

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

//                    $branch = $em->getRepository('RxConnexionBundle:BranchEntity')->find($convertInventory_form['branch_id']);
//
//                    $convertInventory_obj->setBranch($branch);
//                    $convertInventory_obj->setConvertDate($convertInventory_form['convert_date']);
//                    $convertInventory_obj->setNote($convertInventory_form['note']);

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $em->flush();

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

                        $result['id'] = $convertInventory->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 'd': // delete

                    $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find($convertInventory_form['id']);
                    $em->remove($convertInventory);

//                    $newAT = new AuditTrailEntity();
//                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                    $newAT->entity = $convertInventory;
//                    $newAT->setRefTable('convert_inventory');
//                    $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(
     *      "/item/index/{convertInventory_id}",
     *      name = "convert_inventory_item"
     * )
     */
    public function itemAction($convertInventory_id) {

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

        $em = $this->getDoctrine()->getManager();
        $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find(base64_decode($convertInventory_id));

//        $canApproveByUser = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->countForApprovalByUser($this->get('session')->get('userData'), 'Pending Admin Approval', $convertInventory->getId());

        return $this->render('@RxConnexion/ConvertInventory/item.html.twig', array(
            'title' => 'Convert Supplies Items',
            'page_title' => 'Convert Supplies Items',
            'javascripts' => array('rxconnexion/admin/js/convertInventory/convertInventoryItem.js?v=1.0.2'),
            'convertInventory_id' => $convertInventory_id,
            'convertInventory' => $convertInventory,
//            'canApproveByUser' => $canApproveByUser
        ));
    }

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

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

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

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

        return new JsonResponse($result);
    }

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

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

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

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

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

            $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find(base64_decode($convertInventory_id));
            $convertInventoryItem = $em->getRepository('RxConnexionBundle:ConvertInventoryItemEntity')->find(base64_decode($id));

            if(!$convertInventoryItem) {
                $convertInventoryItem = new ConvertInventoryItemEntity();
            }

            $formOptions = array(
                'convertInventory_id' => $convertInventory->getId(),
                'action' => $action
            );
            $form = $this->createForm(ConvertInventoryItemForm::class, $convertInventoryItem, $formOptions);

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

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

        return new JsonResponse($result);
    }

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

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

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

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

            $em = $this->getDoctrine()->getManager();
            $convertInventoryItem_form = $request->get('convertInventoryItem');

            /**@var ConvertInventoryItemEntity $convertInventory*/
            /**@var ConvertInventoryEntity $convertInventory*/
            $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find($convertInventoryItem_form['convertInventory']);
            $convertInventoryItem = $em->getRepository('RxConnexionBundle:ConvertInventoryItemEntity')->find($convertInventoryItem_form['id']);

            if(!$convertInventoryItem) {
                $convertInventoryItem = new ConvertInventoryItemEntity();
            }

            $formOptions = array(
                'convertInventory_id' => $convertInventoryItem_form['convertInventory'],
                'action' => $convertInventoryItem_form['action']
            );
            $form = $this->createForm(ConvertInventoryItemForm::class, $convertInventoryItem, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:ConvertInventoryItemEntity')->validate($convertInventoryItem_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

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

//                            $convertInventoryItem->setInventory($inventory);
//                            $convertInventoryItem->setConvertInventory($convertInventory);
                            $em->persist($convertInventoryItem);


                            $inventory_serial_no = $request->get('inventory_serial_no');
                            $serialNos = [];
                            if($inventory_serial_no) {
                                $qty = 0;
                                foreach ($inventory_serial_no as $inventorySerialNo_id) {
                                    /**@var InventorySerialNoEntity $inventorySerialNo */
                                    $inventorySerialNo = $em->getRepository(InventorySerialNoEntity::class)->find($inventorySerialNo_id);
                                    if($inventorySerialNo) {
                                        $qty ++;
                                        $inventorySerialNo->setStatus(InventorySerialNoEntity::STATUS_3);
                                        $convertInventoryItemISN = new ConvertInventoryItemInventorySerialNoEntity();
                                        $convertInventoryItemISN->setInventorySerialNo($inventorySerialNo);
                                        $convertInventoryItemISN->setConvertInventoryItem($convertInventoryItem);
                                        $convertInventoryItem->addConvertInventoryItemInventorySerialNo($convertInventoryItemISN);
                                        $inventorySerialNo->addConvertInventoryItemInventorySerialNo($convertInventoryItemISN);
                                        $em->persist($convertInventoryItemISN);
                                        $serialNos[] = $inventorySerialNo->getSerialNo();
                                    }
                                }
                                $convertInventoryItem->setQuantity($qty);
                            }

                            $item = $convertInventoryItem->getInventory()->getItem();
                            if($item->getIsPackage()) {
                                $itemisedPackageItems = $item->getItemisedPackageItems();
                                /**@var ItemEntity $packageItem*/
                                foreach ($item->getItems() as $packageItem) {
                                    $convertInventoryItemBi = new ConvertInventoryItemBiEntity();
                                    $convertInventoryItemBi->setItem($packageItem);
                                    $convertInventoryItemBi->setQuantity($packageItem->getPackageItemQuantity() * $convertInventoryItem->getQuantity());
                                    $convertInventoryItemBi->setConvertInventory($convertInventory);
                                    $convertInventoryItemBi->setLocation(/*$convertInventory->getHealthFacility()->getLocations()->first()*/null);
                                    if($packageItem->getIsItemised()) {
                                        $convertInventoryItemBi->setSerialNo($itemisedPackageItems->count() == 1 && $packageItem->getPackageItemQuantity() == 1 && count($serialNos) ? implode(',', $serialNos) : null);
                                    }
                                    $em->persist($convertInventoryItemBi);
                                    $convertInventory->addConvertInventoryItemBi($convertInventoryItemBi);
                                }
                            }

                            $em->flush();

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

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

                        break;

                    case 'u': // update

//                        $convertInventoryItem_obj = $em->getRepository('RxConnexionBundle:ConvertInventoryItemEntity')->find($convertInventoryItem_form['id']);

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

//                        $inventory = $em->getRepository('RxConnexionBundle:InventoryEntity')->find($convertInventoryItem_form['inventory_id']);
//
//                        $convertInventoryItem_obj->setInventory($inventory);
//                        $convertInventoryItem_obj->setQuantity($convertInventoryItem_form['quantity']);

//                        $newAT->parseInformation('Update');
//                        $em->persist($newAT);
                        $inventory_serial_no = $request->get('inventory_serial_no');
                        if($inventory_serial_no) {

                            // CHECK FOR REMOVED SERIAL NOs
                            $isn_ids = $inventory_serial_no;
                            foreach ($convertInventoryItem->getConvertInventoryItemInventorySerialNos() as $convertInventoryItemInventorySerialNo) {
                                if (!in_array($convertInventoryItemInventorySerialNo->getInventorySerialNo()->getId(), $isn_ids)) {
                                    $convertInventoryItemInventorySerialNo->getInventorySerialNo()->setStatus(InventorySerialNoEntity::STATUS_1);
                                    $em->remove($convertInventoryItemInventorySerialNo);
                                    $convertInventoryItem->removeConvertInventoryItemInventorySerialNo($convertInventoryItemInventorySerialNo);
                                }
                            }


                            $qty = 0;
                            foreach ($inventory_serial_no as $item) {
                                /**@var InventorySerialNoEntity $isn */
                                $inventorySerialNo = $em->getRepository(InventorySerialNoEntity::class)->find($item);

                                if(is_null($convertInventoryItem->getConvertInventoryItemInventorySerialNoByInventorySerialNoId($item))) {
                                    if ($inventorySerialNo) {
                                        $qty++;
                                        $inventorySerialNo->setStatus(InventorySerialNoEntity::STATUS_3);
                                        $convertInventoryItemISN = new ConvertInventoryItemInventorySerialNoEntity();
                                        $convertInventoryItemISN->setInventorySerialNo($inventorySerialNo);
                                        $convertInventoryItemISN->setConvertInventoryItem($convertInventoryItem);
                                        $convertInventoryItem->addConvertInventoryItemInventorySerialNo($convertInventoryItemISN);
                                        $inventorySerialNo->addConvertInventoryItemInventorySerialNo($convertInventoryItemISN);
                                        $em->persist($convertInventoryItemISN);
                                    }
                                } elseif($inventorySerialNo) {
                                    $qty++;
                                }
                            }
                            $convertInventoryItem->setQuantity($qty);
                        } else {
                            foreach ($convertInventoryItem->getConvertInventoryItemInventorySerialNos() as $convertInventoryItemInventorySerialNo) {
                                $em->remove($convertInventoryItemInventorySerialNo);
                                $convertInventoryItem->removeConvertInventoryItemInventorySerialNo($convertInventoryItemInventorySerialNo);
                            }
                            $convertInventoryItem->setQuantity(0);
                        }

                        $em->flush();

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

                        break;

                    case 'd': // delete

                        $convertInventoryItem = $em->getRepository('RxConnexionBundle:ConvertInventoryItemEntity')->find($convertInventoryItem_form['id']);
                        foreach ($convertInventoryItem->getConvertInventoryItemInventorySerialNos() as $convertInventoryItemInventorySerialNo) {
                            $convertInventoryItemInventorySerialNo->getInventorySerialNo()->setStatus(InventorySerialNoEntity::STATUS_1);
                            $em->remove($convertInventoryItemInventorySerialNo);
                            $convertInventoryItem->removeConvertInventoryItemInventorySerialNo($convertInventoryItemInventorySerialNo);
                        }
                        $em->remove($convertInventoryItem);

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

                        $em->flush();

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

                        break;
                }

                $result['success'] = true;

            } else {

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/bi/ajax_list", name="convert_inventory_item_bi_ajax_list")
     */
    public function item_bi_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:ConvertInventoryItemBiEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/bi/form", name="convert_inventory_item_bi_form")
     */
    public function item_bi_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 Convert Inventory Item New', 'Admin Convert Inventory Item Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

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

            $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find(base64_decode($convertInventory_id));
            $convertInventoryItemBi = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->find(base64_decode($id));

            if (!$convertInventoryItemBi) {
                $convertInventoryItemBi = new ConvertInventoryItemBiEntity();
            }

            $formOptions = array(
                'convertInventory_id' => base64_decode($convertInventory_id),
                'action' => $action
            );
            $form = $this->createForm(ConvertInventoryItemBiForm::class, $convertInventoryItemBi, $formOptions);

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/bi/form_action", name="convert_inventory_item_bi_form_action")
     */
    public function item_bi_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 Convert Inventory Item New', 'Admin Convert Inventory Item Update'))) $result['errorMessages'][] = 'You don\'t have the right to make the action. Please contact the administrator.';

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

            $em = $this->getDoctrine()->getManager();
            $convertInventoryItemBi_form = $request->get('convertInventoryItemBi');

            $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find($convertInventoryItemBi_form['convertInventory']);

            $convertInventoryItemBi = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->find($convertInventoryItemBi_form['id']);
            if (!$convertInventoryItemBi) {
                $convertInventoryItemBi = new ConvertInventoryItemBiEntity();
            }

            $formOptions = array(
                'convertInventory_id' => $convertInventoryItemBi_form['convertInventory'],
                'action' => $convertInventoryItemBi_form['action']
            );
            $form = $this->createForm(ConvertInventoryItemBiForm::class, $convertInventoryItemBi, $formOptions);

            $errors = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->validate($convertInventoryItemBi_form);

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

                    case 'n': // new

                        $form->handleRequest($request);

                        if ($form->isValid()) {

//                            $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find($convertInventoryItemBi_form['item_id']);
//                            $location = $em->getRepository('RxConnexionBundle:LocationEntity')->find($convertInventoryItemBi_form['location_id']);
//
//                            $convertInventoryItemBi->setItem($item);
//                            $convertInventoryItemBi->setLocation($location);
//                            $convertInventoryItemBi->setConvertInventory($convertInventory);
                            $em->persist($convertInventoryItemBi);
                            $em->flush();

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

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

                        break;

                    case 'u': // update

//                        $convertInventoryItemBi_obj = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->find($convertInventoryItemBi_form['id']);
//
//                        $newAT = new AuditTrailEntity();
//                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                        $newAT->entity = $convertInventoryItemBi_obj;
//                        $newAT->setRefTable('convert_inventory_item_bi');
//                        $newAT->parseOriginalDetails();
//
//                        $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find($convertInventoryItemBi_form['item_id']);
//                        $location = $em->getRepository('RxConnexionBundle:LocationEntity')->find($convertInventoryItemBi_form['location_id']);
//
//                        $convertInventoryItemBi_obj->setItem($item);
//                        $convertInventoryItemBi_obj->setLocation($location);
//                        $convertInventoryItemBi_obj->setQuantity($convertInventoryItemBi_form['quantity']);
//
//                        $newAT->parseInformation('Update');
//                        $em->persist($newAT);

                        $em->flush();

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

                        break;

                    case 'd': // delete

//                        $convertInventoryItemBi = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->find($convertInventoryItemBi_form['id']);
                        $em->remove($convertInventoryItemBi);

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

                        $em->flush();

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

                        break;
                }

                $result['success'] = true;

            } else {

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/bi/form/costing", name="convert_inventory_item_bi_form_costing")
     */
    public function item_bi_form_costingAction(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.';

        $em = $this->getDoctrine()->getManager();
        $convertInventory_id = $request->query->get('convertInventory_id');
        $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find(base64_decode($convertInventory_id));

        if($convertInventory->getStatus() != 'Pending Costing') {
            $result['errorMessages'][] = 'This transaction is for Pending Costing status only.';
        }

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

            $result['success'] = true;
            $id = $request->query->get('id');

            $convertInventoryItemBi = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->find(base64_decode($id));

            $title = 'Item: Add Cost';

            $result['html'] = $this->renderView('@RxConnexion/ConvertInventory/item_bi_form_costing.html.twig', array(
                'page_title' => $title,
                'id' => $id,
                'convertInventoryItemBi' => $convertInventoryItemBi
            ));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/item/bi/form/costing_action", name="convert_inventory_item_bi_form_costing_action")
     */
    public function item_bi_form_costing_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.';

        $em = $this->getDoctrine()->getManager();
        $form = $request->get('form');
        $convertInventoryItemBi = $em->getRepository('RxConnexionBundle:ConvertInventoryItemBiEntity')->find(base64_decode($form['id']));

        if($convertInventoryItemBi->getConvertInventory()->getStatus() != 'Pending Costing') {
            $result['errorMessages'][] = 'This transaction is for Pending Costing status only.';
        }

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

            $convertInventoryItemBi->setTotalCost($form['totalCost']);
            $em->flush();

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

        return new JsonResponse($result);
    }

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

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

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

        $em = $this->getDoctrine()->getManager();
        $convertInventory_id = $request->get('convertInventory_id');
        $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find(base64_decode($convertInventory_id));

        $itemCtr = $convertInventory->getItemCtr();
        $itemBiCtr = $convertInventory->getItemBiCtr();

        if(empty($itemCtr) || is_null($itemCtr) || $itemCtr == 0) {
            $result['errorMessages'][] = 'Please enter atleast one(1) raw material.';
        }
        if($convertInventory->getStatus() === 'In Processing' && (empty($itemBiCtr) || is_null($itemBiCtr) || $itemBiCtr == 0)) {
            $result['errorMessages'][] = 'Please enter atleast one(1) bi product.';
        }

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

            $statusChanged = true;

            /*if($convertInventory->getStatus() === 'New' || $convertInventory->getStatus() === 'Rejected') {

                $convertInventory->setApprovalBatchNo($convertInventory->getApprovalBatchNo() + 1);

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

                    $convertInventory->setStatus('Pending Admin Approval');

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

                        $newConvertInventoryStatus = new ConvertInventoryStatusEntity();
                        $newConvertInventoryStatus->setConvertInventory($convertInventory);
                        $newConvertInventoryStatus->setStatus('Pending Admin Approval');
                        $newConvertInventoryStatus->setBatchNo($convertInventory->getApprovalBatchNo());
                        $em->persist($newConvertInventoryStatus);
                    }

                    $em->flush();

                } else {

                    $convertInventory->setStatus('In Processing');
                    $em->flush();
                }

            } else if($convertInventory->getStatus() === 'Approved') {
                $convertInventory->setStatus('In Processing');
            } else if($convertInventory->getStatus() === 'Pending Costing') {
                if($convertInventory->getTotalCost() != $convertInventory->getItemBiTotalCost()) {
                    $result['errorMessages'][] = 'Total cost per item should match the transaction total cost.';
                    $statusChanged = false;
                } else {
                    $convertInventory->setStatus('Completed');
                }
            } else if($itemBiCtr > 1) {
                $convertInventory->setStatus('Pending Costing');
            } else {*/
                $convertInventory->setStatus('Completed');
            //}

            if($statusChanged) {

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

                $inventoryService = $this->get('rx_connexion.inventoryService');
                /*if($convertInventory->getStatus() == 'In Processing') {
                    $inventoryService->recordMovement('Inventory Convert Inventory Send In Processing', array(
                        'convertInventory' => $convertInventory
                    ));
                } else if($convertInventory->getStatus() == 'Pending Costing') {
                    $inventoryService->recordMovement('Inventory Convert Inventory Send Costing', array(
                        'convertInventory' => $convertInventory
                    ));
                } else if($convertInventory->getStatus() == 'Completed') {*/
                    $inventoryService->recordMovement('Inventory Convert Inventory Send Completed', array(
                        'convertInventory' => $convertInventory
                    ));
                //}

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

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

        return new JsonResponse($result);
    }

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

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

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

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

            $convertInventory = $em->getRepository('RxConnexionBundle:ConvertInventoryEntity')->find(base64_decode($convertInventory_id));

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

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

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

                $em->flush();

                $statusApprovalPendingAdminApproval = $em->getRepository('RxConnexionBundle:StatusApprovalEntity')->findOneBy(array('description' => 'Convert Inventory Pending Admin Approval'));

                $approvalCount = 0;

                foreach($convertInventory->getConvertInventoryStatuses() as $convertInventoryStatus) {
                    if($convertInventoryStatus->getBatchNo() === $convertInventory->getApprovalBatchNo() && $convertInventoryStatus->getApprovalDescription() === 'Approved'){
                        $approvalCount++;
                    }
                }

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

                    $convertInventory->setStatus('Approved');
                    $em->flush();
                }

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

            } else {

                $convertInventory->setStatus('Rejected');

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

                $em->flush();

                foreach($convertInventory->getConvertInventoryStatuses() as $convertInventoryStatus) {
                    if($convertInventoryStatus->getBatchNo() === $convertInventory->getApprovalBatchNo() && $convertInventoryStatus->getApprovalDescription() === 'Pending'){
                        $convertInventoryStatus->setApprovalDescription('Cancelled');
                    }
                }

                $em->flush();

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

            return $this->redirect($this->generateUrl('convert_inventory_item', array(
                'convertInventory_id' => $convertInventory_id
            )), 302);

        } else {

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

    /**
     * @Route("/autocomplete", name="convert_inventory_autocomplete")
     */
    public function autocompleteAction(Request $request) {

        $q = $request->get('query');

        $result = array(
            'query' => 'convertInventories',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ConvertInventoryEntity')->autoCompleteSuggestions($q, $this->get('session')->get('userData'))
        );

        return new JsonResponse($result);
    }
}
