<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\MarketingStaffScheduleEntity;
use RxConnexionBundle\Entity\ReferringProviderChartEntity;
use RxConnexionBundle\Entity\ReferringProviderChartNoteEntity;
use RxConnexionBundle\Entity\ReferringProviderFileEntity;
use RxConnexionBundle\Entity\ReferringProviderNoteEntity;
use RxConnexionBundle\Entity\TicketEntity;
use RxConnexionBundle\Entity\TicketNoteEntity;
use RxConnexionBundle\Form\ReferringProviderChartForm;
use RxConnexionBundle\Form\ReferringProviderChartNoteForm;
use RxConnexionBundle\Form\ReferringProviderFileForm;
use RxConnexionBundle\Form\ReferringProviderNoteForm;
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\ReferringProviderEntity;
use RxConnexionBundle\Entity\ReferringProviderHealthFacilityEntity;

use RxConnexionBundle\Form\ReferringProviderHealthFacilityForm;
use RxConnexionBundle\Form\ReferringProviderForm;
use RxConnexionBundle\Form\ReferringProviderScheduleForm;

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

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

        return $this->render('@RxConnexion/ReferringProvider/index.html.twig', array(
            'title' => 'Manage Referring Physician',
            'page_title' => 'Manage Referring Physician',
            'javascripts' => array('rxconnexion/admin/js/referringProvider/referringProvider.js?v=1.0.1')
        ));
    }

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

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

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

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

                if($hasDetail) {
                    $url = $this->generateUrl('referring_provider_detail', array(
                        'referringProvider_id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Details</a>";
                }

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['phoneNos'],
                    $row['mobileNos'],
                    $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_provider_ajax_list_for_referral_form")
     */
    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:ReferringProviderEntity')->ajax_list_for_referral_form($get, $this->get('session')->get('userData'));

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['phoneNos'],
                    $row['mobileNos'],
                    $row['emails'],
                    'DT_DATA' => array(
                        'firstName' =>$row['first_name'],
                        'middleName' =>$row['middle_name'],
                        'lastName' =>$row['last_name'],
                        'gender' =>$row['gender'],
                        '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_provider_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 Provider New', 'Admin Referring Provider Update'))) return $authService->redirectToHome();

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

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

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

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

            $referringReferringProvider_form = $request->get($form->getName());
            $result = $this->processForm($referringReferringProvider_form, $referringReferringProvider, $form, $request);

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

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

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

    private function processForm($referringReferringProvider_form, $referringReferringProvider, $form, Request $request) {

        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->validate($referringReferringProvider_form);

        if(!count($errors)) {

            switch($referringReferringProvider_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Provider',
                            $em->getClassMetadata(ReferringProviderEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringReferringProvider;
                        $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 Provider',
                        $em->getClassMetadata(ReferringProviderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringReferringProvider;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

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

                    } else {

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

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Referring Provider',
                        $em->getClassMetadata(ReferringProviderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringReferringProvider;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringReferringProvider);
                        $referringReferringProvider->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/{referringProvider_id}",
     *      name = "referring_provider_detail"
     * )
     */
    public function detailAction($referringProvider_id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find(base64_decode($referringProvider_id));

        $title = 'Manage Referring Physician - ' . $referringProvider->getFullName();
        return $this->render('@RxConnexion/ReferringProvider/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/referringProvider/referringProvider_detail.js?v=1.0.2'
            ),
            'referringProvider_id' => $referringProvider_id,
            'referringProvider' => $referringProvider,
            'tab' => $request->query->get('tab'),
            'tab2' => $request->query->get('tab2'),
        ));
    }

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

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

                $values = array(
                    $row['company_description'],
                    $row['branch_description'],
                    $row['description'],
                    $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(
     *      "/referring_health_facility/form/{referringProvider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_health_facilities_form"
     * )
     */
    public function referring_provider_health_facilities_formAction($referringProvider_id, $action, $id) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'referringProvider_id' => $referringProvider_id
        );
        $form = $this->createForm(ReferringProviderHealthFacilityForm::class, $referringProviderHealthFacility, $formOptions);


        $title = $action === 'n' ? 'Add Referring Medical Facility' : 'Update ' . $referringProviderHealthFacility->getReferringHealthFacility()->getDescription()    ;

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

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

        $referringProviderHealthFacility_form = $request->get('referringProviderHealthFacility');
        $em = $this->getDoctrine()->getManager();
        $referringProviderHealthFacility = $em->getRepository('RxConnexionBundle:ReferringProviderHealthFacilityEntity')->find($referringProviderHealthFacility_form['id'] );
        if(!$referringProviderHealthFacility) {
            $referringProviderHealthFacility = new ReferringProviderHealthFacilityEntity();
        }
        $formOptions = array(
            'action' => $referringProviderHealthFacility_form['action'],
            'referringProvider_id' => $referringProviderHealthFacility_form['referringProvider']
        );
        $form = $this->createForm(ReferringProviderHealthFacilityForm::class, $referringProviderHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderHealthFacilityEntity')->validate($referringProviderHealthFacility_form);

        if(!count($errors)) {

            switch($referringProviderHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Provider Health Facility',
                            $em->getClassMetadata(ReferringProviderHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringProviderHealthFacility;
                        $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 Provider Health Facility',
                        $em->getClassMetadata(ReferringProviderHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringProviderHealthFacility;
                    $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 Provider Health Facility',
                        $em->getClassMetadata(ReferringProviderHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringProviderHealthFacility;
                    $newAT->parseDetails();
                    $em->persist($newAT);


                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringProviderHealthFacility);
                        $referringProviderHealthFacility->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_provider_chart_ajax_list", name="referring_provider_chart_ajax_list")
     */
    public function referring_provider_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 Provider Chart Update'), false);

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

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

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

                if($hasUpdate) {
                    $url = $this->generateUrl('referring_provider_chart_form', array(
                        'referring_provider_id' => $referringProviderId,
                        '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_provider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_chart_form"
     * )
     */
    public function referring_provider_chart_formAction($referring_provider_id, $action, $id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find(base64_decode($referring_provider_id));
        $referringProviderChart = $em->getRepository('RxConnexionBundle:ReferringProviderChartEntity')->find(base64_decode($id));
        if(!$referringProviderChart) {
            $referringProviderChart = new ReferringProviderChartEntity();
            $chartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array());
            $referringProviderChart->setChartType($chartType);
        }
        $formOptions = array(
            'action' => $action,
            'referring_provider_id' => $referring_provider_id
        );
        $form = $this->createForm(ReferringProviderChartForm::class, $referringProviderChart, $formOptions);

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

            $referringProviderChart_form = $request->get($form->getName());
            $result = $this->processReferringHealthFacilityChartForm($referringProviderChart_form, $referringProviderChart, $form, $request);

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

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

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

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

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderChartNoteEntity')->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-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_provider_chart_note/form/{referringProviderChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_chart_note_form"
     * )
     */
    public function referring_provider_chart_note_formAction($referringProviderChart_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'referringProviderChart_id' => $referringProviderChart_id
        );
        $form = $this->createForm(ReferringProviderChartNoteForm::class, $referringProviderChartNote, $formOptions);


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

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

    /**
     * @Route(
     *      "/referring_provider_chart_note/save_action",
     *      name = "referring_provider_chart_note_save"
     * )
     */
    public function referring_provider_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 Provider Chart Note New', 'Admin Referring Provider Chart Note Update'))) return $authService->redirectToHome();

        $referringProviderChartNote_form = $request->get('referring_provider_chart_note');
        $em = $this->getDoctrine()->getManager();
        $referringProviderChartNote = $em->getRepository('RxConnexionBundle:ReferringProviderChartNoteEntity')->find($referringProviderChartNote_form['id']);
        if(!$referringProviderChartNote) {
            $referringProviderChartNote = new ReferringProviderChartNoteEntity();
        }
        $formOptions = array(
            'action' => $referringProviderChartNote_form['action'],
            'referringProviderChart_id' => $referringProviderChartNote_form['referringProviderChart']
        );
        $form = $this->createForm(ReferringProviderChartNoteForm::class, $referringProviderChartNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderChartNoteEntity')->validate($referringProviderChartNote_form);

        if(!count($errors)) {

            switch($referringProviderChartNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {
                        $em->persist($referringProviderChartNote);
                        $referringProviderNote = new ReferringProviderNoteEntity();
                        $referringProviderNote->setNote('From referring physician encounter no. ' . $referringProviderChartNote->getReferringProviderChart()->getReferringProviderChartIdWithLink(). ' - ' . $referringProviderChartNote->getNote());
                        $referringProviderNote->setType(ReferringProviderNoteEntity::TYPE_ENCOUNTER);
                        $referringProviderNote->setReferringProvider($referringProviderChartNote->getReferringProviderChart()->getReferringProvider());
                        $em->persist($referringProviderNote);
                        $em->flush();
//
//                        $newAT = new AuditTrailEntity(
//                            'ReferringProvider Chart Note',
//                            $em->getClassMetadata(ReferringProviderChartNoteEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $referringProviderNote;
//                        $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 = $referringProviderChartNote;
                    $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 = $referringProviderChartNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseInformation('Delete');
                    $em->persist($newAT);*/

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringProviderChartNote);
                        $referringProviderChartNote->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($referringProviderChart_form, $referringProviderChart, $form, Request $request) {
        $oldStatus = $referringProviderChart->getChartStatus() ? $referringProviderChart->getChartStatus()->getDescription() : '';
        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderChartEntity')->validate($referringProviderChart_form);

        if(!count($errors)) {

            switch($referringProviderChart_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);
                    if ($form->isValid()) {
//                        $chartType = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ChartTypeEntity')->find($referringProviderChart_form['chart_type']);
//                        if($chartType->getDescription() == 'HSAT') {
//                            $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find(base64_decode($referringProviderChart_form['referringProvider']));
//                            $referringProvider->setPrimaryProvider($em->getReference('RxConnexionBundle:ProviderEntity', $referringProviderChart_form['provider']));
//                            $em->persist($referringProvider);
//                        }

                        $em->persist($referringProviderChart);
                        if(isset($referringProviderChart_form['is_endorsed']) && $referringProviderChart_form['is_endorsed']  != 0) {
                            $ticket = new TicketEntity();
                            $ticket->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $referringProviderChart_form['account_user_endorsed_by']));
                            $ticket->setTicketStatus($em->getReference('RxConnexionBundle:TicketStatusEntity' ,$referringProviderChart_form['ticket_status_id']));
                            $ticket->setTicketSeverity($em->getReference('RxConnexionBundle:TicketSeverityEntity', $referringProviderChart_form['ticket_severity_id']));
                            $em->persist($ticket);
//                            $referringProviderChartTicket = new ReferringProviderChartTicketEntity();
//                            $referringProviderChartTicket->setTicket($ticket);
//                            $referringProviderChartTicket->setReferringProviderChart($referringProviderChart);
//                            $em->persist($referringProviderChartTicket);

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

                        //insert notes on referring provider and referring provider
                        if($referringProviderChart_form['note'] != null || $referringProviderChart_form['note'] != ''){
                            $referringProviderChartNote = new ReferringProviderChartNoteEntity();
                            $referringProviderChartNote->setNote($referringProviderChart->getNote());
                            $referringProviderChartNote->setReferringProviderChart($referringProviderChart);
                            $em->persist($referringProviderChartNote);
                        }

                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Referring Provider Encounter',
                            $em->getClassMetadata(ReferringProviderChartEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringProviderChart;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                        $result['redirect'] = 'index';
                        $result['id'] = $referringProviderChart->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($referringProviderChart_form['chart_type']);
//                    if($chartType->getDescription() == 'HSAT') {
//                        $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find(base64_decode($referringProviderChart_form['referringProvider']));
//                        $referringProvider->setPrimaryProvider($em->getReference('RxConnexionBundle:ProviderEntity', $referringProviderChart_form['provider']));
//                        $em->persist($referringProvider);
//                    }

                    $newAT = new AuditTrailEntity(
                        'Referring Provider Encounter',
                        $em->getClassMetadata(ReferringProviderChartEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringProviderChart;
                    $newAT->parseOriginalDetails();

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

                        if($oldStatus != $newStatus){
                            $schedule = $referringProviderChart->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($referringProviderChart_form['note'] != null || $referringProviderChart_form['note'] != ''){
                            $referringProviderChartNote = new ReferringProviderChartNoteEntity();
                            $referringProviderChartNote->setNote($referringProviderChart->getNote());
                            $referringProviderChartNote->setReferringProviderChart($referringProviderChart);
                            $em->persist($referringProviderChartNote);
                        }
                        $em->flush();

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

                        $result['redirect'] = 'index';
                        $result['id'] = $referringProviderChart->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 Provider Encounter',
                        $em->getClassMetadata(ReferringProviderChartEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringProviderChart;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringProviderChart);
                        $referringProviderChart->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_provider_file_ajax_list", name="referring_provider_file_ajax_list")
     */
    public function referring_provider_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 Provider File Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderFileEntity')->ajax_list($get, $this->get('session')->get('userData'));
            //$data2 = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderChartFileEntity')->manage_referring_provider_ajax_list($get, $this->get('session')->get('userData'));

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

                $id = base64_encode($row['id']);
                $referring_provider_id = $get['referring_provider_id'];
                $action = '';
                $url = $this->generateUrl('referring_provider_file_download', array(
                    'referringProviderFile_id' => $id
                ));

                if($hasUpdate) {
                    $action .= "<a class='action-button-style href-referring-provider-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_provider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_file_form"
     * )
     */
    public function referring_provider_file_formAction($referring_provider_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'referring_provider_id' => $referring_provider_id
        );
        $form = $this->createForm(ReferringProviderFileForm::class, $referringProviderFile, $formOptions);


        $title = $action === 'n' ? 'Add File' : 'Update ' . 'Referring Provider File:' . $referringProviderFile->getId();

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

    /**
     * @Route(
     *      "/referring_provider_file/save_action",
     *      name = "referring_provider_file_save"
     * )
     */
    public function referring_provider_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 Provider File New', 'Admin Referring Provider File Update'))) return $authService->redirectToHome();

        $referringProviderFile_form = $request->get('referringProvider_file');
        $em = $this->getDoctrine()->getManager();
        $referringProviderFile = $em->getRepository('RxConnexionBundle:ReferringProviderFileEntity')->find($referringProviderFile_form['id'] );
        if(!$referringProviderFile) {
            $referringProviderFile = new ReferringProviderFileEntity();
        }
        $formOptions = array(
            'action' => $referringProviderFile_form['action'],
            'referring_provider_id' => $referringProviderFile_form['referringProvider']
        );
        $form = $this->createForm(ReferringProviderFileForm::class, $referringProviderFile, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderFileEntity')->validate($referringProviderFile_form);

        if(!count($errors)) {

            switch($referringProviderFile_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

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

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

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

                            }
                        }

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

                    $referringProviderFile_obj = $em->getRepository('RxConnexionBundle:ReferringProviderFileEntity')->find($referringProviderFile_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/referringProvider/files")) {
                                $filesystem->mkdir("uploads/referringProvider/files", 0755);
                            }

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringProviderFile);
                        $referringProviderFile->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_provider_schedule_ajax_list", name="referring_provider_schedule_ajax_list")
     */
    public function referring_provider_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 Provider Schedule Update'), false);

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

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

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


                if($hasUpdate) {
                    $url = $this->generateUrl('referring_provider_schedule_form', array(
                        'referring_provider_id' =>$get['referring_provider_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_provider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_schedule_form"
     * )
     */
    public function schedule_formAction($referring_provider_id, $action, $id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find(base64_decode($referring_provider_id));

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

        $formOptions = array(
            'referring_provider_id' => $referring_provider_id,
            'action' => $action
        );
        $form = $this->createForm(ReferringProviderScheduleForm::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_provider_detail',array(
                        'referringProvider_id' => $referring_provider_id,
                        'tab' => 'ap'
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('referring_provider_schedule_form', array(
                        'referring_provider_id' => $referring_provider_id,
                        'action' => 'u',
                        'id' => base64_encode($result['id']),
                        'tab' => 'ap'
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('referring_provider_schedule_form'), 302);
                }
            } else {
                $form->submit($schedule_form, false);
            }

        }

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

        return $this->render('@RxConnexion/ReferringProvider/schedule_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/referringProvider/referring_provider_schedule_form.js?v=1.0.11'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'referring_provider_id' => $referring_provider_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);
                        $referringProviderChart = new ReferringProviderChartEntity();
                        $referringProviderChart->setMarketingStaffSchedule($schedule);
                        $referringProviderChart->setHealthFacility($schedule->getHealthFacility());
                        $referringProviderChart->setMarketingStaff($schedule->getMarketingStaff());
                        $referringProviderChart->setReferringProvider($schedule->getReferringProvider());
                        $referringProviderChart->setChartType($schedule->getChartType());
                        if($chartStatus){
                            $referringProviderChart->setChartStatus($chartStatus);
                        }
                        $referringProviderChart->setChartDate($schedule->getScheduleDateAsString());
                        $em->persist($referringProviderChart);
                        $referringProviderChartNote = new ReferringProviderChartNoteEntity();
                        $referringProviderChartNote->setReferringProviderChart($referringProviderChart);
                        $referringProviderChartNote->setNote($schedule->getNote());
                        $em->persist($referringProviderChartNote);
                        $referringProviderNote = new ReferringProviderNoteEntity();
                        $referringProviderNote->setReferringProvider($schedule->getReferringProvider());
                        $referringProviderNote->setType($schedule_form['note_type']);
                        $referringProviderNote->setNote($schedule->getNote());
                        $em->persist($referringProviderNote);
                        $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);
                        $referringProviderChart = $em->getRepository('RxConnexionBundle:ReferringProviderChartEntity')->findOneBy(array(
                            'marketingStaffSchedule' => $schedule->getId()
                        ));

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

                        $chartStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findOneBy(array(
                            'description' => $schedule->getMarketingStaffScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));
                        if($chartStatus && $scheduleStatus){
                            $referringProviderChart->setChartStatus($chartStatus);
                        }
                        if($schedule->getNote() != $oldNotes){
                            $referringProviderChartNote = new ReferringProviderChartNoteEntity();
                            $referringProviderChartNote->setReferringProviderChart($referringProviderChart);
                            $referringProviderChartNote->setNote($schedule->getNote());
                            $em->persist($referringProviderChartNote);
                            $referringProviderNote = new ReferringProviderNoteEntity();
                            $referringProviderNote->setReferringProvider($schedule->getReferringProvider());
                            $referringProviderNote->setType($schedule_form['note_type']);
                            $referringProviderNote->setNote($schedule->getNote());
                            $em->persist($referringProviderNote);
                        }
                        $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_provider_note_ajax_list", name="referring_provider_note_ajax_list")
     */
    public function referring_provider_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 Provider Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->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-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_provider_note_clinical_ajax_list", name="referring_provider_note_clinical_ajax_list")
     */
    public function referring_provider_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 Provider Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->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-provider-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_provider_note_billing_ajax_list", name="referring_provider_note_billing_ajax_list")
     */
    public function referring_provider_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 Provider Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->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-provider-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_provider_note_appointment_ajax_list", name="referring_provider_note_appointment_ajax_list")
     */
    public function referring_provider_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 Provider Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->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-provider-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_provider_note_specialist_ajax_list", name="referring_provider_note_specialist_ajax_list")
     */
    public function referring_provider_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 Provider Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->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-provider-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_provider_note_letter_ajax_list", name="referring_provider_note_letter_ajax_list")
     */
    public function referring_provider_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 Provider Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->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-provider-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_provider_note/form/{referring_provider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_note_form"
     * )
     */
    public function referring_provider_note_formAction($referring_provider_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'referring_provider_id' => $referring_provider_id
        );
        $form = $this->createForm(ReferringProviderNoteForm::class, $referringProviderNote, $formOptions);


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

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

    /**
     * @Route(
     *      "/referring_provider_note/save_action",
     *      name = "referring_provider_note_save"
     * )
     */
    public function referring_provider_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 Provider Note New', 'Admin Referring Provider Note Update'))) return $authService->redirectToHome();

        $referringProviderNote_form = $request->get('referringProvider_note');
        $em = $this->getDoctrine()->getManager();
        $referringProviderNote = $em->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->find($referringProviderNote_form['id']);
        if(!$referringProviderNote) {
            $referringProviderNote = new ReferringProviderNoteEntity();
        }
        $formOptions = array(
            'action' => $referringProviderNote_form['action'],
            'referring_provider_id' => $referringProviderNote_form['referringProvider']
        );
        $form = $this->createForm(ReferringProviderNoteForm::class, $referringProviderNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderNoteEntity')->validate($referringProviderNote_form);

        if(!count($errors)) {

            switch($referringProviderNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringProviderNote);
                        $referringProviderNote->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/{referringProviderFile_id}",
     *
     *      name = "referring_provider_file_download"
     * )
     */
    public function referring_provider_file_downloadAction($referringProviderFile_id){

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

        $fileName = $referringProviderFile->getParsedDescription();
        $uploadDir = $referringProviderFile->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("/referring_provider_health_facility_autocomplete", name="referring_provider_health_facility_autocomplete")
     */
    public function referring_provider_health_facility_autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

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

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

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

        return new JsonResponse($result);
    }
}