<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\MarketingStaffScheduleEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityChartEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityChartNoteEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityFileEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityNoteEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityProviderEntity;
use RxConnexionBundle\Entity\TicketEntity;
use RxConnexionBundle\Form\ReferringHealthFacilityChartForm;
use RxConnexionBundle\Form\ReferringHealthFacilityChartNoteForm;
use RxConnexionBundle\Form\ReferringHealthFacilityFileForm;
use RxConnexionBundle\Form\ReferringHealthFacilityNoteForm;
use RxConnexionBundle\Form\ReferringHealthFacilityProviderForm;
use RxConnexionBundle\Form\ReferringHealthFacilityScheduleForm;
use RxConnexionBundle\Form\SalesAgentReferringHealthFacilityForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;
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()) {

                        if (empty($referringHealthFacility_form['postalCode']) && !empty($referringHealthFacility_form['postalCode_desc'])) {

                            $postalCodeDesc = $referringHealthFacility_form['postalCode_desc'];

                            $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')
                                ->findOneBy([
                                    'description' => $postalCodeDesc,
                                    'isDeleted' => false,
                                ]);

                            if (!$postalCode) {
                                $postalCode = new \RxConnexionBundle\Entity\PostalCodeEntity();
                                $postalCode->setDescription($postalCodeDesc);

                                if (!empty($referringHealthFacility_form['city'])) {
                                    $city = $em->getRepository('RxConnexionBundle:CityEntity')
                                        ->find($referringHealthFacility_form['city']);
                                    if ($city) {
                                        $postalCode->setCity($city);
                                    }
                                }

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


                            $referringHealthFacility->setPostalCode($postalCode);

                        }

                        $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()) {

                        if (empty($referringHealthFacility_form['postalCode']) && !empty($referringHealthFacility_form['postalCode_desc'])) {
                            $postalCodeDesc = $referringHealthFacility_form['postalCode_desc'];

                            $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')
                                ->findOneBy([
                                    'description' => $postalCodeDesc,
                                    'isDeleted' => false,
                                ]);

                            if (!$postalCode) {
                                $postalCode = new \RxConnexionBundle\Entity\PostalCodeEntity();
                                $postalCode->setDescription($postalCodeDesc);

                                if (!empty($referringHealthFacility_form['city'])) {
                                    $city = $em->getRepository('RxConnexionBundle:CityEntity')
                                        ->find($referringHealthFacility_form['city']);
                                    if ($city) {
                                        $postalCode->setCity($city);
                                    }
                                }

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

                            $referringHealthFacility->setPostalCode($postalCode);
                        }

                        $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.1'
            ),
            'referringHealthFacility_id' => $referringHealthFacility_id,
            'referringHealthFacility' => $referringHealthFacility,
            'tab' => $request->query->get('tab'),
            'tab2' => $request->query->get('tab2'),
        ));
    }

    /**
     * @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);
    }

    //ENCOUNTER
    /**
     * @Route("/referring_health_facility_chart_ajax_list", name="referring_health_facility_chart_ajax_list")
     */
    public function referring_health_facility_chart_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 Chart Update'), false);

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

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

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

                if($hasUpdate) {
                    $url = $this->generateUrl('referring_health_facility_chart_form', array(
                        'referring_health_facility_id' => $referringHealthFacilityId,
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $values = array(
                    $row['health_facility_desc'],
                    $row['id'],
                    $row['chart_type_desc'],
                    $row['chart_date'],
                    $row['marketingStaff_fullName'],
                    $row['chart_status_desc'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

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

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

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->find(base64_decode($referring_health_facility_id));
        $referringHealthFacilityChart = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartEntity')->find(base64_decode($id));
        if(!$referringHealthFacilityChart) {
            $referringHealthFacilityChart = new ReferringHealthFacilityChartEntity();
            $chartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array());
            $referringHealthFacilityChart->setChartType($chartType);
        }
        $formOptions = array(
            'action' => $action,
            'referring_health_facility_id' => $referring_health_facility_id
        );
        $form = $this->createForm(ReferringHealthFacilityChartForm::class, $referringHealthFacilityChart, $formOptions);

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

            $referringHealthFacilityChart_form = $request->get($form->getName());
            $result = $this->processReferringHealthFacilityChartForm($referringHealthFacilityChart_form, $referringHealthFacilityChart, $form, $request);

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

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

        return $this->render('@RxConnexion/ReferringHealthFacility/referring_health_facility_chart_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/referringHealthFacility/referring_health_facility_chart_form.js?v=1.0.12'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'referring_health_facility_id' => $referring_health_facility_id,
            'referringHealthFacility' => $referringHealthFacility,
            'referringHealthFacilityChart' => $referringHealthFacilityChart,
            'noteTemplateAccess' => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/referring_health_facility_chart_note_ajax_list", name="referring_health_facility_chart_note_ajax_list")
     */
    public function referring_health_facility_chart_note_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 Chart Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringHealthFacilityChartNoteEntity')->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-health-facility-chart-note-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/referring_health_facility_chart_note/form/{referringHealthFacilityChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_health_facility_chart_note_form"
     * )
     */
    public function referring_health_facility_chart_note_formAction($referringHealthFacilityChart_id, $action, $id) {

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

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityChartNote = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartNoteEntity')->find(base64_decode($id));
        if(!$referringHealthFacilityChartNote) {
            $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
        }

        $formOptions = array(
            'action' => $action,
            'referringHealthFacilityChart_id' => $referringHealthFacilityChart_id
        );
        $form = $this->createForm(ReferringHealthFacilityChartNoteForm::class, $referringHealthFacilityChartNote, $formOptions);


        $title = $action === 'n' ? 'New Note' : 'Update Note';

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

    /**
     * @Route(
     *      "/referring_health_facility_chart_note/save_action",
     *      name = "referring_health_facility_chart_note_save"
     * )
     */
    public function referring_health_facility_chart_note_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 Chart Note New', 'Admin Referring Health Facility Chart Note Update'))) return $authService->redirectToHome();

        $referringHealthFacilityChartNote_form = $request->get('referring_health_facility_chart_note');
        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityChartNote = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartNoteEntity')->find($referringHealthFacilityChartNote_form['id']);
        if(!$referringHealthFacilityChartNote) {
            $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
        }
        $formOptions = array(
            'action' => $referringHealthFacilityChartNote_form['action'],
            'referringHealthFacilityChart_id' => $referringHealthFacilityChartNote_form['referringHealthFacilityChart']
        );
        $form = $this->createForm(ReferringHealthFacilityChartNoteForm::class, $referringHealthFacilityChartNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartNoteEntity')->validate($referringHealthFacilityChartNote_form);

        if(!count($errors)) {

            switch($referringHealthFacilityChartNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {
                        $em->persist($referringHealthFacilityChartNote);
                        $referringHealthFacilityNote = new ReferringHealthFacilityNoteEntity();
                        $referringHealthFacilityNote->setNote('From referring affiliate encounter no. ' . $referringHealthFacilityChartNote->getReferringHealthFacilityChart()->getReferringHealthFacilityChartIdWithLink(). ' - ' . $referringHealthFacilityChartNote->getNote());
                        $referringHealthFacilityNote->setType(ReferringHealthFacilityNoteEntity::TYPE_ENCOUNTER);
                        $referringHealthFacilityNote->setReferringHealthFacility($referringHealthFacilityChartNote->getReferringHealthFacilityChart()->getReferringHealthFacility());
                        $em->persist($referringHealthFacilityNote);
                        $em->flush();
//
//                        $newAT = new AuditTrailEntity(
//                            'ReferringHealthFacility Chart Note',
//                            $em->getClassMetadata(ReferringHealthFacilityChartNoteEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $referringHealthFacilityNote;
//                        $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();
                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                    $newAT->entity = $referringHealthFacilityChartNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseOriginalDetails();*/
                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        $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();
                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                    $newAT->entity = $referringHealthFacilityChartNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseInformation('Delete');
                    $em->persist($newAT);*/

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringHealthFacilityChartNote);
                        $referringHealthFacilityChartNote->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);
    }

    private function processReferringHealthFacilityChartForm($referringHealthFacilityChart_form, $referringHealthFacilityChart, $form, Request $request) {
        $oldStatus = $referringHealthFacilityChart->getChartStatus() ? $referringHealthFacilityChart->getChartStatus()->getDescription() : '';
        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartEntity')->validate($referringHealthFacilityChart_form);

        if(!count($errors)) {

            switch($referringHealthFacilityChart_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        $chartType = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ChartTypeEntity')->find($referringHealthFacilityChart_form['chart_type']);
//                        if($chartType->getDescription() == 'HSAT') {
//                            $referringHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->find(base64_decode($referringHealthFacilityChart_form['referringHealthFacility']));
//                            $referringHealthFacility->setPrimaryHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity', $referringHealthFacilityChart_form['health_facility']));
//                            $em->persist($referringHealthFacility);
//                        }

                        $em->persist($referringHealthFacilityChart);
                        if(isset($referringHealthFacilityChart_form['is_endorsed']) && $referringHealthFacilityChart_form['is_endorsed']  != 0) {
                            $ticket = new TicketEntity();
                            $ticket->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $referringHealthFacilityChart_form['account_user_endorsed_by']));
                            $ticket->setTicketStatus($em->getReference('RxConnexionBundle:TicketStatusEntity' ,$referringHealthFacilityChart_form['ticket_status_id']));
                            $ticket->setTicketSeverity($em->getReference('RxConnexionBundle:TicketSeverityEntity', $referringHealthFacilityChart_form['ticket_severity_id']));
                            $em->persist($ticket);
//                            $referringHealthFacilityChartTicket = new ReferringHealthFacilityChartTicketEntity();
//                            $referringHealthFacilityChartTicket->setTicket($ticket);
//                            $referringHealthFacilityChartTicket->setReferringHealthFacilityChart($referringHealthFacilityChart);
//                            $em->persist($referringHealthFacilityChartTicket);

                            //insert ticket note
                            if($referringHealthFacilityChart_form['note'] != null || $referringHealthFacilityChart_form['note'] != ''){
                                $ticketNote = new TicketNoteEntity();
                                $ticketNote->setTicket($ticket);
                                $ticketNote->setNote($referringHealthFacilityChart_form['note']);
                                $em->persist($ticketNote);
                            }
                        }

                        //insert notes on referring health_facility and referring health_facility
                        if($referringHealthFacilityChart_form['note'] != null || $referringHealthFacilityChart_form['note'] != ''){
                            $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
                            $referringHealthFacilityChartNote->setNote($referringHealthFacilityChart->getNote());
                            $referringHealthFacilityChartNote->setReferringHealthFacilityChart($referringHealthFacilityChart);
                            $em->persist($referringHealthFacilityChartNote);
                        }

                        $em->flush();

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

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

                        $result['redirect'] = 'index';
                        $result['id'] = $referringHealthFacilityChart->getId();

                    } else {

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

                    break;

                case 'u': // update

//                    $chartType = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ChartTypeEntity')->find($referringHealthFacilityChart_form['chart_type']);
//                    if($chartType->getDescription() == 'HSAT') {
//                        $referringHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityEntity')->find(base64_decode($referringHealthFacilityChart_form['referringHealthFacility']));
//                        $referringHealthFacility->setPrimaryHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity', $referringHealthFacilityChart_form['health_facility']));
//                        $em->persist($referringHealthFacility);
//                    }

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

                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        $newStatus = $referringHealthFacilityChart->getChartStatus()->getDescription();
                        $newAT->parseDetails();
                        $em->persist($newAT);

                        if($oldStatus != $newStatus){
                            $schedule = $referringHealthFacilityChart->getMarketingStaffSchedule();
                            if($schedule){
                                $scheduleStatus = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleStatusEntity')->findOneBy(array('description' => $newStatus));
                                if($scheduleStatus){
                                    $schedule->setMarketingStaffScheduleStatus($scheduleStatus);
                                }else{
                                    $scheduleStatus = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleStatusEntity')->findOneBy(array('isLast' => true));
                                    $schedule->setMarketingStaffScheduleStatus($scheduleStatus);
                                }
                            }
                        }
                        if($referringHealthFacilityChart_form['note'] != null || $referringHealthFacilityChart_form['note'] != ''){
                            $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
                            $referringHealthFacilityChartNote->setNote($referringHealthFacilityChart->getNote());
                            $referringHealthFacilityChartNote->setReferringHealthFacilityChart($referringHealthFacilityChart);
                            $em->persist($referringHealthFacilityChartNote);
                        }
                        $em->flush();

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

                        $result['redirect'] = 'index';
                        $result['id'] = $referringHealthFacilityChart->getId();

                    } 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 Encounter',
                        $em->getClassMetadata(ReferringHealthFacilityChartEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringHealthFacilityChart;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

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

                    } 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("/referring_health_facility_file_ajax_list", name="referring_health_facility_file_ajax_list")
     */
    public function referring_health_facility_file_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 File Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringHealthFacilityFileEntity')->ajax_list($get, $this->get('session')->get('userData'));
            //$data2 = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringHealthFacilityChartFileEntity')->manage_referring_health_facility_ajax_list($get, $this->get('session')->get('userData'));

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

                $id = base64_encode($row['id']);
                $referring_health_facility_id = $get['referring_health_facility_id'];
                $action = '';
                $url = $this->generateUrl('referring_health_facility_file_download', array(
                    'referringHealthFacilityFile_id' => $id
                ));

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

                $values = array(
                    $row['date'],
                    $row['user'],
                    "<a href='$url'>". $row['description'] . "</a>" ,
                    $row['fileType_desc'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

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

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

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

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

        $formOptions = array(
            'action' => $action,
            'referring_health_facility_id' => $referring_health_facility_id
        );
        $form = $this->createForm(ReferringHealthFacilityFileForm::class, $referringHealthFacilityFile, $formOptions);


        $title = $action === 'n' ? 'Add File' : 'Update ' . 'Referring Health Facility File:' . $referringHealthFacilityFile->getId();

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

    /**
     * @Route(
     *      "/referring_health_facility_file/save_action",
     *      name = "referring_health_facility_file_save"
     * )
     */
    public function referring_health_facility_file_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 File New', 'Admin Referring Health Facility File Update'))) return $authService->redirectToHome();

        $referringHealthFacilityFile_form = $request->get('referringHealthFacility_file');
        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityFile = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityFileEntity')->find($referringHealthFacilityFile_form['id'] );
        if(!$referringHealthFacilityFile) {
            $referringHealthFacilityFile = new ReferringHealthFacilityFileEntity();
        }
        $formOptions = array(
            'action' => $referringHealthFacilityFile_form['action'],
            'referring_health_facility_id' => $referringHealthFacilityFile_form['referringHealthFacility']
        );
        $form = $this->createForm(ReferringHealthFacilityFileForm::class, $referringHealthFacilityFile, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityFileEntity')->validate($referringHealthFacilityFile_form);

        if(!count($errors)) {

            switch($referringHealthFacilityFile_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $em->persist($referringHealthFacilityFile);
                        $em->flush();
                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {

                            $filesystem = new Filesystem();
                            if (!is_dir("uploads/referringHealthFacility/files")) {
                                $filesystem->mkdir("uploads/referringHealthFacility/files", 0755);
                            }

                            $baseName = $referringHealthFacilityFile->getId() . '-' . time() . '.' . pathinfo($_FILES['form']['name']['file'], PATHINFO_EXTENSION);
                            $uploadFile = $referringHealthFacilityFile->getUploadRootDir() . '/' . $baseName;

                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $referringHealthFacilityFile->removeFile();
                                $referringHealthFacilityFile->setDescription($_FILES['form']['name']['file']);
                                $referringHealthFacilityFile->setParsedDescription($baseName);
                                $em->flush();

                            }
                        }

                        $newAT = new AuditTrailEntity(
                            'Referring Health Facility File',
                            $em->getClassMetadata(ReferringHealthFacilityFileEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringHealthFacilityFile;
                        $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 File',
                        $em->getClassMetadata(ReferringHealthFacilityFileEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringHealthFacilityFile;
                    $newAT->parseOriginalDetails();

                    $referringHealthFacilityFile_obj = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityFileEntity')->find($referringHealthFacilityFile_form['id']);
                    $form->handleRequest($request);
                    if ($form->isValid()) {

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

                        $em->flush();

                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {

                            $filesystem = new Filesystem();
                            if (!is_dir("uploads/referringHealthFacility/files")) {
                                $filesystem->mkdir("uploads/referringHealthFacility/files", 0755);
                            }

                            $baseName = $referringHealthFacilityFile_obj->getId() . '-' . time() . '.' . pathinfo($_FILES['form']['name']['file'], PATHINFO_EXTENSION);
                            $uploadFile = $referringHealthFacilityFile_obj->getUploadRootDir() . '/' . $baseName;

                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $referringHealthFacilityFile_obj->removeFile();
                                $referringHealthFacilityFile_obj->setDescription($_FILES['form']['name']['file']);
                                $referringHealthFacilityFile_obj->setParsedDescription($baseName);
                                $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 File',
                        $em->getClassMetadata(ReferringHealthFacilityFileEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringHealthFacilityFile;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringHealthFacilityFile);
                        $referringHealthFacilityFile->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_schedule_ajax_list", name="referring_health_facility_schedule_ajax_list")
     */
    public function referring_health_facility_schedule_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 Schedule Update'), false);

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

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

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


                if($hasUpdate) {
                    $url = $this->generateUrl('referring_health_facility_schedule_form', array(
                        'referring_health_facility_id' =>$get['referring_health_facility_id'],
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action .= "<a class='action-button-style' href='$url'>Update</a>";
                }

                $values = array(
                    $row['id'],
                    $row['health_facility_desc'],
                    $row['schedule_date'],
                    $row['marketingStaff_desc'],
                    $row['chart_type_desc'],
                    $row['start_time'],
                    $row['end_time'],
                    $row['schedule_status_desc'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/schedule_form/{referring_health_facility_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_health_facility_schedule_form"
     * )
     */
    public function schedule_formAction($referring_health_facility_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'referring_health_facility_id' => $referring_health_facility_id,
            'action' => $action
        );
        $form = $this->createForm(ReferringHealthFacilityScheduleForm::class, $schedule, $formOptions);

        if($request->getMethod() === 'POST') {
            $schedule_form = $request->get($form->getName());
            $result = $this->scheduleProcessForm($schedule_form, $schedule, $form, $request);
            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('referring_health_facility_detail',array(
                        'referringHealthFacility_id' => $referring_health_facility_id,
                        'tab' => 'ap'
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('referring_health_facility_schedule_form', array(
                        'referring_health_facility_id' => $referring_health_facility_id,
                        'action' => 'u',
                        'id' => base64_encode($result['id']),
                        'tab' => 'ap'
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('referring_health_facility_schedule_form'), 302);
                }
            } else {
                $form->submit($schedule_form, false);
            }

        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' Schedule - ' . $referringHealthFacility->getDescription();

        return $this->render('@RxConnexion/ReferringHealthFacility/schedule_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/referringHealthFacility/referring_health_facility_schedule_form.js?v=1.0.5'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'referring_health_facility_id' => $referring_health_facility_id,
            'form2' =>  isset($form2) ? $form2->createView() : array()
        ));
    }

    private function scheduleProcessForm($schedule_form, $schedule, $form, Request $request) {
        $oldNotes = $schedule->getNote();
        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleEntity')->validate($schedule_form);

        if(!count($errors)) {

            switch($schedule_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $chartStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findOneBy(array(
                            'description' => $schedule->getMarketingStaffScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));
                        $em->persist($schedule);
                        $referringHealthFacilityChart = new ReferringHealthFacilityChartEntity();
                        $referringHealthFacilityChart->setMarketingStaffSchedule($schedule);
                        $referringHealthFacilityChart->setHealthFacility($schedule->getHealthFacility());
                        $referringHealthFacilityChart->setMarketingStaff($schedule->getMarketingStaff());
                        $referringHealthFacilityChart->setReferringHealthFacility($schedule->getReferringHealthFacility());
                        $referringHealthFacilityChart->setChartType($schedule->getChartType());
                        if($chartStatus){
                            $referringHealthFacilityChart->setChartStatus($chartStatus);
                        }
                        $referringHealthFacilityChart->setChartDate($schedule->getScheduleDateAsString());
                        $em->persist($referringHealthFacilityChart);
                        $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
                        $referringHealthFacilityChartNote->setReferringHealthFacilityChart($referringHealthFacilityChart);
                        $referringHealthFacilityChartNote->setNote($schedule->getNote());
                        $em->persist($referringHealthFacilityChartNote);
                        $referringHealthFacilityNote = new ReferringHealthFacilityNoteEntity();
                        $referringHealthFacilityNote->setReferringHealthFacility($schedule->getReferringHealthFacility());
                        $referringHealthFacilityNote->setType($schedule_form['note_type']);
                        $referringHealthFacilityNote->setNote($schedule->getNote());
                        $em->persist($referringHealthFacilityNote);
                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Marketing Staff Schedule',
                            $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $schedule;
                        $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(
                        'Marketing Staff Schedule',
                        $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $schedule;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $referringHealthFacilityChart = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartEntity')->findOneBy(array(
                            'marketingStaffSchedule' => $schedule->getId()
                        ));

                        $referringHealthFacilityChart->setHealthFacility($schedule->getHealthFacility());
                        $referringHealthFacilityChart->setMarketingStaff($schedule->getMarketingStaff());
                        $referringHealthFacilityChart->setReferringHealthFacility($schedule->getReferringHealthFacility());
                        $referringHealthFacilityChart->setChartType($schedule->getChartType());
                        if($referringHealthFacilityChart->getChartStatus()){
                            $scheduleStatus = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleStatusEntity')->findOneBy(array(
                                'description' => $referringHealthFacilityChart->getChartStatus()->getDescription()
                            ));
                        }else{
                            $scheduleStatus = array();
                        }

                        $chartStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findOneBy(array(
                            'description' => $schedule->getMarketingStaffScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));
                        if($chartStatus && $scheduleStatus){
                            $referringHealthFacilityChart->setChartStatus($chartStatus);
                        }
                        if($schedule->getNote() != $oldNotes){
                            $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
                            $referringHealthFacilityChartNote->setReferringHealthFacilityChart($referringHealthFacilityChart);
                            $referringHealthFacilityChartNote->setNote($schedule->getNote());
                            $em->persist($referringHealthFacilityChartNote);
                            $referringHealthFacilityNote = new ReferringHealthFacilityNoteEntity();
                            $referringHealthFacilityNote->setReferringHealthFacility($schedule->getReferringHealthFacility());
                            $referringHealthFacilityNote->setType($schedule_form['note_type']);
                            $referringHealthFacilityNote->setNote($schedule->getNote());
                            $em->persist($referringHealthFacilityNote);
                        }
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

//                        if(isset($schedule_form['faxCoverSelection'])){
//                            $faxCoverSelection = implode(',' , $schedule_form['faxCoverSelection']);
//                            $schedule->setFaxCoverSelection($faxCoverSelection);
//                        }
//                        if(isset($schedule_form['faxBodySelection'])){
//                            $faxBodySelection = implode(',' , $schedule_form['faxBodySelection']);
//                            $schedule->setFaxBodySelection($faxBodySelection);
//                        }

                        $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(
                        'Marketing Staff Schedule',
                        $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $schedule;
                    $newAT->parseDetails();
                    $em->persist($newAT);
                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($schedule);
                        $schedule->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("/referring_health_facility_note_ajax_list", name="referring_health_facility_note_ajax_list")
     */
    public function referring_health_facility_note_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 Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringHealthFacilityNoteEntity')->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-health-facility-note-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['type'],
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/referring_health_facility_note_clinical_ajax_list", name="referring_health_facility_note_clinical_ajax_list")
     */
    public function referring_health_facility_note_clinical_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 Note Update'), false);

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

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

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

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

                $values = array(
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/referring_health_facility_note_billing_ajax_list", name="referring_health_facility_note_billing_ajax_list")
     */
    public function referring_health_facility_note_billing_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 Note Update'), false);

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

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

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

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

                $values = array(
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/referring_health_facility_note_appointment_ajax_list", name="referring_health_facility_note_appointment_ajax_list")
     */
    public function referring_health_facility_note_appointment_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 Note Update'), false);

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

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

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

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

                $values = array(
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/referring_health_facility_note_specialist_ajax_list", name="referring_health_facility_note_specialist_ajax_list")
     */
    public function referring_health_facility_note_specialist_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 Note Update'), false);

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

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

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

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

                $values = array(
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/referring_health_facility_note_letter_ajax_list", name="referring_health_facility_note_letter_ajax_list")
     */
    public function referring_health_facility_note_letter_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 Note Update'), false);

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

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

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

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

                $values = array(
                    $row['created_at'],
                    $row['created_by'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/referring_health_facility_note/form/{referring_health_facility_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_health_facility_note_form"
     * )
     */
    public function referring_health_facility_note_formAction($referring_health_facility_id, $action, $id) {

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

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityNote = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityNoteEntity')->find(base64_decode($id));
        if(!$referringHealthFacilityNote) {
            $referringHealthFacilityNote = new ReferringHealthFacilityNoteEntity();
        }

        $formOptions = array(
            'action' => $action,
            'referring_health_facility_id' => $referring_health_facility_id
        );
        $form = $this->createForm(ReferringHealthFacilityNoteForm::class, $referringHealthFacilityNote, $formOptions);


        $title = $action === 'n' ? 'New Note' : 'Update Note';

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

    /**
     * @Route(
     *      "/referring_health_facility_note/save_action",
     *      name = "referring_health_facility_note_save"
     * )
     */
    public function referring_health_facility_note_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 Note New', 'Admin Referring Health Facility Note Update'))) return $authService->redirectToHome();

        $referringHealthFacilityNote_form = $request->get('referringHealthFacility_note');
        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityNote = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityNoteEntity')->find($referringHealthFacilityNote_form['id']);
        if(!$referringHealthFacilityNote) {
            $referringHealthFacilityNote = new ReferringHealthFacilityNoteEntity();
        }
        $formOptions = array(
            'action' => $referringHealthFacilityNote_form['action'],
            'referring_health_facility_id' => $referringHealthFacilityNote_form['referringHealthFacility']
        );
        $form = $this->createForm(ReferringHealthFacilityNoteForm::class, $referringHealthFacilityNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityNoteEntity')->validate($referringHealthFacilityNote_form);

        if(!count($errors)) {

            switch($referringHealthFacilityNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        $newAT = new AuditTrailEntity(
                            'Referring Health Facility Note',
                            $em->getClassMetadata(ReferringHealthFacilityNoteEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringHealthFacilityNote;
                        $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 Note',
                        $em->getClassMetadata(ReferringHealthFacilityNoteEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringHealthFacilityNote;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        /*$referringHealthFacilityNote->setType(ReferringHealthFacilityNoteEntity::TYPE_CLINICAL);*/
                        $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 Note',
                        $em->getClassMetadata(ReferringHealthFacilityNoteEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringHealthFacilityNote;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringHealthFacilityNote);
                        $referringHealthFacilityNote->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(
     *      "/file/download/{referringHealthFacilityFile_id}",
     *
     *      name = "referring_health_facility_file_download"
     * )
     */
    public function referring_health_facility_file_downloadAction($referringHealthFacilityFile_id){

        $em = $this->getDoctrine()->getManager();
        $referringHealthFacilityFile = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityFileEntity')->find(base64_decode($referringHealthFacilityFile_id));
        header('Content-Disposition: attachment; filename="' . $referringHealthFacilityFile->getDescription() . '"');

        $fileName = $referringHealthFacilityFile->getParsedDescription();
        $uploadDir = $referringHealthFacilityFile->getUploadRootDir() ;

        $handle = fopen(realpath($uploadDir) . '/' . $fileName, 'rb');

        $chunkSize = 1024*1024;

        if($handle !== false) {

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

            fclose($handle);
        }

        exit();
    }

    /**
     * @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);
    }
}
