<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ReferringHealthFacilityProviderEntity;
use RxConnexionBundle\Form\ReferringHealthFacilityProviderForm;
use RxConnexionBundle\Form\SalesAgentReferringHealthFacilityForm;
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\ReferringHealthFacilityEntity;
use RxConnexionBundle\Entity\SalesAgentReferringHealthFacilityEntity;

use RxConnexionBundle\Form\ReferringHealthFacilityForm;

/**
 * @Route("/main/referring_health_facility")
 */
class ReferringHealthFacilityController extends Controller
{
    /**
     * @Route("", name="referring_health_facility")
     */
    public function indexAction() {

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

        return $this->render('@RxConnexion/ReferringHealthFacility/index.html.twig', array(
            'title' => 'Manage Referring Affiliate',
            'page_title' => 'Manage Referring Affiliate',
            'javascripts' => array('rxconnexion/admin/js/referringHealthFacility/referringHealthFacility.js?v=1.0.2')
        ));
    }

    /**
     * @Route("/ajax_list", name="referring_health_facility_ajax_list")
     */
    public function ajax_list(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 Referring Health Facility Update'), false);
            $hasDetail = $authService->isUserHasAccesses(array('Admin Referring Health Facility Detail'), false);

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

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

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

                if($hasUpdate) {
                    $url = $this->generateUrl('referring_health_facility_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }
                if($hasDetail){
                    $detailsUrl = $this->generateUrl('referring_health_facility_detail', array(
                        'referringHealthFacility_id' => base64_encode($row['id'])

                    ));
                    $action .= "<a class='action-button-style' href='$detailsUrl'>Details</a>";
                }

                $values = array(
                    $row['company_description'],
                    $row['branch_description'],
                    $row['description'],
                    $row['address'],
                    $row['mobileNos'],
                    $row['phoneNos'],
                    $row['emails'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/ajax_list_for_referral_form", name="referring_health_facility_ajax_list_for_referral")
     */
    public function ajax_list_for_referral_form(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()) {

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

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

                $values = array(
                    $row['company_description'],
                    $row['branch_description'],
                    $row['description'],
                    $row['address'],
                    $row['mobileNos'],
                    $row['phoneNos'],
                    $row['emails'],
                    'DT_DATA' => array(
                        'description' => $row['description'],
                        'company' => $row['company_description'],
                        'branch' => $row['branch_description'],
                        'phoneNo' => $row['phone_no'],
                        'faxNo' => $row['fax_no'],
                        'street' => $row['street'],
                        'cityId' => $row['city_id'],
                        'cityDesc' => $row['city_desc'],
                        'id' => $row['id']

                    )
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_health_facility_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 Referring Health Facility New', 'Admin Referring Health Facility Update'))) return $authService->redirectToHome();

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

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

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

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

            $referringHealthFacility_form = $request->get($form->getName());
            $result = $this->processForm($referringHealthFacility_form, $referringHealthFacility, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('referring_health_facility'), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('referring_health_facility_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('referring_health_facility_form'), 302);
                }
            } else {
                $form->submit($referringHealthFacility_form, false);
            }
        }

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

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

    private function processForm($referringHealthFacility_form, $referringHealthFacility, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->validate($referringHealthFacility_form);

        if(!count($errors)) {

            switch($referringHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Health Facility',
                            $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringHealthFacility;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

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

                    } else {

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

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Referring Health Facility',
                        $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringHealthFacility;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

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

                    } else {

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

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Referring Health Facility',
                        $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringHealthFacility;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringHealthFacility);
                        $referringHealthFacility->setIsDeleted(true);

                        $em->flush();

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

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

                    } else {

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

                    break;
            }

            $result['success'] = true;

        } else {

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

            $result['success'] = false;
        }

        return $result;
    }
    /**
     * @Route(
     *      "/detail/{referringHealthFacility_id}",
     *      name = "referring_health_facility_detail"
     * )
     */
    public function detailAction($referringHealthFacility_id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->find(base64_decode($referringHealthFacility_id));

        $title = 'Manage Referring Affiliate - ' . $referringHealthFacility->getDescription();
        return $this->render('@RxConnexion/ReferringHealthFacility/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/referringHealthFacility/referringHealthFacility_detail.js?v=1.0.0'
            ),
            'referringHealthFacility_id' => $referringHealthFacility_id,
            'referringHealthFacility' => $referringHealthFacility,
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/referring_health_facility_provider_ajax_list", name="referring_health_facility_provider_ajax_list")
     */
    public function referring_health_facility_provider_ajax_list(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 Referring Health Facility Provider Update'), false);

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

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

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

                if($hasUpdate) {
                    $action = "<a class='action-button-style href-referring-provider-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['fullName'],
                    $row['address'],
                    $row['phoneNos'],
                    $row['mobileNos'],
                    $row['emails'],
                    $row['startDate'],
                    $row['endDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/provider/form/{referringHealthFacility_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_health_facility_provider_form"
     * )
     */
    public function referring_health_facility_provider_formAction($referringHealthFacility_id, $action, $id) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'referringHealthFacility_id' => $referringHealthFacility_id
        );
        $form = $this->createForm(ReferringHealthFacilityProviderForm::class, $referringHealthFacilityProvider, $formOptions);


        $title = $action === 'n' ? 'Add Referring Physician' : 'Update ' . $referringHealthFacilityProvider->getReferringProvider()->getFullName();

        $result['html'] =  $this->renderView('@RxConnexion/ReferringHealthFacility/referring_health_facility_provider_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'referringHealthFacility_id' => $referringHealthFacility_id,
            'action' => $action,
            'id' => $id
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/referring_health_facility_provider/save_action",
     *      name = "referring_health_facility_provider_save"
     * )
     */
    public function referring_health_facility_provider_saveAction(Request $request) {

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

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

        $referringHealthFacilityProvider_form = $request->get('referringHealthFacilityProvider');

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityProvider = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->find($referringHealthFacilityProvider_form['id'] );
        if(!$referringHealthFacilityProvider) {
            $referringHealthFacilityProvider = new ReferringHealthFacilityProviderEntity();
        }
        $formOptions = array(
            'action' => $referringHealthFacilityProvider_form['action'],
            'referringHealthFacility_id' => $referringHealthFacilityProvider_form['referringHealthFacility']
        );
        $form = $this->createForm(ReferringHealthFacilityProviderForm::class, $referringHealthFacilityProvider, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->validate($referringHealthFacilityProvider_form);

        if(!count($errors)) {

            switch($referringHealthFacilityProvider_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Health Facility',
                            $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringHealthFacilityProvider;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                    } else {
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Referring Health Facility',
                        $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringHealthFacilityProvider;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    if ($form->isValid()) {

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

                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Referring Health Facility',
                        $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringHealthFacilityProvider;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringHealthFacilityProvider);
                        $referringHealthFacilityProvider->setIsDeleted(true);

                        $em->flush();

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

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Deleted.';

                    } else {

                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;
            }
        } else {

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

    /**
     * @Route("/referring_health_facility_sales_agent_ajax_list", name="referring_health_facility_sales_agent_ajax_list")
     */
    public function referring_health_facility_sales_agent_ajax_list(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 Referring Health Facility Sales Agent Update'), false);

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

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

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

                if($hasUpdate) {
                    $action = "<a class='action-button-style href-referring-sales_agent-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['fullName'],
                    $row['startDate'],
                    $row['endDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/sales_agent/form/{referringHealthFacility_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_health_facility_sales_agent_form"
     * )
     */
    public function referring_health_facility_sales_agent_formAction($referringHealthFacility_id, $action, $id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Referring Health Facility Sales Agent New', 'Admin Referring Health Facility Sales Agent Update'))) return $authService->redirectToHome();

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

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

        $formOptions = array(
            'action' => $action,
            'referringHealthFacility_id' => $referringHealthFacility_id
        );
        $form = $this->createForm(SalesAgentReferringHealthFacilityForm::class, $referringHealthFacilitySalesAgent, $formOptions);


        $title = $action === 'n' ? 'Add Agent' : 'Update ' . $referringHealthFacilitySalesAgent->getSalesAgent()->getAccountUser()->getFullName();

        $result['html'] =  $this->renderView('@RxConnexion/ReferringHealthFacility/referring_health_facility_sales_agent.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'referringHealthFacility_id' => $referringHealthFacility_id,
            'action' => $action,
            'id' => $id
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/referring_health_facility_sales_agent/save_action",
     *      name = "referring_health_facility_sales_agent_save"
     * )
     */
    public function referring_health_facility_sales_agent_saveAction(Request $request) {

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

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Referring Health Facility Sales Agent New', 'Admin Referring Health Facility Sales Agent Update'))) return $authService->redirectToHome();

        $referringHealthFacilitySalesAgent_form = $request->get('referringHealthFacilitySalesAgent');

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilitySalesAgent = $em->getRepository('RxConnexionBundle:SalesAgentReferringHealthFacilityEntity')->find($referringHealthFacilitySalesAgent_form['id'] );

        if(!$referringHealthFacilitySalesAgent) {
            $referringHealthFacilitySalesAgent = new SalesAgentReferringHealthFacilityEntity();
        }

        $formOptions = array(
            'action' => $referringHealthFacilitySalesAgent_form['action'],
            'referringHealthFacility_id' => $referringHealthFacilitySalesAgent_form['referringHealthFacility']
        );
        $form = $this->createForm(SalesAgentReferringHealthFacilityForm::class, $referringHealthFacilitySalesAgent, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:SalesAgentReferringHealthFacilityEntity')->validate($referringHealthFacilitySalesAgent_form);

        if(!count($errors)) {

            switch($referringHealthFacilitySalesAgent_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Health Facility',
                            $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringHealthFacilitySalesAgent_form;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                    } else {
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Referring Health Facility',
                        $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringHealthFacilitySalesAgent_form;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    if ($form->isValid()) {

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

                        $em->flush();

                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Referring Health Facility',
                        $em->getClassMetadata(ReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringHealthFacilitySalesAgent_form;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringHealthFacilitySalesAgent);
                        $referringHealthFacilitySalesAgent->setIsDeleted(true);

                        $em->flush();

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

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Deleted.';

                    } else {

                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;
            }
        } else {

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

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

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

        $result = array(
            'query' => 'cities',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->autocomplete_suggestions($q)
        );

        return new JsonResponse($result);
    }
}
