<?php

namespace RxConnexionBundle\Controller;

use Doctrine\ORM\EntityManager;
use RxConnexionBundle\Entity\InsuranceEntity;
use RxConnexionBundle\Entity\InventoryEntity;
use RxConnexionBundle\Entity\InventorySerialNoEntity;
use RxConnexionBundle\Entity\ItemEntity;
use RxConnexionBundle\Entity\LetterTemplateEmailEntity;
use RxConnexionBundle\Entity\LetterTemplateEntity;
use RxConnexionBundle\Entity\PatientBillingBreakdownEntity;
use RxConnexionBundle\Entity\PatientBillingFinancingPaymentDetailEntity;
use RxConnexionBundle\Entity\PatientBillingInventoryEntity;
use RxConnexionBundle\Entity\PatientBillingRefundEntity;
use RxConnexionBundle\Entity\PatientChartTicketEntity;
use RxConnexionBundle\Entity\PatientEmailCcEntity;
use RxConnexionBundle\Entity\PatientEmailEntity;
use RxConnexionBundle\Entity\PatientEmailFileEntity;
use RxConnexionBundle\Entity\PatientHealthFacilityEntity;
use RxConnexionBundle\Entity\PatientLetterAliceNightOneEntity;
use RxConnexionBundle\Entity\PatientLetterGeneralPrescriptionFRSIEntity;
use RxConnexionBundle\Entity\PatientLetterNoteEntity;
use RxConnexionBundle\Entity\AccountUserReminderEntity;
use RxConnexionBundle\Entity\PatientLetterPrescriptionEntity;
use RxConnexionBundle\Entity\PatientLetterPrescriptionFRSIEntity;
use RxConnexionBundle\Entity\PatientLetterPrescriptionFRSIv2Entity;
use RxConnexionBundle\Entity\PatientLetterPrescriptionPSSEntity;
use RxConnexionBundle\Entity\PatientLetterRefusalCareEntity;
use RxConnexionBundle\Entity\PatientLetterSpecialistReferralEntity;
use RxConnexionBundle\Entity\PatientPaymentBreakdownEntity;
use RxConnexionBundle\Entity\PatientRefundBreakdownEntity;
use RxConnexionBundle\Entity\PatientRentalEntity;
use RxConnexionBundle\Entity\PatientServiceEntity;
use RxConnexionBundle\Entity\PatientTicketEntity;
use RxConnexionBundle\Entity\PatientTreatmentConsiderationEntity;
use RxConnexionBundle\Entity\ReferralEntity;
use RxConnexionBundle\Entity\ReferredByPatientEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityProviderEntity;
use RxConnexionBundle\Entity\AccountUserReminderRefPatientEntity;
use RxConnexionBundle\Entity\ReferringProviderEntity;
use RxConnexionBundle\Entity\SystemParameterEntity;
use RxConnexionBundle\Entity\TicketCcEntity;
use RxConnexionBundle\Entity\TicketEntity;
use RxConnexionBundle\Entity\TicketNoteEntity;
use RxConnexionBundle\Form\PatientBillingRefundForm;
use RxConnexionBundle\Form\PatientEmailForm;
use RxConnexionBundle\Form\PatientHealthFacilityForm;
use RxConnexionBundle\Form\PatientReminderForm;
use RxConnexionBundle\Form\PatientRentalForm;
use RxConnexionBundle\Form\PatientServiceOtherForm;
use RxConnexionBundle\Service\InventoryService;
use RxConnexionBundle\Service\SRFaxService;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

use RxConnexionBundle\Entity\AppointmentNoticeFaxEntity;
use RxConnexionBundle\Entity\PatientChartDeviceEntity;
use RxConnexionBundle\Entity\PatientChartEntity;
use RxConnexionBundle\Entity\PatientChartFileEntity;
use RxConnexionBundle\Entity\PatientChartNoteEntity;
use RxConnexionBundle\Entity\PatientChartOtherProcedureEntity;
use RxConnexionBundle\Entity\PatientChartPaymentEntity;
use RxConnexionBundle\Entity\PatientChartPaymentOtherProcedureEntity;
use RxConnexionBundle\Entity\PatientChartPaymentProcedureEntity;
use RxConnexionBundle\Entity\PatientChartProcedureEntity;
use RxConnexionBundle\Entity\PatientChartTypeMethodEntity;
use RxConnexionBundle\Entity\PatientDiagnosisEntity;
use RxConnexionBundle\Entity\PatientDiagnosisMedicationEntity;
use RxConnexionBundle\Entity\PatientFileEntity;
use RxConnexionBundle\Entity\PatientInsuranceEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\PatientLetterEntity;
use RxConnexionBundle\Entity\PatientReferringHealthFacilityEntity;
use RxConnexionBundle\Entity\PatientReferringProviderEntity;
use RxConnexionBundle\Entity\PatientBillingEntity;
use RxConnexionBundle\Entity\PatientPaymentEntity;
use RxConnexionBundle\Entity\ScheduleEntity;
use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Entity\PatientEntity;
use RxConnexionBundle\Entity\FaxTranOutboundEntity;
use RxConnexionBundle\Entity\PatientRedFlagEntity;
use RxConnexionBundle\Entity\PatientSpecialistEntity;
use RxConnexionBundle\Entity\PatientTreatmentPlanEntity;
use RxConnexionBundle\Entity\PatientLetterFileEntity;

use RxConnexionBundle\Form\AppointmentNoticeFaxForm;
use RxConnexionBundle\Form\PatientChartDeviceForm;
use RxConnexionBundle\Form\PatientChartFileForm;
use RxConnexionBundle\Form\PatientChartForm;
use RxConnexionBundle\Form\PatientChartNoteForm;
use RxConnexionBundle\Form\PatientChartOtherProcedureForm;
use RxConnexionBundle\Form\PatientChartPaymentForm;
use RxConnexionBundle\Form\PatientChartProcedureForm;
use RxConnexionBundle\Form\PatientChartUpdateIsDoneForm;
use RxConnexionBundle\Form\PatientDiagnosisForm;
use RxConnexionBundle\Form\PatientDiagnosisMedicationForm;
use RxConnexionBundle\Form\PatientFileForm;
use RxConnexionBundle\Form\PatientInsuranceForm;
use RxConnexionBundle\Form\PatientNoteForm;
use RxConnexionBundle\Form\PatientLetterForm;
use RxConnexionBundle\Form\PatientReferringHealthFacilityForm;
use RxConnexionBundle\Form\PatientReferringProviderForm;
use RxConnexionBundle\Form\PatientScheduleForm;
use RxConnexionBundle\Form\PatientBillingForm;
use RxConnexionBundle\Form\PatientPaymentForm;
use RxConnexionBundle\Form\PatientForm;
use RxConnexionBundle\Form\PatientRedFlagForm;
use RxConnexionBundle\Form\PatientSpecialistForm;
use RxConnexionBundle\Form\PatientServiceForm;
use RxConnexionBundle\Form\PatientTreatmentConsiderationForm;
use RxConnexionBundle\Form\PatientTreatmentPlanForm;

use RxConnexionBundle\Form\PatientLetterNoteForm;
use RxConnexionBundle\Form\Type\PatientServicesForm;

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
// Require PDF class of the library
use PDFMerger;

/**
 * @Route("/main/patient")
 */
class PatientController extends Controller
{
    /**
     * @Route("", name="patient")
     */
    public function indexAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient'))) return $authService->redirectToHome();
        $userData = $this->get('session')->get('userData');
        /*if($userData['type'] === "Super Admin"){
            $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findAllNotDeleted();
        } else {
            $healthFacilities = $em->getReposupditory('RxConnexionBundle:HealthFacilityEntity')->findBy(array('id' => $userData['branches']));
        }*/
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findAllNotDeletedAndHasPatient($userData);
        $hl7MessageTypes = $this->get('rx_connexion.hl7Service')->messageTypes;

        $flagColor = array(
            'red' => 'Red',
            'green' => 'Green',
            'yellow' => 'Yellow',
            'blue' => 'Blue',
        );

        return $this->render('@RxConnexion/Patient/index.html.twig', array(
            'title' => 'Manage Patient',
            'page_title' => 'Manage Patient',
            'javascripts' => array('rxconnexion/admin/js/patient/patient.js?v=1.0.11'),
            'stylesheets' => array('rxconnexion/admin/css/patient/patient.css?v=1.0.2'),
            'healthFacilities' => $healthFacilities,
            'hl7MessageTypes' => $hl7MessageTypes,
            'flagColor' => $flagColor
        ));
    }

    /**
     * @Route("/mass_export_hl7", name="patient_mass_export_hl7")
     */
    public function mass_export_hl7Action(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient'))) return $authService->redirectToHome();

        $get = $request->get('forms');
        $type = $get['type'];
        $hl7Service = $this->get('rx_connexion.hl7Service');
        $zipName = $this->get('kernel')->getProjectDir() .'/var/temp/'. 'patientHl7'. uniqid() .'.zip';
        $zip = new \ZipArchive();
        $zip->open($zipName, \ZIPARCHIVE::CREATE);
        if(isset($get['patient'])){
            foreach ($get['patient'] as $patientId){
                $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patientId));
                $hl7Data = $hl7Service->generate($type, $patient, $type);
                $fileName = $type.'-'.$patient->getFullName().'.hl7';
                $zip->addFromString($fileName,$hl7Data['data']);
            }
            $zip->close();
            /*$handle = fopen($zipName, 'rb');

            $chunkSize = 1024*1024;

            if($handle !== false) {

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

                fclose($handle);
            }*/
            header("Content-type: application/zip");
            header('Content-disposition: attachment; filename='.$zipName);
            header('Content-Length: ' . filesize($zipName));
            readfile($zipName);
            exit();
        }else{
            $this->get('session')->getFlashBag()->set('error_messages', 'Please choose patient(s) to export.');
            return $this->redirect($this->generateUrl('patient'), 302);
        }
    }

    /**
     * @Route(
     *      "/export-all-hl7-form",
     *      name = "patient_export_all_hl7_form"
     * )
     */
    public function patient_export_all_hl7_formAction() {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Export HL7'))) return $authService->redirectToHome();

        $hl7Service = $this->get('rx_connexion.hl7ForAllService');
        $hl7MessageTypes = $hl7Service->messageTypes;

        $title = 'Export Patients Details to HL7 File';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/export_all_hl7.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'hl7MessageTypes' => $hl7MessageTypes
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route("/export_all_hl7", name="patient_export_all_hl7")
     */
    public function export_all_hl7Action(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient'))) return $authService->redirectToHome();

        $type = $request->query->get('type');
        $hl7Service = $this->get('rx_connexion.hl7ForAllService');
        $zipName = $this->get('kernel')->getProjectDir() .'/var/temp/'. 'patientHl7'. uniqid() .'.zip';
        $zip = new \ZipArchive();
        $zip->open($zipName, \ZIPARCHIVE::CREATE);
        $patients = $em->getRepository('RxConnexionBundle:PatientEntity')->getPatientDetailsForHl7();
        foreach ($patients as $patient){
            $hl7Data = $hl7Service->generate($type, $patient, $type);
            $fileName = $type.'-'.$patient['fullName'].'.hl7';
            $zip->addFromString($fileName,$hl7Data['data']);
        }
        $zip->close();
        /*$handle = fopen($zipName, 'rb');

        $chunkSize = 1024*1024;

        if($handle !== false) {

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

            fclose($handle);
        }*/
        header("Content-type: application/zip");
        header('Content-disposition: attachment; filename='.$zipName);
        header('Content-Length: ' . filesize($zipName));
        readfile($zipName);
        set_time_limit(30);
        exit();
    }

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

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

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

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

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

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

                $flagColor = '';
                foreach ($redFlagDT as $rfDT) {
                    if($row['id'] == $rfDT['patient_id']) {
                        if($rfDT['is_green_flag'] == 1) {
                            $flagColor = 'Green';
                        }
                        if($rfDT['is_yellow_flag'] == 1) {
                            $flagColor = 'Yellow';
                        }
                        if($rfDT['is_red_flag'] == 1) {
                            $flagColor = 'Red';
                        }
                        if($rfDT['is_blue_flag'] == 1) {
                            $flagColor = 'Blue';
                        }
                    }
                }
                $checkBoxShow = $get['checkBoxShow'] === 'show' ? '' : 'display: none;';

                $values = array(
                    "<input type='checkbox' style='margin:10px; $checkBoxShow' name='forms[patient][$row[id]]' value='$id' class='patient-checkbox-hl7'>".$row['id'],
                    $row['full_name'],
                    $row['phnNo'],
                    $row['healthFacility_desc'],
                    $row['address'],
                    $row['phoneNo'],
                    $row['mobileNo'],
                    $row['gender'],
                    $row['birthDate'],
                    $action,
                    array('DT_RowData' => array(
                        'flagColor' => $flagColor
                    ))
                );

                $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 = "patient_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 Patient New', 'Admin Patient Update'))) return $authService->redirectToHome();

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

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

        $service = $em->getRepository('RxConnexionBundle:ServiceEntity')->findAll();
        if(count($service)){
            foreach ($service as $services){
                $patientService = $patient->getPatientServiceByServiceId($services->getId());
                if(!$patientService){
                    $patientService = new PatientServiceEntity();
                    $patientService->setStartDate(date('Y/m/d'));
                    $patientService->setEndDate(null);
                    $patientService->setService($services);
                    if (isset($patient_form['is_specialist'])) {
                        $patientService->setPatientServiceType('Specialist');
                    } else {
                        $patientService->setPatientServiceType('Others');
                    }
                    $patient->addPatientService($patientService);
                }
            }
        }

        if($patient->getHealthFacility() != null) {
            $healthFacility = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($id));
            $patient->setHealthFacility($healthFacility->getHealthFacility());
        }

        $formOptions = array('action' => $action);
        $form = $this->createForm(PatientForm::class, $patient, $formOptions);
        if($request->getMethod() === 'POST') {

            $patient_form = $request->get($form->getName());
            $result = $this->processForm($patient_form, $patient, $form, $request);

            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('patient'), 302);
                } else if($result['redirect'] === 'detail') {
                    return $this->redirect($this->generateUrl('patient_detail', array(
                        'patient_id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('patient_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id']),
                        'tab' => 'p'
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('patient_form'), 302);
                }
            } else {
                $form->submit($patient_form, false);
            }
        }

        $title = ($action === 'n' ? 'New' : 'Update') . ' Patient';
        $fromDetail = false;
        if($request->get('fd') != null){
            $fromDetail = true;
        }
        return $this->render('@RxConnexion/Patient/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/patient/patient_form.js?v=1.0.4'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'fromDetail' => $fromDetail,
        ));
    }

    private function processForm($patient_form, $patient, $form, Request $request) {

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

        if(!count($errors)) {

            switch($patient_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        if(isset($patient_form['is_referral'])){
                            $referral = new ReferralEntity();
                            $referral->setFirstName($patient_form['first_name']);
                            $referral->setMiddleName($patient_form['middle_name']);
                            $referral->setLastName($patient_form['last_name']);
                            $referral->setBirthDate($patient_form['birth_date']);
                            $referral->setGender($patient_form['gender']);
                            $referral->setReferralDate($patient_form['referral_date']);
                            $referral->setPersonalHealthNo($patient_form['personal_health_no']);
                            $referral->setHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity',$patient_form['health_facility']));
                            $referral->setCity($em->getReference('RxConnexionBundle:CityEntity',$patient_form['city']));
                            $referral->setPostalCode($em->getReference('RxConnexionBundle:PostalCodeEntity',$patient_form['postalCode']));
                            $referral->setStreet($patient_form['street']);
                            $referral->setMobileNo($patient_form['mobile_no']);
                            $referral->setMobileNoTwo($patient_form['mobile_no_two']);
                            $referral->setMobileNoThree($patient_form['mobile_no_three']);
                            $referral->setPhoneNo($patient_form['phone_no']);
                            $referral->setPhoneNoTwo($patient_form['phone_no_two']);
                            $referral->setPhoneNoThree($patient_form['phone_no_three']);
                            $referral->setEmail($patient_form['email']);
                            $referral->setEmailTwo($patient_form['email_two']);
                            $referral->setEmailThree($patient_form['email_three']);
                            $em->persist($referral);
                            $patient->setReferral($referral);
                        }
                        $em->persist($patient);
                        if($patient_form['health_facility'] != ''){
                            $patientHealthFacility = new PatientHealthFacilityEntity();
                            $patientHealthFacility->setPatient($patient);
                            $patientHealthFacility->setHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity',$patient_form['health_facility']));
                            $patientHealthFacility->setStartDate(date('m/d/Y'));
                            $em->persist($patientHealthFacility);
                        }
                        $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')->find($patient_form['postalCode']);
                        $apiUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($patient_form['street'] . ' ' . $postalCode->getCity()->getDescription() . ', ' . $postalCode->getCity()->getProvince()->getDescription() . ' ' . $postalCode->getCity()->getProvince()->getCountry()->getDescription() . ' ' . $postalCode->getDescription()) . '&key=' .$this->container->getParameter('google_map_api_key');

                        try {
                            $headers = get_headers($apiUrl, 1);
                        } catch(\Exception $e) {
                            $headers = FALSE;
                        }

                        if($headers !== FALSE && substr($headers[0], 9, 3) === '200') {

                            $apiData = json_decode(file_get_contents($apiUrl), true);

                            if(count($apiData) && isSet($apiData['status'])) {

                                if($apiData['status'] === 'OK') {
                                    $patient->setGeoLat($apiData['results'][0]['geometry']['location']['lat']);
                                    $patient->setGeoLong($apiData['results'][0]['geometry']['location']['lng']);
                                    /*$uploadPath = $this->get('kernel')->getProjectDir() . "/web/uploads/patient/map/";
                                    $baseName = $patient_form['first_name'] . " " . $patient_form['last_name'] . ".png";
                                    $parsedName = $patient_form['first_name'] . " " . $patient_form['last_name'] . '-' . time(). ".png";
                                    file_put_contents($uploadPath . $baseName, $googleMapsImg);
                                    $patient->removeGoogleMapsImage();
                                    $patient->setMapImageDescription($baseName);
                                    $patient->setParsedMapImageDescription($parsedName);*/
                                } else {
                                    $patient->setGeoLat(null);
                                    $patient->setGeoLong(null);
                                }
                            }
                        }
                        $em->flush();

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

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

                            if (move_uploaded_file($_FILES['form']['tmp_name']['photo'], $uploadFile)) {
                                $patient->removePhoto();
                                $patient->setPhotoDescription($_FILES['form']['name']['photo']);
                                $patient->setParsedPhotoDescription($baseName);
                                $em->flush();

                            }
                        }


                        if(isset($patient_form['referredBy']) && isset($patient_form['referredByPatient_fullName'])) {
                            $referredByPatient = new ReferredByPatientEntity();
                            $referredByPatient->setPatient($patient);
                            $referredByPatient->setReferredBy($patient_form['referredBy']);
                            $referredByPatient->setReferredByFullName($patient_form['referredByPatient_fullName']);
                            $em->persist($referredByPatient);
                        }

                        $newAT = new AuditTrailEntity(
                            'Patient',
                            $em->getClassMetadata(PatientEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patient;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

                        $result['redirect'] = 'detail';
                        $result['id'] = $patient->getId();

                    } else {

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

                    break;

                case 'u': // update
                    $oldGoogleMapImageDesc = $patient->getParsedMapImageDescription();

                    $newAT = new AuditTrailEntity(
                        'Patient',
                        $em->getClassMetadata(PatientEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patient;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')->find($patient_form['postalCode']);
                        $province = $postalCode->getCity()->getProvince() ? $postalCode->getCity()->getProvince()->getDescription() : '';
                        $apiUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($patient_form['street'] . ' ' . $postalCode->getCity()->getDescription() . ', ' . $province . ' ' . 'Canada' . ' ' . $postalCode->getDescription()) . '&key=' .$this->container->getParameter('google_map_api_key');

                        try {
                            $headers = get_headers($apiUrl, 1);
                        } catch(\Exception $e) {
                            $headers = FALSE;
                        }

                        if($headers !== FALSE && substr($headers[0], 9, 3) === '200') {

                            $apiData = json_decode(file_get_contents($apiUrl), true);

                            if(count($apiData) && isSet($apiData['status'])) {

                                if($apiData['status'] === 'OK') {
                                    $patient->setGeoLat($apiData['results'][0]['geometry']['location']['lat']);
                                    $patient->setGeoLong($apiData['results'][0]['geometry']['location']['lng']);
                                    /*$googleMapsImg = file_get_contents("https://maps.googleapis.com/maps/api/staticmap?center=" . urlencode($patient_form['street'] . ' ' . $postalCode->getCity()->getDescription() . ', ' . $postalCode->getCity()->getProvince()->getDescription() . ' ' . $postalCode->getCity()->getProvince()->getCountry()->getDescription() . ' ' . $postalCode->getDescription()) . "&zoom=13&size=450x465&maptype=roadmap&markers=color:red%7Clabel:P%7C" . urlencode($patient->getGeoLat()) . "," . urlencode($patient->getGeoLong()) ."&key=" . "AIzaSyCgtrVLEdDvSgs3OBAiR0egtPiqsdTA_8w");
                                    $uploadPath = $this->get('kernel')->getProjectDir() . "/web/uploads/patient/map/";
                                    $baseName = $patient_form['first_name'] . " " . $patient_form['last_name'] . ".png";
                                    $parsedName = $patient_form['first_name'] . " " . $patient_form['last_name'] . '-' . time(). ".png";
                                    file_put_contents($uploadPath . $baseName, $googleMapsImg);
                                    $patient->removeGoogleMapsImage();
                                    $patient->setMapImageDescription($baseName);
                                    $patient->setParsedMapImageDescription($parsedName);*/
                                } else {
                                    $patient->setGeoLat(null);
                                    $patient->setGeoLong(null);
                                }
                            }
                        }
                        if($patient->getActivePatientHealthFacility()){
                            if($patient_form['health_facility'] != '' && $patient_form['health_facility'] != $patient->getActivePatientHealthFacility()->getHealthFacility()->getId()){
                                $activeHealthFacility = $patient->getActivePatientHealthFacility();
                                $activeHealthFacility->setEndDate(date('m/d/Y'));

                                $patientHealthFacility = new PatientHealthFacilityEntity();
                                $patientHealthFacility->setPatient($patient);
                                $patientHealthFacility->setHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity',$patient_form['health_facility']));
                                $patientHealthFacility->setStartDate(date('m/d/Y'));
                                $em->persist($patientHealthFacility);
                            }
                        }else{
                            $patientHealthFacility = new PatientHealthFacilityEntity();
                            $patientHealthFacility->setPatient($patient);
                            $patientHealthFacility->setHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity',$patient_form['health_facility']));
                            $patientHealthFacility->setStartDate(date('m/d/Y'));
                            $em->persist($patientHealthFacility);
                        }

                        $em->flush();

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

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

                            if (move_uploaded_file($_FILES['form']['tmp_name']['photo'], $uploadFile)) {
                                $patient->removePhoto();
                                $patient->setPhotoDescription($_FILES['form']['name']['photo']);
                                $patient->setParsedPhotoDescription($baseName);
                                $em->flush();

                            }
                        }


                        //For referral by
                        if(isset($patient_form['referredBy']) && isset($patient_form['referredByPatient_fullName'])) {
                            $referredByPatient = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferredByPatientEntity')->findOneBy(array(
                                'patient' => $patient_form['id']
                            ));

                            if(isset($referredByPatient)) {
                                $referredByPatient->setReferredBy($patient_form['referredBy']);
                                $referredByPatient->setReferredByFullName($patient_form['referredByPatient_fullName']);
                                $em->flush();
                            } else {
                                $referredByPatient = new ReferredByPatientEntity();
                                $referredByPatient->setPatient($patient);
                                $referredByPatient->setReferredBy($patient_form['referredBy']);
                                $referredByPatient->setReferredByFullName($patient_form['referredByPatient_fullName']);
                                $em->persist($referredByPatient);
                                $em->flush();
                            }

                        }

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

                        $result['redirect'] = 'detail';
                        $result['id'] = $patient->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(
                        'Patient',
                        $em->getClassMetadata(PatientEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patient;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patient);
                        $patient->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(
     *      "/upload_form",
     *      name = "patient_upload_form"
     * )
     */
    public function upload_formAction() {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient New', 'Admin Patient Update'))) return $authService->redirectToHome();

        $title = 'Upload Patient';

        return $this->render('@RxConnexion/Patient/upload_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'stylesheets' => array(
                'rxconnexion/dropzone/min/dropzone.min.css'
            ),
            'javascripts' => array(
                'rxconnexion/dropzone/min/dropzone.min.js',
                'rxconnexion/admin/js/patient/patient_upload_form.js?v=1.0.0'
            )
        ));
    }
    /**
     * @Route(
     *      "/do_upload_form",
     *      name = "patient_do_upload_form"
     * )
     */
    public function do_upload_formAction(Request $request) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient New', 'Admin Patient Update'))) return $authService->redirectToHome();
        $em = $this->getDoctrine()->getManager();
        $patientInfos = array();
        $result = array();
        $dttst = new DateTimeToStringTransformer();
        $acceptedTypes = array(
            'ADT^A01',
            'ADT^A02',
            'ADT^A04',
            'ADT^A05'
        );

        if($request->getMethod() === 'POST') {
            $numFile = count($_FILES['file']['tmp_name']);
            for ( $x = 0; $x < $numFile; $x++){
                if(isset($_FILES['file']) && !empty($_FILES['file']['tmp_name'][$x])) {
                    $fileType = pathinfo($_FILES['file']['name'][$x], PATHINFO_EXTENSION);
                    $uploadedFile = file_get_contents($_FILES['file']['tmp_name'][$x]);
                    $patientDetails = explode('|', $uploadedFile);
                    if($fileType == 'hl7') {
                        if(in_array($patientDetails[8], $acceptedTypes)){
                            $date = date_create_from_format("YmdHis",$patientDetails[20]);
                            $birthDate = date('Y-m-d H:i:s', strtotime($dttst->transform($date)));
                            $patientName = explode('^', $patientDetails[18]);
                            $patientExist = $em->getRepository('RxConnexionBundle:PatientEntity')->patientExists($patientName[0], $patientName[1], $birthDate);
                            if (!$patientExist) {
                                switch($patientDetails[8]) {
                                    /*--------------------------------------------------------------------------------------------------------*/
                                    /*					ADT A01	Patient Admit												                  */
                                    /*--------------------------------------------------------------------------------------------------------*/
                                    case 'ADT^A01' :
                                        if(isset($patientDetails[16])){
                                            $detail = explode('^', $patientDetails[16]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['healthCardNo'] = $detail[0];
                                            }else{
                                                $patientInfos['healthCardNo'] = '';
                                            }
                                        }
                                        if(isset($patientDetails[18])){
                                            $detail = explode('^', $patientDetails[18]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['lastName'] = $detail[0];
                                            }else{
                                                $patientInfos['lastName'] = '';
                                            }
                                            if(isset($detail[1]) && $detail[1] != 'null'){
                                                $patientInfos['firstName'] = $detail[1];
                                            }else{
                                                $patientInfos['firstName'] = '';
                                            }
                                        }

                                        if(isset($patientDetails[20])){
                                            $date = date_create_from_format("YmdHis",$patientDetails[20]);
                                            $startDate = date('m/d/Y', strtotime($dttst->transform($date)));
                                            $patientInfos['birthDate'] = $startDate;

                                        }

                                        if(isset($patientDetails[21])){
                                            $patientInfos['gender'] = $patientDetails[21] == 'M' ? 'Male' : 'Female';

                                        }

                                        if(isset($patientDetails[24])){
                                            $detail = explode('^', $patientDetails[24]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['street'] = $detail[0];
                                            }else{
                                                $patientInfos['street'] = '';
                                            }
                                            if(isset($detail[2]) && $detail[2] != 'null'){
                                                $patientInfos['city'] = $detail[2];
                                            }else{
                                                $patientInfos['city'] = '';
                                            }
                                            if(isset($detail[4]) && $detail[4] != 'null'){
                                                $postalCode = explode(' ', $detail[4]);
                                                $res = str_replace("PV1", "", $postalCode[1]);
                                                unset($postalCode[1]);
                                                $postalCode[] = trim($res);
                                                $patientInfos['postalCode'] = $postalCode[0] . ' ' . $postalCode[2];
                                            }else{
                                                $patientInfos['postalCode'] = '';
                                            }
                                        }

                                        if(isset($patientDetails[32])){
                                            $rps = explode('~', $patientDetails[32]);
                                            $referringPhysicians = array();
                                            foreach ($rps as $key => $rp){
                                                $referringPhysician = explode('^', $rp);
                                                $referringPhysicians[$key]['lastName'] = $referringPhysician[1];
                                                $referringPhysicians[$key]['firstName'] = $referringPhysician[2];
                                            }
                                            $patientInfos['referringPhysicians'] = $referringPhysicians;
                                        }

                                        if(strpos($patientDetails[34], 'IN1') !== false){
                                            $insurances = array();
                                            $res = str_replace("IN1", "", $patientDetails[38]);
                                            $insurances['name'] = trim($res);
                                            $detailDate = explode('^', $patientDetails[37]);
                                            if(isset($detailDate[6])){
                                                $date = date_create_from_format("YmdHis",$detailDate[6]);
                                                $startDate = date('m/d/Y', strtotime($dttst->transform($date)));
                                                $insurances['startDate'] = $startDate;
                                            }
                                            $patientInfos['insurances'][] = $insurances;
                                        }
                                        if(strpos($patientDetails[38], 'IN1') !== false){
                                            $insurances = array();
                                            $res = str_replace("IN1", "", $patientDetails[42]);
                                            $insurances['name'] = trim($res);
                                            $detailDate = explode('^', $patientDetails[37]);
                                            if(isset($detailDate[6])){
                                                $date = date_create_from_format("YmdHis",$detailDate[6]);
                                                $dttst = new DateTimeToStringTransformer();
                                                $startDate = date('m/d/Y', strtotime($dttst->transform($date)));
                                                $insurances['startDate'] = $startDate;
                                            }
                                            $patientInfos['insurances'][] = $insurances;
                                        }
                                        $city = $em->getRepository('RxConnexionBundle:CityEntity')->findOneBy(array('description' => $patientInfos['city']));
                                        $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')->findOneBy(array('description' => $patientInfos['postalCode']));
                                        $patient = new PatientEntity();
                                        $patient->setAlbertaHealthCardNo($patientInfos['healthCardNo']);
                                        $patient->setFirstName($patientInfos['firstName']);
                                        $patient->setLastName($patientInfos['lastName']);
                                        $patient->setBirthDate($patientInfos['birthDate']);
                                        $patient->setGender($patientInfos['gender']);
                                        $patient->setStreet($patientInfos['street']);
                                        $patient->setCity($city);
                                        $patient->setPostalCode($postalCode);
                                        $patient->setIsActive(true);
                                        $em->persist($patient);
                                        $em->flush();
                                        foreach ($patientInfos['referringPhysicians'] as $rp){
                                            $referringPhysician = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->findOneBy(array('fullName' => $rp['firstName'] . ' ' . $rp['lastName']));
                                            $patientReferringPhysician = new PatientReferringProviderEntity();
                                            if(!$referringPhysician) {
                                                $referringPhysician = new ReferringProviderEntity();
                                                $referringPhysician->setFirstName($rp['firstName']);
                                                $referringPhysician->setLastName($rp['lastName']);
                                                $referringPhysician->setHonorific(ReferringProviderEntity::HONORIFIC_DR);
                                                $em->persist($referringPhysician);
                                            }
                                            $patientReferringPhysician->setReferringProvider($referringPhysician);
                                            $patientReferringPhysician->setPatient($patient);
                                            $patientReferringPhysician->setStartDate(date('m/d/Y'));
                                            $em->persist($patientReferringPhysician);
                                            $em->flush();
                                        }
                                        foreach ($patientInfos['insurances'] as $i){
                                            $insurance = $em->getRepository('RxConnexionBundle:InsuranceEntity')->findOneBy(array('description' => $i['name']));
                                            $patientInsurance = new PatientInsuranceEntity();
                                            if(!$insurance) {
                                                $insurance = new InsuranceEntity();
                                                $insurance->setDescription($i['name']);
                                                $insurance->setCode($i['name']);
                                                $em->persist($insurance);
                                            }
                                            $patientInsurance->setInsurance($insurance);
                                            $patientInsurance->setPatient($patient);
                                            $patientInsurance->setStartDate($i['startDate']);
                                            $em->persist($patientInsurance);
                                            $em->flush();
                                        }
                                        $patientFile = new PatientFileEntity();
                                        $patientFile->setNote('HL7 file');
                                        $patientFile->setPatient($patient);
                                        $em->persist($patientFile);
                                        $em->flush();
                                        $baseName = $patientFile->getId() . '-' . time() . '.' . pathinfo($_FILES['file']['name'][$x], PATHINFO_EXTENSION);
                                        $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;

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

                                        }
                                        break;
                                    /*--------------------------------------------------------------------------------------------------------*/
                                    /*					ADT A02	Patient Transfer										                      */
                                    /*--------------------------------------------------------------------------------------------------------*/
                                    case 'ADT^A02' :
                                        if(isset($patientDetails[16])){
                                            $detail = explode('^', $patientDetails[16]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['healthCardNo'] = $detail[0];
                                            }else{
                                                $patientInfos['healthCardNo'] = '';
                                            }
                                        }
                                        if(isset($patientDetails[18])){
                                            $detail = explode('^', $patientDetails[18]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['lastName'] = $detail[0];
                                            }else{
                                                $patientInfos['lastName'] = '';
                                            }
                                            if(isset($detail[1]) && $detail[1] != 'null'){
                                                $patientInfos['firstName'] = $detail[1];
                                            }else{
                                                $patientInfos['firstName'] = '';
                                            }
                                        }

                                        if(isset($patientDetails[20])){
                                            $date = date_create_from_format("YmdHis",$patientDetails[20]);
                                            $startDate = date('m/d/Y', strtotime($dttst->transform($date)));
                                            $patientInfos['birthDate'] = $startDate;

                                        }

                                        if(isset($patientDetails[21])){
                                            $patientInfos['gender'] = $patientDetails[21] == 'M' ? 'Male' : 'Female';

                                        }

                                        if(isset($patientDetails[24])){
                                            $detail = explode('^', $patientDetails[24]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['street'] = $detail[0];
                                            }else{
                                                $patientInfos['street'] = '';
                                            }
                                            if(isset($detail[2]) && $detail[2] != 'null'){
                                                $patientInfos['city'] = $detail[2];
                                            }else{
                                                $patientInfos['city'] = '';
                                            }
                                            if(isset($detail[4]) && $detail[4] != 'null'){
                                                $postalCode = explode(' ', $detail[4]);
                                                $res = str_replace("PV1", "", $postalCode[1]);
                                                unset($postalCode[1]);
                                                $postalCode[] = trim($res);
                                                $patientInfos['postalCode'] = $postalCode[0] . ' ' . $postalCode[2];
                                            }else{
                                                $patientInfos['postalCode'] = '';
                                            }
                                        }

                                        if(isset($patientDetails[32])){
                                            $rps = explode('~', $patientDetails[32]);
                                            $referringPhysicians = array();
                                            foreach ($rps as $key => $rp){
                                                $referringPhysician = explode('^', $rp);
                                                $referringPhysicians[$key]['lastName'] = $referringPhysician[1];
                                                $referringPhysicians[$key]['firstName'] = $referringPhysician[2];
                                            }
                                            $patientInfos['referringPhysicians'] = $referringPhysicians;
                                        }

                                        $city = $em->getRepository('RxConnexionBundle:CityEntity')->findOneBy(array('description' => $patientInfos['city']));
                                        $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')->findOneBy(array('description' => $patientInfos['postalCode']));
                                        $patient = new PatientEntity();
                                        $patient->setAlbertaHealthCardNo($patientInfos['healthCardNo']);
                                        $patient->setFirstName($patientInfos['firstName']);
                                        $patient->setLastName($patientInfos['lastName']);
                                        $patient->setBirthDate($patientInfos['birthDate']);
                                        $patient->setGender($patientInfos['gender']);
                                        $patient->setStreet($patientInfos['street']);
                                        $patient->setCity($city);
                                        $patient->setPostalCode($postalCode);
                                        $patient->setIsActive(true);
                                        $em->persist($patient);
                                        $em->flush();
                                        foreach ($patientInfos['referringPhysicians'] as $rp){
                                            $referringPhysician = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->findOneBy(array('fullName' => $rp['firstName'] . ' ' . $rp['lastName']));
                                            $patientReferringPhysician = new PatientReferringProviderEntity();
                                            if(!$referringPhysician) {
                                                $referringPhysician = new ReferringProviderEntity();
                                                $referringPhysician->setFirstName($rp['firstName']);
                                                $referringPhysician->setLastName($rp['lastName']);
                                                $referringPhysician->setHonorific(ReferringProviderEntity::HONORIFIC_DR);
                                                $em->persist($referringPhysician);
                                            }
                                            $patientReferringPhysician->setReferringProvider($referringPhysician);
                                            $patientReferringPhysician->setPatient($patient);
                                            $patientReferringPhysician->setStartDate(date('m/d/Y'));
                                            $em->persist($patientReferringPhysician);
                                            $em->flush();
                                        }
                                        $patientFile = new PatientFileEntity();
                                        $patientFile->setNote('HL7 file');
                                        $patientFile->setPatient($patient);
                                        $em->persist($patientFile);
                                        $em->flush();
                                        $baseName = $patientFile->getId() . '-' . time() . '.' . pathinfo($_FILES['file']['name'][$x], PATHINFO_EXTENSION);
                                        $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;

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

                                        }
                                        break;

                                    /*--------------------------------------------------------------------------------------------------------*/
                                    /*					ADT A04 - A05 	Patient Registration/Info Update 									  */
                                    /*--------------------------------------------------------------------------------------------------------*/
                                    case 'ADT^A04' :
                                    case 'ADT^A05' :
                                        if(isset($patientDetails[16])){
                                            $detail = explode('^', $patientDetails[16]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['healthCardNo'] = $detail[0];
                                            }else{
                                                $patientInfos['healthCardNo'] = '';
                                            }
                                        }
                                        if(isset($patientDetails[18])){
                                            $detail = explode('^', $patientDetails[18]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['lastName'] = $detail[0];
                                            }else{
                                                $patientInfos['lastName'] = '';
                                            }
                                            if(isset($detail[1]) && $detail[1] != 'null'){
                                                $patientInfos['firstName'] = $detail[1];
                                            }else{
                                                $patientInfos['firstName'] = '';
                                            }
                                        }

                                        if(isset($patientDetails[20])){
                                            $date = date_create_from_format("YmdHis",$patientDetails[20]);
                                            $startDate = date('m/d/Y', strtotime($dttst->transform($date)));
                                            $patientInfos['birthDate'] = $startDate;

                                        }

                                        if(isset($patientDetails[21])){
                                            $patientInfos['gender'] = $patientDetails[21] == 'M' ? 'Male' : 'Female';

                                        }

                                        if(isset($patientDetails[24])){
                                            $detail = explode('^', $patientDetails[24]);
                                            if(isset($detail[0]) && $detail[0] != 'null'){
                                                $patientInfos['street'] = $detail[0];
                                            }else{
                                                $patientInfos['street'] = '';
                                            }
                                            if(isset($detail[2]) && $detail[2] != 'null'){
                                                $patientInfos['city'] = $detail[2];
                                            }else{
                                                $patientInfos['city'] = '';
                                            }
                                            if(isset($detail[4]) && $detail[4] != 'null'){
                                                $postalCode = explode(' ', $detail[4]);
                                                $res = str_replace("PV1", "", $postalCode[1]);
                                                unset($postalCode[1]);
                                                $postalCode[] = trim($res);
                                                $patientInfos['postalCode'] = $postalCode[0] . ' ' . $postalCode[2];
                                            }else{
                                                $patientInfos['postalCode'] = '';
                                            }
                                        }

                                        if(isset($patientDetails[32])){
                                            $rps = explode('~', $patientDetails[32]);
                                            $referringPhysicians = array();
                                            foreach ($rps as $key => $rp){
                                                $referringPhysician = explode('^', $rp);
                                                $referringPhysicians[$key]['lastName'] = $referringPhysician[1];
                                                $referringPhysicians[$key]['firstName'] = $referringPhysician[2];
                                            }
                                            $patientInfos['referringPhysicians'] = $referringPhysicians;
                                        }
                                        $city = $em->getRepository('RxConnexionBundle:CityEntity')->findOneBy(array('description' => $patientInfos['city']));
                                        $postalCode = $em->getRepository('RxConnexionBundle:PostalCodeEntity')->findOneBy(array('description' => $patientInfos['postalCode']));
                                        $patient = new PatientEntity();
                                        $patient->setAlbertaHealthCardNo($patientInfos['healthCardNo']);
                                        $patient->setFirstName($patientInfos['firstName']);
                                        $patient->setLastName($patientInfos['lastName']);
                                        $patient->setBirthDate($patientInfos['birthDate']);
                                        $patient->setGender($patientInfos['gender']);
                                        $patient->setStreet($patientInfos['street']);
                                        $patient->setCity($city);
                                        $patient->setPostalCode($postalCode);
                                        $patient->setIsActive(true);
                                        $em->persist($patient);
                                        $em->flush();
                                        foreach ($patientInfos['insurances'] as $i){
                                            $insurance = $em->getRepository('RxConnexionBundle:InsuranceEntity')->findOneBy(array('description' => $i['name']));
                                            $patientInsurance = new PatientInsuranceEntity();
                                            if(!$insurance) {
                                                $insurance = new InsuranceEntity();
                                                $insurance->setDescription($i['name']);
                                                $insurance->setCode($i['name']);
                                                $em->persist($insurance);
                                            }
                                            $patientInsurance->setInsurance($insurance);
                                            $patientInsurance->setPatient($patient);
                                            $patientInsurance->setStartDate($i['startDate']);
                                            $em->persist($patientInsurance);
                                            $em->flush();
                                        }
                                        $patientFile = new PatientFileEntity();
                                        $patientFile->setNote('HL7 file');
                                        $patientFile->setPatient($patient);
                                        $em->persist($patientFile);
                                        $em->flush();
                                        $baseName = $patientFile->getId() . '-' . time() . '.' . pathinfo($_FILES['file']['name'][$x], PATHINFO_EXTENSION);
                                        $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;

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

                                        }
                                        break;

                                }
                                $result['successess'][] = true;
                            }else{
                                $result['successess'][] = false;
                                $result['errors'][] = $_FILES['file']['name'][$x] . ' patient already exists.';
                            }
                        }else{
                            $result['successess'][] = false;
                            $result['errors'][] = $_FILES['file']['name'][$x] . ' has invalid HL7 type for upload.';
                        }
                    }else{
                        $result['successess'][] = false;
                        $result['errors'][] = $_FILES['file']['name'][$x] . ' has invalid file format.';
                    }
                }
            }
            if(in_array(true, $result['successess'])){
                if(isset($result['errors'])){
                    $msgs = '';
                    foreach($result['errors'] as $msg) {
                        $msgs .= $msg . '<br />';
                    }
                    $this->get('session')->getFlashBag()->set('success_messages', 'File Successfully Uploaded with exception(s) ' . $msgs  );
                }else{
                    $this->get('session')->getFlashBag()->set('success_messages', 'File Successfully Uploaded');
                }
            }else{
                $msgs = '';
                foreach($result['errors'] as $msg) {
                    $msgs .= $msg . '<br />';
                }
                $this->get('session')->getFlashBag()->set('error_messages', $msgs );
            }
        }
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/detail/{patient_id}",
     *      name = "patient_detail"
     * )
     */
    public function detailAction($patient_id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));
        $latestPatientChartWithVitals = $em->getRepository('RxConnexionBundle:PatientChartEntity')->getPatientLatestChartWithVitals(base64_decode($patient_id));
        //$lastPatientChartWithVitals = $em->getRepository('RxConnexionBundle:PatientChartEntity')->getPatientLastChartWithVitals(base64_decode($patient_id));
        $lastPatientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->getPatientLastChart(base64_decode($patient_id));
        $patientProfileAssessment = $em->getRepository('RxConnexionBundle:PatientChartEntity')->patientProfileAssessment(base64_decode($patient_id));
        $latestRedFlag = $em->getRepository('RxConnexionBundle:PatientRedFlagEntity')->latestRedFlag(base64_decode($patient_id));
        $redFlagValidation = $em->getRepository('RxConnexionBundle:PatientRedFlagEntity')->redFlagValidation(base64_decode($patient_id));
        $letterStatus = $em->getRepository('RxConnexionBundle:PatientLetterStatusEntity')->findAll();
        $accountReceivable = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->arPatientDashboard(base64_decode($patient_id));
        $patientReferringProviderNote = $em->getRepository('RxConnexionBundle:PatientReferringProviderEntity')->patientReferringProviderNote(base64_decode($patient_id));
        $overview = $em->getRepository('RxConnexionBundle:PatientEntity')->overviewHealthFacility(base64_decode($patient_id));
        $invoiceNo = $request->get('invoiceNo');
        $letterId = $request->get('letter');


        $googleMapsImg = '';
        if($patient->getPostalCode() && $patient->getCity()){
            $province = $patient->getCity()->getProvince() ? $patient->getCity()->getProvince()->getDescription() : '';
            $googleMapsImg = "https://maps.googleapis.com/maps/api/staticmap?center=" . urlencode($patient->getStreet() . ' ' . $patient->getCity()->getDescription() . ', ' . $province . ' ' . 'Canada' . ' ' . $patient->getPostalCode()->getDescription()) . "&zoom=13&size=450x465&maptype=roadmap&markers=color:red%7Clabel:P%7C" . urlencode($patient->getGeoLat()) . "," . urlencode($patient->getGeoLong()) ."&key=" . $this->container->getParameter('google_map_api_key');
        }

        $is_Exist = null;
        foreach($redFlagValidation as $rfv) {
            $is_Exist = $rfv['validation'];
        }

        /* CHECK FOR FINANCING BILLING */

        $checkFinanceBillToday = $this->check_financing_billing_today($patient);
        if($checkFinanceBillToday > 0){
            $this->get('session')->getFlashBag()->set('success_messages', "$checkFinanceBillToday Bill has been successfully generated.");
        }

        $title = 'Manage Patient - ' . $patient->getFullName();
        return $this->render('@RxConnexion/Patient/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/patient/patient_detail.js?v=1.3.9'
            ),
            'patient_id' => $patient_id,
            'patient' => $patient,
            'patientOverview' => $overview,
            'redFlagValid' => $is_Exist,
            'patientLetterStatus' => $letterStatus,
            'patientRedFlag' => isset($latestRedFlag) ? $latestRedFlag : null,
            'lastPatientChart' => isset($lastPatientChart) ? $lastPatientChart : null,
            'patientProfileAssessment' => isset($patientProfileAssessment) ? $patientProfileAssessment : null,
            //'lastPatientChartWithVitals' => isset($lastPatientChartWithVitals) ? $lastPatientChartWithVitals : null,
            'latestPatientChartWithVitals' => isset($latestPatientChartWithVitals) ? $latestPatientChartWithVitals : null,
            'accountReceivable' => isset($accountReceivable) ? $accountReceivable : null,
            'tab' => $request->query->get('tab'),
            'tab2' => $request->query->get('tab2'),
            'googleMapApiKey' => $this->container->getParameter('google_map_api_key'),
            'staticMap' => $googleMapsImg,
            'invoiceNo' => $invoiceNo,
            'letterId' => base64_decode($letterId),
            'patientReferringProviderNote' => $patientReferringProviderNote,
            'noteTemplateAccess' => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
        ));
    }

    /**
     * @Route("/patient_chart_ajax_list", name="patient_chart_ajax_list")
     */
    public function patient_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 Patient Chart Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Chart Transfer'), false);

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

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

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

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Encounter' value='$id' class='patient-file-checkbox'>";
                }

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

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

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

        return new JsonResponse($result);
    }

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

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

        $em = $this->getDoctrine()->getManager();
        $accountUserId = $request->get('au');

        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));
        $company = $patient->getActiveHealthFacility()->getCompany();
        $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->find(base64_decode($id));
        $latestRedFlag = $em->getRepository('RxConnexionBundle:PatientRedFlagEntity')->latestRedFlag(base64_decode($patient_id));
        $accountUser = !empty($accountUserId) && !is_null($accountUserId) ? $em->getRepository('RxConnexionBundle:AccountUserEntity')->find(base64_decode($accountUserId)) : null;

        if(!$patientChart) {
            $patientChart = new PatientChartEntity();
            $chartType = $em->getRepository('RxConnexionBundle:ChartTypeEntity')->findOneBy(array());
            $patientChart->setChartType($chartType);
            foreach($chartType->getMethods() as $method){
                $patientChartTypeMethod = new PatientChartTypeMethodEntity();
                $patientChartTypeMethod->setChartTypeMethod($method);
                $patientChart->addChartTypeMethod($patientChartTypeMethod);
            }
        }
        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientChartForm::class, $patientChart, $formOptions);

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

            $patientChart_form = $request->get($form->getName());
            $result = $this->processPatientChartForm($patientChart_form, $patientChart, $form, $request);

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

        $checkExistInitialAssessment = $em->getRepository('RxConnexionBundle:PatientChartEntity')->checkExistInitialAssessment(array(
            'patient_id' => base64_decode($patient_id)
        ));

        $overview = $em->getRepository('RxConnexionBundle:PatientEntity')->overviewHealthFacility(base64_decode($patient_id));

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

        return $this->render('@RxConnexion/Patient/patient_chart_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/patient/patient_chart_form.js?v=1.0.13'),
            'form' => $form->createView(),
            'action' => $action,
            'patientRedFlag' => isset($latestRedFlag) ? $latestRedFlag : null,
            'patientOverview' => $overview,
            'id' => $id,
            'patient_id' => $patient_id,
            'patient' => $patient,
            'patientChart' => $patientChart,
            'checkExistInitialAssessment' => $checkExistInitialAssessment,
            'accountUser' => $accountUser,
            'noteTemplateAccess' => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
            'company_id' => $company->getId(),
            'tab' => $request->query->get('tab')
        ));
    }

    private function processPatientChartForm($patientChart_form, $patientChart, $form, Request $request) {
        $oldStatus = $patientChart->getChartStatus() ? $patientChart->getChartStatus()->getDescription() : '';
        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:PatientChartEntity')->validate($patientChart_form);

        if(!count($errors)) {

            switch($patientChart_form['action']) {

                case 'n': // new

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

                        $em->persist($patientChart);
                        if(isset($patientChart_form['is_endorsed']) && $patientChart_form['is_endorsed']  != 0) {
                            $ticket = new TicketEntity();
                            $ticket->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $patientChart_form['account_user_endorsed_by']));
                            $ticket->setTicketStatus($em->getReference('RxConnexionBundle:TicketStatusEntity' ,$patientChart_form['ticket_status_id']));
                            $ticket->setTicketSeverity($em->getReference('RxConnexionBundle:TicketSeverityEntity', $patientChart_form['ticket_severity_id']));
                            $em->persist($ticket);
                            $patientChartTicket = new PatientChartTicketEntity();
                            $patientChartTicket->setTicket($ticket);
                            $patientChartTicket->setPatientChart($patientChart);
                            $em->persist($patientChartTicket);
                            $patientTicket = new PatientTicketEntity();
                            $patientTicket->setPatient($patientChart->getPatient());
                            $patientTicket->setTicket($ticket);
                            $em->persist($patientTicket);

                            if (!empty($patientChart_form['patientChartCcs'])) {
                                foreach ($patientChart_form['patientChartCcs'] as $patientChartCc) {
                                    $ticketCc = new TicketCcEntity();
                                    $ticketCc->setTicket($ticket);
                                    $ticketCc->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $patientChartCc['accountUser']));
                                    $em->persist($ticketCc);
                                }
                            }

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

                        //insert notes on patient_chart_note and patient_note
                        if($patientChart_form['note'] != null || $patientChart_form['note'] != ''){
                            $patientChartNote = new PatientChartNoteEntity();
                            $patientChartNote->setNote($patientChart->getNote());
                            $patientChartNote->setPatientChart($patientChart);
                            $em->persist($patientChartNote);
                            $patientNote = new PatientNoteEntity();
                            $patientNote->setNote('From chart no. ' . $patientChartNote->getPatientChart()->getPatientChartIdWithLink(). ' - ' . $patientChartNote->getNote());
                            $patientNote->setType($patientChart_form['note_type']);
                            $patientNote->setPatient($patientChartNote->getPatientChart()->getPatient());
                            $em->persist($patientNote);
                        }

                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Patient Encounter',
                            $em->getClassMetadata(PatientChartEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientChart;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

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

                    if(isset($patientChart_form['is_endorsed']) && $patientChart_form['is_endorsed']  != 0) {
                        $ticket = new TicketEntity();
                        $ticket->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $patientChart_form['account_user_endorsed_by']));
                        $ticket->setTicketStatus($em->getReference('RxConnexionBundle:TicketStatusEntity' ,$patientChart_form['ticket_status_id']));
                        $ticket->setTicketSeverity($em->getReference('RxConnexionBundle:TicketSeverityEntity', $patientChart_form['ticket_severity_id']));
                        $em->persist($ticket);
                        $patientChartTicket = new PatientChartTicketEntity();
                        $patientChartTicket->setTicket($ticket);
                        $patientChartTicket->setPatientChart($patientChart);
                        $em->persist($patientChartTicket);
                        $patientTicket = new PatientTicketEntity();
                        $patientTicket->setPatient($patientChart->getPatient());
                        $patientTicket->setTicket($ticket);
                        $em->persist($patientTicket);

                        if (!empty($patientChart_form['patientChartCcs'])) {
                            foreach ($patientChart_form['patientChartCcs'] as $patientChartCc) {
                                $ticketCc = new TicketCcEntity();
                                $ticketCc->setTicket($ticket);
                                $ticketCc->setAccountUser($em->getReference('RxConnexionBundle:AccountUserEntity', $patientChartCc['accountUser']));
                                $em->persist($ticketCc);
                            }
                        }

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

                    $newAT = new AuditTrailEntity(
                        'Patient Encounter',
                        $em->getClassMetadata(PatientChartEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientChart;
                    $newAT->parseOriginalDetails();

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

                        if($oldStatus != $newStatus){
                            $schedule = $patientChart->getSchedule();
                            if($schedule){
                                $scheduleStatus = $em->getRepository('RxConnexionBundle:ScheduleStatusEntity')->findOneBy(array('description' => $newStatus));
                                if($scheduleStatus){
                                    $schedule->setScheduleStatus($scheduleStatus);
                                }else{
                                    $scheduleStatus = $em->getRepository('RxConnexionBundle:ScheduleStatusEntity')->findOneBy(array('isLast' => true));
                                    $schedule->setScheduleStatus($scheduleStatus);
                                }
                            }
                        }
                        if($patientChart_form['note'] != null || $patientChart_form['note'] != ''){
                            $patientChartNote = new PatientChartNoteEntity();
                            $patientChartNote->setNote($patientChart->getNote());
                            $patientChartNote->setPatientChart($patientChart);
                            $em->persist($patientChartNote);
                            $patientNote = new PatientNoteEntity();
                            $patientNote->setNote('From chart no. ' . $patientChartNote->getPatientChart()->getPatientChartIdWithLink(). ' - ' . $patientChartNote->getNote());
                            $patientNote->setType($patientChart_form['note_type']);
                            $patientNote->setPatient($patientChartNote->getPatientChart()->getPatient());
                            $em->persist($patientNote);
                        }
                        $em->flush();

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientChart);
                        $patientChart->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("/chart/autocomplete", name="patient_chart_autocomplete")
     */
    public function chart_autocompleteAction(Request $request) {

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

        $result = array(
            'query' => 'patientCharts',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientChartEntity')->autocompleteSuggestions($q)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/chart_for_billing/autocomplete", name="patient_chart_for_billing_autocomplete")
     */
    public function chart_for_billing_autocompleteAction(Request $request) {

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

        $result = array(
            'query' => 'patientCharts',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientChartEntity')->autocompleteSuggestionsForBilling($q)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_chart_file_ajax_list", name="patient_chart_file_ajax_list")
     */
    public function patient_chart_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 Patient Chart File Update'), false);

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

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

                $id = base64_encode($row['id']);
                $action = '';
                $url = $this->generateUrl('patient_chart_file_download', array(
                    'patientChartFile_id' => $id
                ));

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

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

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/chart_file/form/{patientChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_file_form"
     * )
     */
    public function patient_chart_file_formAction($patientChart_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'patient_chart_id' => $patientChart_id
        );
        $form = $this->createForm(PatientChartFileForm::class, $patientChartFile, $formOptions);


        $title = $action === 'n' ? 'Add File' : 'Update ' . 'Patient Encounter File ID:' . $patientChartFile->getId();

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

    /**
     * @Route(
     *      "/patient_chart_file/save_action",
     *      name = "patient_chart_file_save"
     * )
     */
    public function patient_chart_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 Patient Chart File New', 'Admin Patient Chart File Update'))) return $authService->redirectToHome();

        $patientChartFile_form = $request->get('patient_chart_file');
        $em = $this->getDoctrine()->getManager();
        $patientChartFile = $em->getRepository('RxConnexionBundle:PatientChartFileEntity')->find($patientChartFile_form['id'] );
        if(!$patientChartFile) {
            $patientChartFile = new PatientChartFileEntity();
        }
        $formOptions = array(
            'action' => $patientChartFile_form['action'],
            'patient_chart_id' => $patientChartFile_form['patient_chart']
        );
        $form = $this->createForm(PatientChartFileForm::class, $patientChartFile, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientChartFileEntity')->validate($patientChartFile_form);

        if(!count($errors)) {

            switch($patientChartFile_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

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

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

                            }
                        }

                        $newAT = new AuditTrailEntity(
                            'Patient Encounter File',
                            $em->getClassMetadata(PatientChartFileEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientChartFile;
                        $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(
                        'Patient Encounter File',
                        $em->getClassMetadata(PatientChartFileEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientChartFile;
                    $newAT->parseOriginalDetails();

                    $patientChartFile_obj = $em->getRepository('RxConnexionBundle:PatientChartFileEntity')->find($patientChartFile_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'])) {

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

                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $patientChartFile_obj->removeFile();
                                $patientChartFile_obj->setDescription($_FILES['form']['name']['file']);
                                $patientChartFile_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(
                        'Patient Encounter File',
                        $em->getClassMetadata(PatientChartFileEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientChartFile;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $patientChartFile = $em->getRepository('RxConnexionBundle:PatientChartFileEntity')->find($patientChartFile_form['id']);
                        //$em->remove($patientChartFile);
                        $patientChartFile->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("/patient_chart_medical_diagnosis_ajax_list", name="patient_chart_medical_diagnosis_ajax_list")
     */
    public function patient_chart_medical_diagnosis_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 Patient Chart Medical Diagnosis Update'), false);

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

                $values = array(
                    $row['diagnosis_type_desc'],
                    $row['diagnosis_desc'],
                    $row['start_date'],
                    $row['end_date'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_diagnosis/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_diagnosis_form"
     * )
     */
    public function patient_diagnosis_formAction($patient_id, $action, $id) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientDiagnosisForm::class, $patientDiagnosis, $formOptions);


        $title = $action === 'n' ? 'New Diagnosis' : 'Update ' . 'Diagnosis ID: ' . $patientDiagnosis->getId();

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

    /**
     * @Route(
     *      "/patient_diagnosis/save_action",
     *      name = "patient_diagnosis_save"
     * )
     */
    public function patient_diagnosis_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 Patient Chart Medical Diagnosis New', 'Admin Patient Chart Medical Diagnosis Update'))) return $authService->redirectToHome();

        $patientDiagnosis_form = $request->get('patient_diagnosis');
        $em = $this->getDoctrine()->getManager();
        $patientDiagnosis = $em->getRepository('RxConnexionBundle:PatientDiagnosisEntity')->find($patientDiagnosis_form['id'] );
        if(!$patientDiagnosis) {
            $patientDiagnosis = new PatientDiagnosisEntity();
        }
        $formOptions = array(
            'action' => $patientDiagnosis_form['action'],
            'patient_id' => $patientDiagnosis_form['patient']
        );
        $form = $this->createForm(PatientDiagnosisForm::class, $patientDiagnosis, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientDiagnosisEntity')->validate($patientDiagnosis_form);

        if(!count($errors)) {

            switch($patientDiagnosis_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Diagnosis',
                            $em->getClassMetadata(PatientDiagnosisEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientDiagnosis;
                        $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(
                        'Patient Diagnosis',
                        $em->getClassMetadata(PatientDiagnosisEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientDiagnosis;
                    $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(
                        'Patient Diagnosis',
                        $em->getClassMetadata(PatientDiagnosisEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientDiagnosis;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientDiagnosis);
                        $patientDiagnosis->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("/patient_chart_medical_diagnosis_medication_ajax_list", name="patient_chart_medical_diagnosis_medication_ajax_list")
     */
    public function patient_chart_medical_diagnosis_medication_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 Patient Chart Medical Medication Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientDiagnosisMedicationEntity')->ajax_list($get, $this->get('session')->get('userData'));
            foreach($data['results'] as $row) {

                $id = base64_encode($row['id']);
                $patientDiagnosis_id = base64_encode($get['patientDiagnosis_id']);
                $class = 'action-button-style href-patient-chart-medical-diagnosis-medication-form' . $get['patientDiagnosis_id'];
                $action = '';

                if($hasUpdate) {
                    $action = "<a class= '$class' data-action='u' data-pd-id='$patientDiagnosis_id' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['medication_desc'],
                    $row['start_date'],
                    $row['end_date'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_diagnosis_medication/form/{patientDiagnosis_id}/{action}/{id}",
     *      defaults = {
     *          "patientDiagnosis_id": "",
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_diagnosis_medication_form"
     * )
     */
    public function patient_diagnosis_medication_formAction($patientDiagnosis_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patientDiagnosis_id' => $patientDiagnosis_id
        );
        $form = $this->createForm(PatientDiagnosisMedicationForm::class, $patientDiagnosisMedication, $formOptions);


        $title = $action === 'n' ? 'New Medication' : 'Update ' . 'Medication ID: ' . $patientDiagnosisMedication->getId();

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

    /**
     * @Route(
     *      "/patient_diagnosis_medication/save_action",
     *      name = "patient_diagnosis_medication_save"
     * )
     */
    public function patient_diagnosis_medication_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 Patient Chart Medical Medication New', 'Admin Patient Chart Medical Medication Update'))) return $authService->redirectToHome();

        $patientDiagnosisMedication_form = $request->get('patient_diagnosis_medication');
        $em = $this->getDoctrine()->getManager();
        $patientDiagnosisMedication = $em->getRepository('RxConnexionBundle:PatientDiagnosisMedicationEntity')->find($patientDiagnosisMedication_form['id']);
        if(!$patientDiagnosisMedication) {
            $patientDiagnosisMedication = new PatientDiagnosisMedicationEntity();
        }
        $formOptions = array(
            'action' => $patientDiagnosisMedication_form['action'],
            'patientDiagnosis_id' => $patientDiagnosisMedication_form['patient_diagnosis']
        );
        $form = $this->createForm(PatientDiagnosisMedicationForm::class, $patientDiagnosisMedication, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientDiagnosisMedicationEntity')->validate($patientDiagnosisMedication_form);

        if(!count($errors)) {

            switch($patientDiagnosisMedication_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Diagnosis Medication',
                            $em->getClassMetadata(PatientDiagnosisMedicationEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientDiagnosisMedication;
                        $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(
                        'Patient Diagnosis Medication',
                        $em->getClassMetadata(PatientDiagnosisMedicationEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientDiagnosisMedication;
                    $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(
                        'Patient Diagnosis Medication',
                        $em->getClassMetadata(PatientDiagnosisMedicationEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientDiagnosisMedication;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientDiagnosisMedication);
                        $patientDiagnosisMedication->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("/patient_chart_billing_procedure_ajax_list", name="patient_chart_billing_procedure_ajax_list")
     */
    public function patient_chart_billing_procedure_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 Patient Chart Billing Procedure Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientChartProcedureEntity')->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-patient-chart-billing-procedure-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['chartProcedure_desc'],
                    '&#36;' .number_format($row['amount'], 2, '.', ','),
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_chart_procedure/form/{patientChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_procedure_form"
     * )
     */
    public function patient_chart_procedure_formAction($patientChart_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patientChart_id' => $patientChart_id
        );
        $form = $this->createForm(PatientChartProcedureForm::class, $patientChartProcedure, $formOptions);


        $title = $action === 'n' ? 'New Billing' : 'Update ' . 'Billing ' . $patientChartProcedure->getId();

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

    /**
     * @Route(
     *      "/patient_chart_procedure/save_action",
     *      name = "patient_chart_procedure_save"
     * )
     */
    public function patient_chart_procedure_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 Patient Chart Billing Procedure New', 'Admin Patient Chart Billing Procedure Update'))) return $authService->redirectToHome();

        $patientChartProcedure_form = $request->get('patient_chart_procedure');
        $em = $this->getDoctrine()->getManager();
        $patientChartProcedure = $em->getRepository('RxConnexionBundle:PatientChartProcedureEntity')->find($patientChartProcedure_form['id']);
        if(!$patientChartProcedure) {
            $patientChartProcedure = new PatientChartProcedureEntity();
        }
        $formOptions = array(
            'action' => $patientChartProcedure_form['action'],
            'patientChart_id' => $patientChartProcedure_form['patient_chart']
        );
        $form = $this->createForm(PatientChartProcedureForm::class, $patientChartProcedure, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientChartProcedureEntity')->validate($patientChartProcedure_form);

        if(!count($errors)) {

            switch($patientChartProcedure_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Encounter Procedure',
                            $em->getClassMetadata(PatientChartProcedureEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientChartProcedure;
                        $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(
                        'Patient Encounter Procedure',
                        $em->getClassMetadata(PatientChartProcedureEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientChartProcedure;
                    $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(
                        'Patient Encounter Procedure',
                        $em->getClassMetadata(PatientChartProcedureEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientChartProcedure;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientChartProcedure);
                        $patientChartProcedure->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("/patient_chart_billing_other_ajax_list", name="patient_chart_billing_other_ajax_list")
     */
    public function patient_chart_billing_other_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 Patient Chart Billing Other Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientChartOtherProcedureEntity')->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-patient-chart-billing-other-procedure-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    '&#36;' .number_format($row['amount'], 2, '.', ','),
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_chart_other_procedure/form/{patientChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_other_procedure_form"
     * )
     */
    public function patient_chart_other_procedure_formAction($patientChart_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patientChart_id' => $patientChart_id
        );
        $form = $this->createForm(PatientChartOtherProcedureForm::class, $patientChartOtherProcedure, $formOptions);


        $title = $action === 'n' ? 'New Other Procedure Billing' : 'Update ' . 'Other Procedure Billing ' . $patientChartOtherProcedure->getId();

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

    /**
     * @Route(
     *      "/patient_chart_other_procedure/save_action",
     *      name = "patient_chart_other_procedure_save"
     * )
     */
    public function patient_chart_other_procedure_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 Patient Chart Billing Other Procedure New', 'Admin Patient Chart Billing Other Procedure Update'))) return $authService->redirectToHome();

        $patientChartOtherProcedure_form = $request->get('patient_chart_other_procedure');
        $em = $this->getDoctrine()->getManager();
        $patientChartOtherProcedure = $em->getRepository('RxConnexionBundle:PatientChartOtherProcedureEntity')->find($patientChartOtherProcedure_form['id']);
        if(!$patientChartOtherProcedure) {
            $patientChartOtherProcedure = new PatientChartOtherProcedureEntity();
        }
        $formOptions = array(
            'action' => $patientChartOtherProcedure_form['action'],
            'patientChart_id' => $patientChartOtherProcedure_form['patient_chart']
        );
        $form = $this->createForm(PatientChartOtherProcedureForm::class, $patientChartOtherProcedure, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientChartOtherProcedureEntity')->validate($patientChartOtherProcedure_form);

        if(!count($errors)) {

            switch($patientChartOtherProcedure_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Encounter Other Procedure',
                            $em->getClassMetadata(PatientChartOtherProcedureEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientChartOtherProcedure;
                        $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(
                        'Patient Encounter Other Procedure',
                        $em->getClassMetadata(PatientChartOtherProcedureEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientChartOtherProcedure;
                    $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(
                        'Patient Encounter Other Procedure',
                        $em->getClassMetadata(PatientChartOtherProcedureEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientChartOtherProcedure;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientChartOtherProcedure);
                        $patientChartOtherProcedure->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("/patient_chart_payment_ajax_list", name="patient_chart_payment_ajax_list")
     */
    public function patient_chart_payment_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 Patient Chart Payment Update'), false);

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

                $values = array(
                    $row['payment_type'],
                    $row['payment_date'],
                    $row['or_no'],
                    $row['dr_no'],
                    $row['barcode'],
                    $row['check_no'],
                    $row['check_date'],
                    '&#36;' .number_format($row['amount'], 2, '.', ','),
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_chart_payment/form/{patientChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_payment_form"
     * )
     */
    public function patient_chart_payment_formAction($patientChart_id, $action, $id) {

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

        $em = $this->getDoctrine()->getManager();
        $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->find(base64_decode($patientChart_id));
        $patientChartPayment = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->find(base64_decode($id));
        if(!$patientChartPayment) {
            $patientChartPayment = new PatientChartPaymentEntity();
        }
        $patientChartProcedures = $patientChart->getProcedures();
        $patientChartOtherProcedures = $patientChart->getOtherProcedures();
        if($patientChartProcedures->count()){
            foreach ($patientChartProcedures as $patientChartProcedure){
                $patientChartPaymentProcedure = $patientChartPayment->getPaymentProcedureByProcedureId($patientChartProcedure->getId());
                if(!$patientChartPaymentProcedure){
                    $patientChartPaymentProcedure = new PatientChartPaymentProcedureEntity();
                    $patientChartPaymentProcedure->setPatientChartProcedure($patientChartProcedure);
                    $patientChartPayment->addProcedure($patientChartPaymentProcedure);
                }
            }
        }
        if($patientChartOtherProcedures->count()){
            foreach ($patientChartOtherProcedures as $patientChartOtherProcedure){
                $patientChartPaymentOtherProcedure = $patientChartPayment->getPaymentOtherProcedureByOtherProcedureId($patientChartOtherProcedure->getId());
                if(!$patientChartPaymentOtherProcedure){
                    $patientChartPaymentOtherProcedure = new PatientChartPaymentOtherProcedureEntity();
                    $patientChartPaymentOtherProcedure->setPatientChartOtherProcedure($patientChartOtherProcedure);
                    $patientChartPayment->addOtherProcedure($patientChartPaymentOtherProcedure);
                }
            }
        }


        $formOptions = array(
            'action' => $action,
            'patientChart_id' => $patientChart_id
        );
        $form = $this->createForm(PatientChartPaymentForm::class, $patientChartPayment, $formOptions);


        $title = $action === 'n' ? 'New Payment' : 'Update ' . 'Payment ' . $patientChartPayment->getId();

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

    /**
     * @Route(
     *      "/patient_chart_payment/save_action",
     *      name = "patient_chart_payment_save"
     * )
     */
    public function patient_chart_payment_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 Patient Chart Payment New', 'Admin Patient Chart Payment Update'))) return $authService->redirectToHome();

        $patientChartPayment_form = $request->get('patient_chart_payment');
        $em = $this->getDoctrine()->getManager();
        $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->find(base64_decode($patientChartPayment_form['patient_chart']));
        $patientChartPayment = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->find($patientChartPayment_form['id']);
        if(!$patientChartPayment) {
            $patientChartPayment = new PatientChartPaymentEntity();
        }

        $patientChartProcedures = $patientChart->getProcedures();
        $patientChartOtherProcedures = $patientChart->getOtherProcedures();
        if($patientChartProcedures->count()){
            foreach ($patientChartProcedures as $patientChartProcedure){
                $patientChartPaymentProcedure = $patientChartPayment->getPaymentProcedureByProcedureId($patientChartProcedure->getId());
                if(!$patientChartPaymentProcedure){
                    $patientChartPaymentProcedure = new PatientChartPaymentProcedureEntity();
                    $patientChartPaymentProcedure->setPatientChartProcedure($patientChartProcedure);
                    $patientChartPayment->addProcedure($patientChartPaymentProcedure);
                }
            }
        }

        if($patientChartOtherProcedures->count()){
            foreach ($patientChartOtherProcedures as $patientChartOtherProcedure){
                $patientChartPaymentOtherProcedure = $patientChartPayment->getPaymentOtherProcedureByOtherProcedureId($patientChartOtherProcedure->getId());
                if(!$patientChartPaymentOtherProcedure){
                    $patientChartPaymentOtherProcedure = new PatientChartPaymentOtherProcedureEntity();
                    $patientChartPaymentOtherProcedure->setPatientChartOtherProcedure($patientChartOtherProcedure);
                    $patientChartPayment->addOtherProcedure($patientChartPaymentOtherProcedure);
                }
            }
        }
        $formOptions = array(
            'action' => $patientChartPayment_form['action'],
            'patientChart_id' => $patientChartPayment_form['patient_chart']
        );
        $form = $this->createForm(PatientChartPaymentForm::class, $patientChartPayment, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientChartPaymentEntity')->validate($patientChartPayment_form);

        if(!count($errors)) {

            switch($patientChartPayment_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Encounter Payment',
                            $em->getClassMetadata(PatientChartPaymentEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientChartPayment;
                        $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(
                        'Patient Encounter Payment',
                        $em->getClassMetadata(PatientChartPaymentEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientChartPayment;
                    $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(
                        'Patient Encounter Payment',
                        $em->getClassMetadata(PatientChartPaymentEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientChartPayment;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientChartPayment);
                        $patientChartPayment->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("/patient_file_ajax_list", name="patient_file_ajax_list")
     */
    public function patient_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 Patient File Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient File Transfer'), false);
            $hasHl7 = $authService->isUserHasAccesses(array('Admin Patient Export HL7'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientFileEntity')->ajax_list($get, $this->get('session')->get('userData'));
            //$data2 = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientChartFileEntity')->manage_patient_ajax_list($get, $this->get('session')->get('userData'));

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

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

                $url = null;
                if($row['faxingOptionIdEncoded'] != '' || $row['faxingOptionIdEncoded'] != null) {
                    $url = $this->generateUrl('faxing_option_patient_file_download', array(
                        'faxingOption_id' => $row['faxingOptionIdEncoded']
                    ));
                } else if($row['faxTranId'] != '' || $row['faxTranId'] != null) {
                    $url = $this->generateUrl('fax_view', array(
                        'id' => $row['faxTranId'],
                        'sDirection' => 'IN'
                    ));
                } else {
                    $url = $this->generateUrl('patient_file_download', array(
                        'patientFile_id' => $id
                    ));
                }

                if($hasUpdate) {
                    $action .= "<a class='action-button-style href-patient-file-form' data-action='u' data-id='$id'>Update</a>";
                }
                if($hasHl7) {
                    $urlHl7 = $this->generateUrl('patient_export_hl7', array('patient_id' => $patient_id, 'type' => 'MDM-T01', 'fileName' => $row['description'], 'fileId' => $row['id']));
                    $action .= "<a href='$urlHl7' title='Export to HL7 Format' class='action-button-style' style='min-width: unset!important;'><i class='fa fa-file-code-o'></i></a>";
                }

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id' data-type='File' value='$id' class='patient-chart-checkbox'>";
                }

                $values = array(
                    $transferLink.$row['date'],
                    $row['user'],
                    "<a href='$url' target='_blank'>". $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/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_file_form"
     * )
     */
    public function patient_file_formAction($patient_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );

        $form = $this->createForm(PatientFileForm::class, $patientFile, $formOptions);


        $title = $action === 'n' ? 'Add File' : 'Update ' . 'Patient File ID:' . $patientFile->getId();

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_file_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'patient_id' => $patient_id,
            'action' => $action,
            'tab' => $request->query->get('tab'),
            'id' => $id
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }
    /**
     * @Route(
     *      "/patient_file/save_action",
     *      name = "patient_file_save"
     * )
     */
    public function patient_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 Patient File New', 'Admin Patient File Update'))) return $authService->redirectToHome();

        $patientFile_form = $request->get('patient_file');
        $em = $this->getDoctrine()->getManager();
        $patientFile = $em->getRepository('RxConnexionBundle:PatientFileEntity')->find($patientFile_form['id'] );
        if(!$patientFile) {
            $patientFile = new PatientFileEntity();
        }
        $formOptions = array(
            'action' => $patientFile_form['action'],
            'patient_id' => $patientFile_form['patient']
        );
        $form = $this->createForm(PatientFileForm::class, $patientFile, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientFileEntity')->validate($patientFile_form);

        if(!count($errors)) {

            switch($patientFile_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

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

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

                            }
                        }

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

                    $patientFile_obj = $em->getRepository('RxConnexionBundle:PatientFileEntity')->find($patientFile_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'])) {

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientFile);
                        $patientFile->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/{patientFile_id}",
     *
     *      name = "patient_file_download"
     * )
     */
    public function patient_file_downloadAction($patientFile_id){

        $em = $this->getDoctrine()->getManager();
        $patientFile = $em->getRepository('RxConnexionBundle:PatientFileEntity')->find(base64_decode($patientFile_id));
        header('Content-Disposition: attachment; filename="' . $patientFile->getDescription() . '"');
        if($patientFile->getFileType()){
            if($patientFile->getFileType()->getDescription() == 'Referral Fax') {
                $patientFile_fileName = explode('.', $patientFile->getDescription());
                $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->findOneBy(array('fileName' => $patientFile_fileName[0]));
                if (!$faxTran) {
                    $fileName = null;
                } else {
                    $fileName = $faxTran->getFaxId() . '.pdf';
                }
                $uploadDir = __DIR__ . '/../../../web/uploads/fax';
            }else{
                $fileName = $patientFile->getParsedDescription();
                $uploadDir = $patientFile->getUploadRootDir() ;
            }
        } else {
            $fileName = $patientFile->getParsedDescription();
            $uploadDir = $patientFile->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(
     *      "/chart_file/download/{patientChartFile_id}",
     *      name = "patient_chart_file_download"
     * )
     */
    public function patient_chart_file_downloadAction($patientChartFile_id){

        $em = $this->getDoctrine()->getManager();
        $patientChartFile = $em->getRepository('RxConnexionBundle:PatientChartFileEntity')->find(base64_decode($patientChartFile_id));


        header('Content-Disposition: attachment; filename="' . $patientChartFile->getDescription() . '"');

        $handle = fopen(realpath($patientChartFile->getUploadRootDir()) . '/' . $patientChartFile->getParsedDescription(), 'rb');
        $chunkSize = 1024*1024;

        if($handle !== false) {

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

            fclose($handle);
        }

        exit();
    }

    /**
     * @Route("/patient_insurance_ajax_list", name="patient_insurance_ajax_list")
     */
    public function patient_insurance_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 Patient Insurance Update'), false);

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

                $values = array(
                    $row['insurance_desc'],
                    $row['insurance_no'],
                    $row['plan_contact_no'],
                    $row['fax_no'],
                    $row['phone_no'],
                    $row['mobile_no'],
                    $row['expire_date'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }
    /**
     * @Route(
     *      "/patient_insurance/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_insurance_form"
     * )
     */
    public function patient_insurance_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientInsuranceForm::class, $patientInsurance, $formOptions);


        $title = $action === 'n' ? 'New Insurance' : 'Update ' . $patientInsurance->getInsurance()->getDescription();

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

    /**
     * @Route(
     *      "/patient_insurance_medication/save_action",
     *      name = "patient_insurance_save"
     * )
     */
    public function patient_insurance_medication_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 Patient Insurance New', 'Admin Patient Insurance Update'))) return $authService->redirectToHome();

        $patientInsurance_form = $request->get('patient_insurance');
        $em = $this->getDoctrine()->getManager();
        $patientInsurance = $em->getRepository('RxConnexionBundle:PatientInsuranceEntity')->find($patientInsurance_form['id']);
        if(!$patientInsurance) {
            $patientInsurance = new PatientInsuranceEntity();
        }
        $formOptions = array(
            'action' => $patientInsurance_form['action'],
            'patient_id' => $patientInsurance_form['patient']
        );
        $form = $this->createForm(PatientInsuranceForm::class, $patientInsurance, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientInsuranceEntity')->validate($patientInsurance_form);

        if(!count($errors)) {

            switch($patientInsurance_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Insurance',
                            $em->getClassMetadata(PatientInsuranceEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientInsurance;
                        $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(
                        'Patient Insurance',
                        $em->getClassMetadata(PatientInsuranceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientInsurance;
                    $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(
                        'Patient Insurance',
                        $em->getClassMetadata(PatientInsuranceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientInsurance;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

    // ========================= REFERRING HEALTH FACILITY

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

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

                $values = array(
                    $row['health_facility'],
                    $row['address'],
                    $row['fax_no'],
                    $row['phone_no'],
                    $row['fax_no'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_referring_health_facility/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_referring_health_facility_form"
     * )
     */
    public function patient_referring_health_facility_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientReferringHealthFacilityForm::class, $patientHealthFacility, $formOptions);

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

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

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

        $patientReferringHealthFacility_form = $request->get('patient_referring_health_facility');
        $em = $this->getDoctrine()->getManager();
        $patientReferringHealthFacility = $em->getRepository('RxConnexionBundle:PatientReferringHealthFacilityEntity')->find($patientReferringHealthFacility_form['id']);
        if(!$patientReferringHealthFacility) {
            $patientReferringHealthFacility = new PatientReferringHealthFacilityEntity();
        }

        $formOptions = array(
            'action' => $patientReferringHealthFacility_form['action'],
            'patient_id' => $patientReferringHealthFacility_form['patient']
        );
        $form = $this->createForm(PatientReferringHealthFacilityForm::class, $patientReferringHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientReferringHealthFacilityEntity')->validate($patientReferringHealthFacility_form);

        if(!count($errors)) {

            switch($patientReferringHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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



    // ========================== REFERRING PROVIDER

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

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

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

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

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Patient Referring Provider Update'), false);

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['fax_no'],
                    $row['phone_no'],
                    $row['mobile_no'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_referring_provider/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_referring_provider_form"
     * )
     */
    public function patient_referring_provider_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientReferringProviderForm::class, $patientProvider, $formOptions);

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

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

    /**
     * @Route(
     *      "/patient_referring_provider/save_action",
     *      name = "patient_referring_provider_save"
     * )
     */
    public function patient_referring_provider_saveAction(Request $request) {

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

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

        $patientReferringProvider_form = $request->get('patient_referring_provider');
        $em = $this->getDoctrine()->getManager();
        $patientReferringProvider = $em->getRepository('RxConnexionBundle:PatientReferringProviderEntity')->find($patientReferringProvider_form['id']);
        if(!$patientReferringProvider) {
            $patientReferringProvider = new PatientReferringProviderEntity();
        }

        $formOptions = array(
            'action' => $patientReferringProvider_form['action'],
            'patient_id' => $patientReferringProvider_form['patient']
        );
        $form = $this->createForm(PatientReferringProviderForm::class, $patientReferringProvider, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientReferringProviderEntity')->validate($patientReferringProvider_form);

        if(!count($errors)) {

            switch($patientReferringProvider_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

    // ========================= PATIENT LINKED REFERRING HF AND PROVIDER


    /**
     * @Route(
     *      "/patient_linked_referring_health_facility_and_provider/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_linked_referring_health_facility_and_provider_form"
     * )
     */
    public function patient_linked_referring_health_facility_and_provider_formAction($patient_id, $action, $id, Request $request) {

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

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

        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));

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

            $result = array(
                'success'       => true,
                'errorMessages' => array(),
            );
            $formData = $request->get('patientLinkedReferringHealthFacilityAndProvider');

            if(!empty($formData['referringHealthFacility']) && !empty($formData['referringProvider']) && !empty($formData['startDate'])) {
                $referringHealthProviderHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->findOneBy(array(
                    'referringHealthFacility' => $formData['referringHealthFacility'],
                    'referringProvider'       => $formData['referringProvider']
                ));
                if(!$referringHealthProviderHealthFacility){
                    $referringHealthProviderHealthFacility = new ReferringHealthFacilityProviderEntity();
                    $referringHealthProviderHealthFacility->setReferringProvider($em->getReference('RxConnexionBundle:ReferringProviderEntity', $formData['referringProvider']));
                    $referringHealthProviderHealthFacility->setReferringHealthFacility($em->getReference('RxConnexionBundle:ReferringHealthFacilityEntity', $formData['referringHealthFacility']));
                    $referringHealthProviderHealthFacility->setStartDate($formData['startDate']);
                    $em->persist($referringHealthProviderHealthFacility);
                    $em->flush();
                }

                $patientReferringProviderForm = array(
                    'action'     => 'n',
                    'patient'    => $patient_id,
                    'id'         => '0',
                    'start_date' => $formData['startDate'],
                    'end_date'   => '',
                    'referring_provider' => $formData['referringProvider'],
                );
                $errors = $em->getRepository('RxConnexionBundle:PatientReferringProviderEntity')->validate($patientReferringProviderForm);
                if(!count($errors)){
                    $patientReferringProvider = new PatientReferringProviderEntity();
                    $patientReferringProvider->setPatient($patient);
                    $patientReferringProvider->setReferringProvider($referringHealthProviderHealthFacility->getReferringProvider());
                    $patientReferringProvider->setStartDate($formData['startDate']);
                    $em->persist($patientReferringProvider);
                } else {
                    $result['success'] = false;
                    $result['errorMessages'] = array_merge($result['errorMessages'], $errors);
                }

                $patientReferringHealthFacilityForm = array(
                    'action'     => 'n',
                    'patient'    => $patient_id,
                    'id'         => '0',
                    'start_date' => $formData['startDate'],
                    'end_date'   => '',
                    'referring_health_facility' => $formData['referringHealthFacility'],
                );
                $errors = $em->getRepository('RxConnexionBundle:PatientReferringHealthFacilityEntity')->validate($patientReferringHealthFacilityForm);
                if(!count($errors)){
                    $patientReferringHealthFacility = new PatientReferringHealthFacilityEntity();
                    $patientReferringHealthFacility->setPatient($patient);
                    $patientReferringHealthFacility->setReferringHealthFacility($referringHealthProviderHealthFacility->getReferringHealthFacility());
                    $patientReferringHealthFacility->setStartDate($formData['startDate']);
                    $em->persist($patientReferringHealthFacility);
                } else {
                    $result['success'] = false;
                    $result['errorMessages'] = array_merge($result['errorMessages'], $errors);
                }

                $em->flush();

            } else {
                $result['success'] = false;
                $result['errorMessages'] = array('Please fill up required field.');
            }

            return new JsonResponse($result);
        }

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

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_linked_referring_health_facility_and_provider_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'action' => $action,
            'patient_id' => $patient_id,
            'id' => $id
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }



    // ========================= PATIENT SPECIALIST

    /**
     * @Route("/patient_specialist_ajax_list", name="patient_specialist_ajax_list")
     */
    public function patient_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 Patient Specialist Update'), false);

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['phone_no'],
                    $row['mobile_no'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_specialist/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_specialist_form"
     * )
     */
    public function patient_specialist_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientSpecialistForm::class, $patientSpecialist, $formOptions);

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

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

    /**
     * @Route(
     *      "/patient_specialist/save_action",
     *      name = "patient_specialist_save"
     * )
     */
    public function patient_specialist_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 Patient Specialist New', 'Admin Patient Specialist Update'))) return $authService->redirectToHome();

        $patientSpecialist_form = $request->get('patientSpecialist');
        $em = $this->getDoctrine()->getManager();
        $patientSpecialist = $em->getRepository('RxConnexionBundle:PatientSpecialistEntity')->find($patientSpecialist_form['id']);
        if(!$patientSpecialist) {
            $patientSpecialist = new PatientSpecialistEntity();
        }

        $formOptions = array(
            'action' => $patientSpecialist_form['action'],
            'patient_id' => $patientSpecialist_form['patient']
        );
        $form = $this->createForm(PatientSpecialistForm::class, $patientSpecialist, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientSpecialistEntity')->validate($patientSpecialist_form);

        if(!count($errors)) {

            switch($patientSpecialist_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        $newAT = new AuditTrailEntity(
                            'Patient Specialist Facility',
                            $em->getClassMetadata(PatientSpecialistEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientSpecialist;
                        $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(
                        'Patient Specialist Facility',
                        $em->getClassMetadata(PatientSpecialistEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientSpecialist;
                    $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(
                        'Patient Specialist Facility',
                        $em->getClassMetadata(PatientSpecialistEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientSpecialist;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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


    // ========================= PATIENT SERVICES

    /**
     * @Route("/patient_services_ajax_list", name="patient_services_ajax_list")
     */
    public function patient_services_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 Patient Services Update'), false);

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

                $values = array(
                    $row['service_desc'],
                    $row['health_facility_desc'],
                    $row['specialist_full_name'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_services_other_ajax_list", name="patient_services_other_ajax_list")
     */
    public function patient_services_other_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 Patient Services Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientServiceEntity')->patient_service_other_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-patient-services-other-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['service_desc'],
                    $row['health_facility_desc'],
                    $row['specialist_full_name'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_service/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_services_form"
     * )
     */
    public function patient_services_formAction($patient_id, $action, $id) {

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

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

        if(!$patientServices) {
            $patientServices = new PatientServiceEntity();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientServiceForm::class, $patientServices, $formOptions);

        $title = $action === 'n' ? 'New Patient Service' : 'Update Patient Service';

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

    /**
     * @Route(
     *      "/patient_service/save_action",
     *      name = "patient_services_save"
     * )
     */
    public function patient_services_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 Patient Services New', 'Admin Patient Services Update'))) return $authService->redirectToHome();

        $patientServices_form = $request->get('patientServiceForm');
        $em = $this->getDoctrine()->getManager();
        $patientService = $em->getRepository('RxConnexionBundle:PatientServiceEntity')->find($patientServices_form['id']);
        if(!$patientService) {
            $patientService = new PatientServiceEntity();
        }

        $formOptions = array(
            'action' => $patientServices_form['action'],
            'patient_id' => $patientServices_form['patient']
        );
        $form = $this->createForm(PatientServiceForm::class, $patientService, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientServiceEntity')->validate($patientServices_form);

        if(!count($errors)) {

            switch($patientServices_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Services',
                            $em->getClassMetadata(PatientServiceEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientService;
                        $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(
                        'Patient Services',
                        $em->getClassMetadata(PatientServiceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientService;
                    $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(
                        'Patient Services',
                        $em->getClassMetadata(PatientServiceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientService;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $patientService->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(
     *      "/patient_service/other/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_services_other_form"
     * )
     */
    public function patient_services_other_formAction($patient_id, $action, $id) {

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

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

        if(!$patientServices) {
            $patientServices = new PatientServiceEntity();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientServiceOtherForm::class, $patientServices, $formOptions);

        $title = $action === 'n' ? 'New Patient Service (Other)' : 'Update Patient Service (Other)';

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

    /**
     * @Route(
     *      "/patient_service/other/save_action",
     *      name = "patient_services_other_save"
     * )
     */
    public function patient_services_other_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 Patient Services New', 'Admin Patient Services Update'))) return $authService->redirectToHome();

        $patientServices_form = $request->get('patientServicesOtherForm');
        $em = $this->getDoctrine()->getManager();
        $patientService = $em->getRepository('RxConnexionBundle:PatientServiceEntity')->find($patientServices_form['id']);
        if(!$patientService) {
            $patientService = new PatientServiceEntity();
        }

        $formOptions = array(
            'action' => $patientServices_form['action'],
            'patient_id' => $patientServices_form['patient']
        );
        $form = $this->createForm(PatientServiceOtherForm::class, $patientService, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientServiceEntity')->validate($patientServices_form);

        if(!count($errors)) {

            switch($patientServices_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        $newAT = new AuditTrailEntity(
                            'Patient Services',
                            $em->getClassMetadata(PatientServiceEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientService;
                        $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(
                        'Patient Services',
                        $em->getClassMetadata(PatientServiceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientService;
                    $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(
                        'Patient Services',
                        $em->getClassMetadata(PatientServiceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientService;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

    // ========================= PATIENT TICKET

    /**
     * @Route("/patient_ticket_ajax_list", name="patient_ticket_ajax_list")
     */
    public function patient_ticket_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 Patient Ticket Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Endorsement Transfer'), false);

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

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

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

                if($hasUpdate) {
                    $returnUrl = $this->generateUrl('patient_detail', array(
                        'patient_id' => $get['patient_id'],
                        'tab' => 'ti',
                    ));
                    $url = $this->generateUrl('ticket_form', array(
                        'action' => 'u',
                        'id' => $id,
                        'return' => $returnUrl,
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }
                $patientChartsWithLink = '';
                if(isset($row['patientCharts'])){
                    $patientChartsWithLinks = array();
                    $patientChartDetails = explode(',' , $row['patientCharts']);
                    foreach ($patientChartDetails as $patientChartDetail){
                        $patientChartDetailForIds = explode('-', $patientChartDetail);
                        if(!empty($patientChartDetailForIds[0])) {
                            $patientChartLink = $this->generateUrl('patient_chart_form', array(
                                'patient_id' => base64_encode($patientChartDetailForIds[2]),
                                'action' => 'u',
                                'id' => base64_encode($patientChartDetailForIds[0])
                            ));
                            $patientChartsWithLinks[] = "<a href='$patientChartLink' target='_blank'> $patientChartDetailForIds[0] - $patientChartDetailForIds[1] - $patientChartDetailForIds[3]</a>";
                        }
                    }
                    $patientChartsWithLink = implode('<br />' ,$patientChartsWithLinks);
                }

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Endorsement' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$row['id'],
                    $row['updated_at'],
                    $row['user'],
                    $row['ticketStatus'],
                    $row['ticketSeverity'],
                    $patientChartsWithLink,
                    $row['latestNote'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

//    /**
//     * @Route(
//     *      "/patient_ticket/form/{patient_id}/{action}/{id}",
//     *      defaults = {
//     *          "action":  "n",
//     *          "id": 0
//     *      },
//     *      requirements = {
//     *          "action": "n|u"
//     *      },
//     *      name = "patient_ticket_form"
//     * )
//     */
//    public function patient_ticket_formAction($patient_id, $action, $id) {
//
//        $authService = $this->get('rx_connexion.authService');
//        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
//        if(!$authService->isUserHasAccesses(array('Admin Patient Ticket New', 'Admin Patient Ticket Update'))) return $authService->redirectToHome();
//
//        $em = $this->getDoctrine()->getManager();
//        $patientTicket = $em->getRepository('RxConnexionBundle:PatientTicketEntity')->find(base64_decode($id));
//        if(!$patientTicket) {
//            $patientTicket = new PatientTicketEntity();
//        }
//
//        $formOptions = array(
//            'action' => $action,
//            'patient_id' => $patient_id
//        );
//        $form = $this->createForm(PatientTicketForm::class, $patientTicket, $formOptions);
//
//        $title = $action === 'n' ? 'New Ticket' : 'Update Ticket';
//
//        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_ticket_form.html.twig', array(
//            'title' => $title,
//            'page_title' => $title,
//            'form' => $form->createView(),
//            'action' => $action,
//            'patient_id' => $patient_id,
//            'id' => $id
//        ));
//        $result['success'] = true;
//        return new JsonResponse($result);
//    }
//
//    /**
//     * @Route(
//     *      "/patient_ticket/save_action",
//     *      name = "patient_ticket_save"
//     * )
//     */
//    public function patient_ticket_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 Patient Ticket New', 'Admin Patient Ticket Update'))) return $authService->redirectToHome();
//
//        $patientTicket_form = $request->get('patientTicket');
//        $em = $this->getDoctrine()->getManager();
//        $patientTicket = $em->getRepository('RxConnexionBundle:PatientTicketEntity')->find($patientTicket_form['id']);
//        if(!$patientTicket) {
//            $patientTicket = new PatientTicketEntity();
//        }
//
//        $formOptions = array(
//            'action' => $patientTicket_form['action'],
//            'patient_id' => $patientTicket_form['patient']
//        );
//        $form = $this->createForm(PatientTicketForm::class, $patientTicket, $formOptions);
//        $errors = $em->getRepository('RxConnexionBundle:PatientTicketEntity')->validate($patientTicket_form);
//
//        if(!count($errors)) {
//
//            switch($patientTicket_form['action']) {
//
//                case 'n': // new
//
//                    $form->handleRequest($request);
//
//                    if($form->isValid()) {
//                        $em->persist($patientTicket);
//                        $em->flush();
//
//                        $newAT = new AuditTrailEntity(
//                            'Patient Ticket',
//                            $em->getClassMetadata(PatientTicketEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $patientTicket;
//                        $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(
//                        'Patient Ticket',
//                        $em->getClassMetadata(PatientTicketEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_UPDATE
//                    );
//                    $newAT->entity = $patientTicket;
//                    $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(
//                        'Patient Ticket',
//                        $em->getClassMetadata(PatientTicketEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_DELETE
//                    );
//                    $newAT->entity = $patientTicket;
//                    $newAT->parseDetails();
//                    $em->persist($newAT);
//
//                    $form->handleRequest($request);
//
//                    if ($form->isValid()) {
//
//                        $patientTicket->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);
//    }

    // ========================= PATIENT TREATMENT CONSIDERATION

    /**
     * @Route("/patient_treatment_consideration_ajax_list", name="patient_treatment_consideration_ajax_list")
     */
    public function patient_treatment_consideration_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 Patient Treatment Consideration Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientTreatmentConsiderationEntity')->patient_treatment_consideration_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-patient-treatment-consideration-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['treatment_consideration_desc'],
                    $row['start_date'],
                    $row['end_date'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_treatment_consideration/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_treatment_consideration_form"
     * )
     */
    public function patient_treatment_consideration_formAction($patient_id, $action, $id) {

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

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

        if(!$patientTreatmentConsideration) {
            $patientTreatmentConsideration = new PatientTreatmentConsiderationEntity();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientTreatmentConsiderationForm::class, $patientTreatmentConsideration, $formOptions);

        $title = $action === 'n' ? 'New Patient Treatment Consideration' : 'Update Patient Treatment Consideration';

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

    /**
     * @Route(
     *      "/patient_treatment_consideration/save_action",
     *      name = "patient_treatment_consideration_save"
     * )
     */
    public function patient_treatment_consideration_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 Patient Treatment Consideration New', 'Admin Patient Treatment Consideration Update'))) return $authService->redirectToHome();

        $patientTreatmentConsideration_form = $request->get('patientTreatmentConsideration');
        $em = $this->getDoctrine()->getManager();
        $patientTreatmentConsideration = $em->getRepository('RxConnexionBundle:PatientTreatmentConsiderationEntity')->find($patientTreatmentConsideration_form['id']);
        if(!$patientTreatmentConsideration) {
            $patientTreatmentConsideration = new PatientTreatmentConsiderationEntity();
        }

        $formOptions = array(
            'action' => $patientTreatmentConsideration_form['action'],
            'patient_id' => $patientTreatmentConsideration_form['patient']
        );
        $form = $this->createForm(PatientTreatmentConsiderationForm::class, $patientTreatmentConsideration, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientTreatmentConsiderationEntity')->validate($patientTreatmentConsideration_form);

        if(!count($errors)) {

            switch($patientTreatmentConsideration_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Treatment Consideration',
                            $em->getClassMetadata(PatientTreatmentConsiderationEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientTreatmentConsideration;
                        $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(
                        'Patient Treatment Consideration',
                        $em->getClassMetadata(PatientTreatmentConsiderationEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientTreatmentConsideration;
                    $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(
                        'Patient Treatment Consideration',
                        $em->getClassMetadata(PatientTreatmentConsiderationEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientTreatmentConsideration;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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


    // ========================= PATIENT TREATMENT PLAN

    /**
     * @Route("/patient_treatment_plan_ajax_list", name="patient_treatment_plan_ajax_list")
     */
    public function patient_treatment_plan_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 Patient Treatment Plan Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientTreatmentPlanEntity')->patient_treatment_plan_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-patient-treatment-plan-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['treatment_plan_desc'],
                    $row['start_date'],
                    $row['end_date'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_treatment_plan/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action": "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_treatment_plan_form"
     * )
     */
    public function patient_treatment_plan_formAction($patient_id, $action, $id) {

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

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

        if(!$patientTreatmentPlan) {
            $patientTreatmentPlan = new PatientTreatmentPlanEntity();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientTreatmentPlanForm::class, $patientTreatmentPlan, $formOptions);

        $title = $action === 'n' ? 'New Patient Treatment Plan' : 'Update Patient Treatment Plan';

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

    /**
     * @Route(
     *      "/patient_treatment_plan/save_action",
     *      name = "patient_treatment_plan_save"
     * )
     */
    public function patient_treatment_plan_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 Patient Treatment Plan New', 'Admin Patient Treatment Plan Update'))) return $authService->redirectToHome();

        $patientTreatmentPlan_form = $request->get('patientTreatmentPlan');
        $em = $this->getDoctrine()->getManager();
        $patientTreatmentPlan = $em->getRepository('RxConnexionBundle:PatientTreatmentPlanEntity')->find($patientTreatmentPlan_form['id']);
        if(!$patientTreatmentPlan) {
            $patientTreatmentPlan = new PatientTreatmentPlanEntity();
        }

        $formOptions = array(
            'action' => $patientTreatmentPlan_form['action'],
            'patient_id' => $patientTreatmentPlan_form['patient']
        );
        $form = $this->createForm(PatientTreatmentPlanForm::class, $patientTreatmentPlan, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientTreatmentPlanEntity')->validate($patientTreatmentPlan_form);

        if(!count($errors)) {

            switch($patientTreatmentPlan_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Treatment Plan',
                            $em->getClassMetadata(PatientTreatmentPlanEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientTreatmentPlan;
                        $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(
                        'Patient Treatment Plan',
                        $em->getClassMetadata(PatientTreatmentPlanEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientTreatmentPlan;
                    $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(
                        'Patient Treatment Plan',
                        $em->getClassMetadata(PatientTreatmentPlanEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientTreatmentPlan;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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


    /*--------------------------------------------------------------------------------------------------------*/
    /*					Letters																	              */
    /*--------------------------------------------------------------------------------------------------------*/

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

            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Letter Transfer'), false);
            $hasUpdate = $authService->isUserHasAccesses(array('Admin Patient Letter Update'), false);
            $hasPreview = $authService->isUserHasAccesses(array('Admin Patient Letter Preview'), false);
            $hasFax = $authService->isUserHasAccesses(array('Admin Patient Letter Pdf'), false);
            $hasApproved = $authService->isUserHasAccesses(array('Admin Patient Letter Approved'), false);
            $hasPatientLetterNote = $authService->isUserHasAccesses(array('Admin Patient Letter Note'), false);
            $em = $this->getDoctrine()->getManager();
            $data = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->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-patient-letter-form' data-action='u' data-id='$id'>Update</a>";
                }
                $faxUrl = $this->generateUrl('patient_letter_export_to_pdf', array(
                    'patientLetter_id' => $id,
                    'letter_type' => $row['letter_type']
                ));
                $previewUrl = $this->generateUrl('patient_letter_preview', array(
                    'patientLetter_id' =>$id,
                    'letter_type' => $row['letter_type']
                ));

                $approvedUrl = $this->generateUrl('patient_approve_letter', array(
                    'patientLetter_id' => $id,
                ));

                if($hasPatientLetterNote) {
                    $action .= "<a class='action-button-style href-patient-letter-note-form' data-action='n' data-id='$id'>Notes</a>";
                }

                if($hasApproved && $row['status'] !== 'Approved') {
                    $action .= "<a href='$approvedUrl' class='action-button-style ask-continue' data-message='Are you sure you want to approve this letter?' data-action='u' data-id='$id'>Approved</a>";
                }

                if($hasPreview) {
                    $action .= "<a class='action-button-style' target='_blank' href='$previewUrl'>Preview</a>";
                }

                $attachmentWithLink = '';
                if(isset($row['attachmentFile'])){
                    $attachmentWithLinks = array();
                    $attachmentDetails = explode(',' , $row['attachmentFile']);
                    foreach ($attachmentDetails as $attachmentDetail){
                        $attachmentDetailForIds = explode('~', $attachmentDetail);
                        $attachmentLink = !empty($attachmentDetailForIds[0]) ? $this->generateUrl('patient_letter_file_download', array(
                            'id' => base64_encode($attachmentDetailForIds[0])
                        )) : 'javascript:void(0)';
                        $attachmentWithLinks[] = isset($attachmentDetailForIds[1]) ? "<a href='$attachmentLink' target='_blank'> $attachmentDetailForIds[1]</a>" : '';
                    }
                    $attachmentWithLink = implode('<br />' ,$attachmentWithLinks);
                }

                $recipient = '';
                if(!empty($row['rpDescription'])){
                    $recipient = $row['rpDescription'];
                }elseif(!empty($row['rhfDescription'])){
                    $recipient = $row['rhfDescription'];
                }elseif(!empty($row['iDescription'])) {
                    $recipient = $row['iDescription'];
                }else if(empty($row['rpDescription']) && !empty($row['patient_referring_provider_id'])){
//                    $recipient = $row['recipient'];
                    if(isset($get['patient_id'])){
//                        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($get['patient_id']));
//                        foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
//                            if(date_format($prhf->getStartDate(),'Y-m-d') <= date('Y-m-d') && ($prhf->getEndDate() == null || date_format($prhf->getEndDate(),'Y-m-d') > date('Y-m-d'))){
//                                $recipient .= '(' . $prhf->getReferringHealthFacility()->getFaxNo() . ')';
//                            }
//                        }

                        $recipient = $row['recipient'];
                        $rp = $em->getRepository('RxConnexionBundle:PatientReferringProviderEntity')->find($row['patient_referring_provider_id']);
                        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($get['patient_id']));

                        $startDate = null;
                        $endDate = null;
                        $now = new \DateTime(date('Y-m-d'));
                        foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
                            foreach ($rp->getReferringProvider()->getReferringHealthFacilityProviders() as $rhfp){
                                $startDate = new \DateTime($rhfp->getStartDateAsString());
                                $endDate = new \DateTime($rhfp->getEndDateAsString());
                                if($prhf->getReferringHealthFacility()->getId() == $rhfp->getReferringHealthFacility()->getId()){
                                    if($startDate <= $now && ($prhf->getEndDate() == null || $prhf->getEndDate() == '' || $endDate >= $now)) {
                                        $recipient .= '(' . $prhf->getReferringHealthFacility()->getFaxNo() . ')';
                                    }
                                }
                            }
                        }
                    }

                }else if(empty($row['rhfDescription'])){
                    $recipient = $row['recipient'] . '(N/A)';
                }else if(empty($row['iDescription'])){
                    $recipient = $row['recipient'] . '(N/A)';
                }
                if($hasFax) {
                    $action .= "<a class='action-button-style ask-continue' data-message='Are you sure you want to fax $recipient?' href='$faxUrl'>Fax ({$row['faxCtr']})</a>";
                }

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Letters' value='$id' class='patient-transfer-checkbox'>";
                }

                $patientLetter = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->find($row['id']);
                $fileUrl = $patientLetter->getPhotoWebPath();
                $fileUrl2 = $patientLetter->getPhotoWebPath2();
                $photoDesc = $row['photo_desc'];
                $photoDesc2 = $row['photo_desc_2'];
                $values = array(
                    $transferLink.$row['createdAt'],
                    $row['letter_type'],
                    $recipient,
                    $row['status'],
                    "<a href='$fileUrl' target='_blank'>$photoDesc</a>" . "<br />" . "<a href='$fileUrl2' target='_blank'>$photoDesc2</a> ".$attachmentWithLink,
                    $row['pages'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_letter/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_letter_form"
     * )
     */
    public function patient_letter_formAction($patient_id, $action, $id) {

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

        $em = $this->getDoctrine()->getManager();
        $patientLetter = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->find(base64_decode($id));
        $patientLetterPrescription = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id)
        ));

        $patientLetterPrescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id)
        ));

        $patientLetterPrescriptionPss = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionPSSEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id)
        ));

        $prescriptionGeneralPrescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterGeneralPrescriptionFRSIEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id),
        ));

        $patientLetterPrescriptionFrsiV2 = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIv2Entity')->findOneBy(array(
            'patientLetter' => base64_decode($id),
        ));

        $patientLetterAliceNightOne = $em->getRepository('RxConnexionBundle:PatientLetterAliceNightOneEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id),
        ));

        $patientLetterSpecialistReferral = $em->getRepository('RxConnexionBundle:PatientLetterSpecialistReferralEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id)
        ));

        $patientLetterRefusalCare = $em->getRepository('RxConnexionBundle:PatientLetterRefusalCareEntity')->findOneBy(array(
            'patientLetter' => base64_decode($id)
        ));

        $userData = $this->get('session')->get('userData');

        $letterTypes = $em->getRepository('RxConnexionBundle:LetterTemplateEntity')->letterTemplates(array(
            'userData' => $userData
        ));

        if(!$patientLetter) {
            $patientLetter = new PatientLetterEntity();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientLetterForm::class, $patientLetter, $formOptions);


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

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_letter_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'action' => $action,
            'patient_id' => base64_decode($patient_id),
            'id' => $id,
            'patientLetter' => $patientLetter,
            'patientLetterPrescription' => $patientLetterPrescription,
            'patientLetterPrescriptionFrsi' => $patientLetterPrescriptionFrsi,
            'patientLetterPrescriptionFrsiV2' => $patientLetterPrescriptionFrsiV2,
            'patientLetterAliceNightOne' => $patientLetterAliceNightOne,
            'patientLetterPrescriptionPss' => $patientLetterPrescriptionPss,
            'patientLetterSpecialistReferral' => $patientLetterSpecialistReferral,
            'patientLetterRefusalCare' => $patientLetterRefusalCare,
            'generalPrescriptionFrsi' => $prescriptionGeneralPrescriptionFrsi,
            'letterTypes' => $letterTypes
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_letter/save_action",
     *      name = "patient_letter_save"
     * )
     */
    public function patient_letter_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 Patient Letter New', 'Admin Patient Letter Update'))) return $authService->redirectToHome();

        $patientLetter_form = $request->get('patient_letter');
        $em = $this->getDoctrine()->getManager();
        $patientLetter = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->find($patientLetter_form['id']);
        if(!$patientLetter) {
            $patientLetter = new PatientLetterEntity();
        }
        $formOptions = array(
            'action' => $patientLetter_form['action'],
            'patient_id' => $patientLetter_form['patient']
        );
        $form = $this->createForm(PatientLetterForm::class, $patientLetter, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->validate($patientLetter_form);

        if(!count($errors)) {

            switch($patientLetter_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $prescriptionForm = $request->get('prescription');
                        $generalPrescriptionFrsi = $request->get('generalPrescriptionFrsi');
                        $prescriptionFrsiForm = $request->get('prescription_frsi');
                        $prescriptionFrsiFormV2 = $request->get('prescription_frsi_v2');
                        $aliceNightOneForm = $request->get('alice_night_one');
                        $prescriptionPssForm = $request->get('prescription_pss');
                        $specialistReferralForm = $request->get('specialistReferral');
                        $refusalCareForm = $request->get('refusalCare');
                        $patientLetterType = $request->get('patientLetterType');

                        $attentionRf = '';
                        $attentionIns = '';
                        $attentionRhf = '';

                        $attentionName = '';
                        $attentionPhoneNo = '';
                        $attentionFaxNo = '';
                        if(isset($patientLetter_form['patient_referring_provider_desc']) && $patientLetter_form['patient_referring_provider_desc'] != '') {
                            $attentionRf = $em->getReference('RxConnexionBundle:PatientReferringProviderEntity', $patientLetter_form['patient_referring_provider']);
                        } else if(isset($patientLetter_form['patient_insurance_desc']) && $patientLetter_form['patient_insurance_desc'] != '') {
                            $attentionIns = $em->getReference('RxConnexionBundle:PatientInsuranceEntity', $patientLetter_form['patient_insurance']);
                        } else if(isset($patientLetter_form['patient_referring_health_facility_desc']) && $patientLetter_form['patient_referring_health_facility_desc'] != '') {
                            /*
                            $activeRf = $em->getRepository(PatientEntity::class)->find(base64_decode($patientLetter_form['patient']));
                            foreach($activeRf->getPatientReferringProviders() as $activeRfs) {
                                if ($activeRfs->getEndDate() == null or $activeRfs->getEndDate() >= date('Y-m-d')) {
                                    $attentionName = $activeRfs->getReferringProvider()->getFullName();
                                    $attentionPhoneNo = $activeRfs->getReferringProvider()->getPhoneNo();
                                    $attentionFaxNo = $activeRfs->getReferringProvider()->getFaxNo();
                                }
                            }
                            */

                            $attentionRhf = $em->getReference('RxConnexionBundle:PatientReferringHealthFacilityEntity', $patientLetter_form['patient_referring_health_facility']);
                        }

                        if($patientLetter_form['patient_referring_provider_desc'] != '') {
                            $attention = $attentionRf->getReferringProvider()->getFullName();
                            $phoneNo = $attentionRf->getReferringProvider()->getPhoneNo();
                            $faxNo = $attentionRf->getReferringProvider()->getFaxNo();
                        } else if($patientLetter_form['patient_referring_health_facility_desc'] != '') {
                            $attention = $attentionRhf->getReferringHealthFacility()->getDescription();
                            $phoneNo = $attentionRhf->getReferringHealthFacility()->getPhoneNo();
                            $faxNo = $attentionRhf->getReferringHealthFacility()->getFaxNo();
                        } else {
                            $attention = $attentionIns->getInsurance()->getDescription();
                            $phoneNo = $attentionIns->getInsurance()->getPhoneNo();
                            $faxNo = $attentionIns->getInsurance()->getFaxNo();
                        }

                        $session = $this->get('session')->get('userData');
                        $patient = $em->getReference('RxConnexionBundle:PatientEntity', base64_decode($patientLetter_form['patient']));

                        $patientLetter->setAttention($attention);
                        $patientLetter->setRecipient($patient->getFullName());
                        $patientLetter->setLetterType($patientLetterType['letter_type']);
                        $patientLetter->setDate(date_create('now')->format('Y-m-d H:i:s'));
                        $patientLetter->setPhoneNo($phoneNo);
                        $patientLetter->setFaxNo($faxNo);
                        $patientLetter->setName($session['fullName']);
                        $patientLetter->setCarbonCopy('');

                        if(isset($patientLetter_form['faxCoverSelection'])) {
                            $faxCoverSelection = implode(',', $patientLetter_form['faxCoverSelection']);
                            $patientLetter->setFaxCoverSelection($faxCoverSelection);
                        }

                        if(isset($patientLetter_form['faxBranchSelection'])) {
                            $faxBranchSelection = implode(',', $patientLetter_form['faxBranchSelection']);
                            $patientLetter->setFaxBranchSelection($faxBranchSelection);
                        }

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

                        if(isset($_FILES['form'])) {
//                            if(!empty($_FILES['form']['tmp_name']['file1'])){
//                                $baseName = $patientLetter->getId() . '-1-' . uniqid() . '.' . pathinfo($_FILES['form']['name']['file1'], PATHINFO_EXTENSION);
//                                $baseNameArr = explode(".", $baseName);
//                                $baseName .= (strtoupper(end($baseNameArr)) !== 'PDF') ? '.pdf' : '';
//                                $uploadFile = $patientLetter->getUploadRootDir() . '/' . $baseName;
//
//
//                                if (move_uploaded_file($_FILES['form']['tmp_name']['file1'], $uploadFile)) {
//                                    $patientLetter->removePhoto();
//                                    $patientLetter->setPhotoDesc($_FILES['form']['name']['file1']);
//                                    $patientLetter->setParsedPhotoDesc($baseName);
//                                    $em->flush();
//                                }
//                            }
//
//                            if(!empty($_FILES['form']['tmp_name']['file2'])){
//                                $baseName = $patientLetter->getId() . '-2-' . uniqid() . '.' . pathinfo($_FILES['form']['name']['file2'], PATHINFO_EXTENSION);
//                                $baseNameArr = explode(".", $baseName);
//                                $baseName .= (strtoupper(end($baseNameArr)) !== 'PDF') ? '.pdf' : '';
//                                $uploadFile = $patientLetter->getUploadRootDir() . '/' . $baseName;
//
//                                if (move_uploaded_file($_FILES['form']['tmp_name']['file2'], $uploadFile)) {
//                                    $patientLetter->removePhoto2();
//                                    $patientLetter->setPhotoDesc2($_FILES['form']['name']['file2']);
//                                    $patientLetter->setParsedPhotoDesc2($baseName);
//                                    $em->flush();
//                                }
//                            }
                        }

                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $patientLetterFile = new PatientLetterFileEntity();
                                    $patientLetterFile->setPatientLetter($patientLetter);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $patientLetterFile->getUploadRootDir() . '/' . $baseName;
                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $patientLetterFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $patientLetterFile->setParsedFileDesc($baseName);
                                        $em->persist($patientLetterFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }

                        if($patientLetterType['letter_type'] == 'Specialist Referral') {
                            $specialistReferral = new PatientLetterSpecialistReferralEntity();
                            $specialistReferral->setPatientLetter($patientLetter);
                            $specialistReferral->setContactNo($specialistReferralForm['contactNo']);
                            $specialistReferral->setIsAssessment(isset($specialistReferralForm['isAssessment']) ? true : false);
                            $specialistReferral->setIsResult(isset($specialistReferralForm['isResult']) ? true : false);
                            $specialistReferral->setIsRecommendation(isset($specialistReferralForm['isRecommendation']) ? true : false);
                            $specialistReferral->setIsHsatCompleted(isset($specialistReferralForm['isHsatCompleted']) ? true : false);
                            $specialistReferral->setHsatCompletedDate($specialistReferralForm['hsatCompletedDate']);
                            $specialistReferral->setIsLevelOnePsgCompleted(isset($specialistReferralForm['isLevelOnePsgCompleted']) ? true : false);
                            $specialistReferral->setNote($specialistReferralForm['note']);
                            $specialistReferral->setIsOsa(isset($specialistReferralForm['isOsa']) ? true : false);
                            $specialistReferral->setIsRefusedCpap(isset($specialistReferralForm['is_refused_cpap']) ? true : false);
                            $specialistReferral->setIsMildOsa(isset($specialistReferralForm['is_mild_osa']) ? true : false);
                            $specialistReferral->setIsNormalHsat(isset($specialistReferralForm['is_normal_hsat']) ? true : false);
                            $specialistReferral->setIsReassess(isset($specialistReferralForm['is_reassess']) ? true : false);
                            $specialistReferral->setIsComplexSleep(isset($specialistReferralForm['is_complex_sleep']) ? true : false);
                            $specialistReferral->setIsComplexSleep(isset($specialistReferralForm['is_complex_titration']) ? true : false);
                            $specialistReferral->setIsIncreaseBmChfOcpd(isset($specialistReferralForm['is_increase_bm_chf_ocpd']) ? true : false);
                            $specialistReferral->setIsNonRespiratorySleepDisorder(isset($specialistReferralForm['is_non_respiratory_sleep_disorder']) ? true : false);
                            $specialistReferral->setIsRequestingOralAppliance(isset($specialistReferralForm['is_requesting_oral_appliance']) ? true : false);
                            $specialistReferral->setIsSleepPhysician(isset($specialistReferralForm['is_sleep_physician']) ? true : false);
                            $specialistReferral->setIsRespirologist(isset($specialistReferralForm['is_respirologist'])? true : false);
                            $specialistReferral->setIsInternalMedicine(isset($specialistReferralForm['is_internal_medicine']) ? true : false);
                            $specialistReferral->setIsDentalConsultation(isset($specialistReferralForm['is_dental_consultation']) ? true : false);
                            $specialistReferral->setComment($specialistReferralForm['comment']);
                            $em->persist($specialistReferral);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription') {
                            $prescription = new PatientLetterPrescriptionEntity();
                            $prescription->setPatientLetter($patientLetter);
                            $prescription->setDateOfStudy($prescriptionForm['dateOfStudy']);
                            $prescription->setInterpretationCompletedDoctor($prescriptionForm['interpretationCompletedDoctor']);
                            $prescription->setFindingConsistent($prescriptionForm['findingConsistent']);
                            $prescription->setRecommendation($prescriptionForm['recommendation']);
                            $prescription->setAhi($prescriptionForm['ahi']);
                            $prescription->setRdi($prescriptionForm['rdi']);
                            $prescription->setIsCpapTheraphy(isset($prescriptionForm['isCpapTheraphy']) ? true : false);
                            $prescription->setCpapTheraphyOne($prescriptionForm['cpap_therapy_value_one']);
                            $prescription->setCpapTheraphyTwo($prescriptionForm['cpap_therapy_value_two']);
                            $prescription->setCpapTheraphyThree($prescriptionForm['cpap_therapy_value_three']);
                            $prescription->setIsReferralToSleepSpecialist(isset($prescriptionForm['isLevelOnePsg']) ? true : false);
                            $prescription->setIsOralAppliance(isset($prescriptionForm['isOralAppliance']) ? true : false);
                            $em->persist($prescription);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription (FRSC)') {
                            $prescriptionFrsi = new PatientLetterPrescriptionFRSIEntity();
                            $prescriptionFrsi->setPatientLetter($patientLetter);
                            $prescriptionFrsi->setDate($prescriptionFrsiForm['date']);
                            $prescriptionFrsi->setDiagnosis($prescriptionFrsiForm['diagnosis']);
                            $prescriptionFrsi->setInterpretationCompletedDoctor($prescriptionFrsiForm['interpretationCompletedDoctor']);
//                            $prescription->setFindingConsistent($prescriptionForm['findingConsistent']);
                            $prescriptionFrsi->setRecommendation($prescriptionFrsiForm['recommendation']);
                            $prescriptionFrsi->setAhi($prescriptionFrsiForm['ahi']);
                            $prescriptionFrsi->setRdi($prescriptionFrsiForm['rdi']);
                            $prescriptionFrsi->setIsCpapTheraphy(isset($prescriptionFrsiForm['rdi']) ? true : false);
                            $prescriptionFrsi->setCpapTheraphyOne($prescriptionFrsiForm['cpap_therapy_value_one']);
                            $prescriptionFrsi->setCpapTheraphyTwo($prescriptionFrsiForm['cpap_therapy_value_two']);
                            $prescriptionFrsi->setCpapTheraphyThree($prescriptionFrsiForm['cpap_therapy_value_three']);
                            $prescriptionFrsi->setIsReferralToSleepSpecialist(isset($prescriptionFrsiForm['isLevelOnePsg']) ? true : false);
                            $prescriptionFrsi->setIsOralAppliance(isset($prescriptionFrsiForm['isOralAppliance']) ? true : false);
                            $em->persist($prescriptionFrsi);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription (FRSC) v2') {
                            $prescriptionFrsiV2 = new PatientLetterPrescriptionFRSIv2Entity();
                            $prescriptionFrsiV2->setPatientLetter($patientLetter);
                            $prescriptionFrsiV2->setDate($prescriptionFrsiFormV2['date']);
                            $prescriptionFrsiV2->setInterpretingPhysician($prescriptionFrsiFormV2['interpretationCompletedDoctor']);
                            $prescriptionFrsiV2->setRecommendation($prescriptionFrsiFormV2['recommendation']);
                            $prescriptionFrsiV2->setAhi($prescriptionFrsiFormV2['ahi']);
                            $prescriptionFrsiV2->setRdi($prescriptionFrsiFormV2['rdi']);
                            $prescriptionFrsiV2->setOsa($prescriptionFrsiFormV2['osa']);
                            $prescriptionFrsiV2->setCpapTheraphyOne($prescriptionFrsiFormV2['cpap_therapy_value_one']);
                            $prescriptionFrsiV2->setCpapTheraphyTwo($prescriptionFrsiFormV2['cpap_therapy_value_two']);
                            $prescriptionFrsiV2->setCpapTheraphyThree($prescriptionFrsiFormV2['cpap_therapy_value_three']);
                            $prescriptionFrsiV2->setIsReferralToSleepSpecialist(isset($prescriptionFrsiFormV2['referralToSleepSpecialist']) ? true : false);
                            $em->persist($prescriptionFrsiV2);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Alice Night One (FRSC)'
                            || $patientLetterType['letter_type'] == 'Alice Night One - Mixed Apnea (PSS)'
                            || $patientLetterType['letter_type'] == 'Alice Night One - OSA (PSS)') {
                            $aliceNightOne = new PatientLetterAliceNightOneEntity();
                            $aliceNightOne->setPatientLetter($patientLetter);
                            $aliceNightOne->setDate($aliceNightOneForm['date']);
                            $aliceNightOne->setInterpretingPhysician($aliceNightOneForm['interpretationCompletedDoctor']);
                            $aliceNightOne->setRecommendation($aliceNightOneForm['recommendation']);
                            $aliceNightOne->setAhi($aliceNightOneForm['ahi']);
                            $aliceNightOne->setOsa($aliceNightOneForm['osa']);
                            $aliceNightOne->setCpapTheraphyOne($aliceNightOneForm['cpap_therapy_value_one']);
                            $aliceNightOne->setCpapTheraphyTwo($aliceNightOneForm['cpap_therapy_value_two']);
                            $aliceNightOne->setCpapTheraphyThree($aliceNightOneForm['cpap_therapy_value_three']);
                            $aliceNightOne->setIsReferralToSleepSpecialist(isset($aliceNightOneForm['referralToSleepSpecialist']) ? true : false);
                            $em->persist($aliceNightOne);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription (PSS)') {
                            $prescriptionPss = new PatientLetterPrescriptionPSSEntity();
                            $prescriptionPss->setPatientLetter($patientLetter);
                            $prescriptionPss->setDate($prescriptionPssForm['date']);
                            $prescriptionPss->setDiagnosis($prescriptionPssForm['diagnosis']);
                            $prescriptionPss->setInterpretationCompletedDoctor($prescriptionPssForm['interpretationCompletedDoctor']);
//                            $prescription->setFindingConsistent($prescriptionForm['findingConsistent']);
                            $prescriptionPss->setRecommendation($prescriptionPssForm['recommendation']);
                            $prescriptionPss->setAhi($prescriptionPssForm['ahi']);
                            $prescriptionPss->setRdi($prescriptionPssForm['rdi']);
                            $prescriptionPss->setIsCpapTheraphy(isset($prescriptionPssForm['rdi']) ? true : false);
                            $prescriptionPss->setCpapTheraphyOne($prescriptionPssForm['cpap_therapy_value_one']);
                            $prescriptionPss->setCpapTheraphyTwo($prescriptionPssForm['cpap_therapy_value_two']);
                            $prescriptionPss->setCpapTheraphyThree($prescriptionPssForm['cpap_therapy_value_three']);
                            $prescriptionPss->setIsReferralToSleepSpecialist(isset($prescriptionPssForm['isLevelOnePsg']) ? true : false);
                            $prescriptionPss->setIsOralAppliance(isset($prescriptionPssForm['isOralAppliance']) ? true : false);
                            $em->persist($prescriptionPss);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Refusal of Care Against Medical Advice (FRSC)') {
                            $refusalCare = new PatientLetterRefusalCareEntity();
                            $refusalCare->setPatientLetter($patientLetter);
                            $refusalCare->setPatientStatement($refusalCareForm['patientStatement']);
                            $refusalCare->setName($refusalCareForm['patientStatementName']);
                            $refusalCare->setPatientStatementDate($refusalCareForm['patientStatementDate']);
                            $refusalCare->setWitnessInfoDate($refusalCareForm['witnessInfoDate']);
                            $refusalCare->setWitnessInfoName($refusalCareForm['witnessInfoName']);
                            $em->persist($refusalCare);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'General Prescription (FRSC)') {
                            $prescriptionGeneralPrescriptionFrsi = new PatientLetterGeneralPrescriptionFRSIEntity();
                            $prescriptionGeneralPrescriptionFrsi->setPatientLetter($patientLetter);
                            $prescriptionGeneralPrescriptionFrsi->setDateOfStudy($generalPrescriptionFrsi['dateOfStudy']);
                            $prescriptionGeneralPrescriptionFrsi->setInterpretationCompletedDoctor($generalPrescriptionFrsi['interpretationCompletedDoctor']);
                            $prescriptionGeneralPrescriptionFrsi->setFindingConsistent($generalPrescriptionFrsi['findingConsistent']);
                            $prescriptionGeneralPrescriptionFrsi->setRecommendation($generalPrescriptionFrsi['recommendation']);
                            $prescriptionGeneralPrescriptionFrsi->setAhi($generalPrescriptionFrsi['ahi']);
                            $prescriptionGeneralPrescriptionFrsi->setRdi($generalPrescriptionFrsi['rdi']);
                            $prescriptionGeneralPrescriptionFrsi->setIsCpapTheraphy(isset($generalPrescriptionFrsi['isCpapTheraphy']) ? true : false);
                            $prescriptionGeneralPrescriptionFrsi->setCpapTheraphyOne($generalPrescriptionFrsi['cpap_therapy_value_one']);
                            $prescriptionGeneralPrescriptionFrsi->setCpapTheraphyTwo($generalPrescriptionFrsi['cpap_therapy_value_two']);
                            $prescriptionGeneralPrescriptionFrsi->setCpapTheraphyThree($generalPrescriptionFrsi['cpap_therapy_value_three']);
                            $prescriptionGeneralPrescriptionFrsi->setIsReferralToSleepSpecialist(isset($prescriptionForm['isLevelOnePsg']) ? true : false);
                            $prescriptionGeneralPrescriptionFrsi->setIsOralAppliance(isset($generalPrescriptionFrsi['isOralAppliance']) ? true : false);
                            $em->persist($prescriptionGeneralPrescriptionFrsi);
                            $em->flush();
                        }

                        $newAT = new AuditTrailEntity(
                            'Patient Letter',
                            $em->getClassMetadata(PatientLetterEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientLetter;
                        $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.';
                        $result['errorMessages2'] = $form->getErrors(true);
                    }

                    break;

                case 'u': // update

                    $prescriptionForm = $request->get('prescription');
                    $prescriptionFrsiForm = $request->get('prescription_frsi');
                    $prescriptionFrsiFormV2 = $request->get('prescription_frsi_v2');
                    $aliceNightOneForm = $request->get('alice_night_one');
                    $prescriptionPssForm = $request->get('prescription_pss');
                    $specialistReferralForm = $request->get('specialistReferral');
                    $generalPrescriptionFrsi = $request->get('generalPrescriptionFrsi');
                    $refusalCareForm = $request->get('refusalCare');
                    $patientLetterType = $request->get('patientLetterType');

                    $attentionRf = '';
                    $attentionIns = '';

                    $attentionName = '';
                    $attentionPhoneNo = '';
                    $attentionFaxNo = '';
                    if(isset($patientLetter_form['patient_referring_provider_desc']) && $patientLetter_form['patient_referring_provider_desc'] != '') {
                        $attentionRf = $em->getReference('RxConnexionBundle:PatientReferringProviderEntity', $patientLetter_form['patient_referring_provider']);
                    } else if(isset($patientLetter_form['patient_insurance_desc']) && $patientLetter_form['patient_insurance_desc'] != '') {
                        $attentionIns = $em->getReference('RxConnexionBundle:PatientInsuranceEntity', $patientLetter_form['patient_insurance']);
                    } else if(isset($patientLetter_form['patient_referring_health_facility_desc']) && $patientLetter_form['patient_referring_health_facility_desc'] != '') {
                        $activeRf = $em->getRepository(PatientEntity::class)->find(base64_decode($patientLetter_form['patient']));
                        foreach($activeRf->getPatientReferringProviders() as $activeRfs) {
                            if ($activeRfs->getEndDate() != null or $activeRfs->getEndDate() >= date('Y-m-d')) {
                                $attentionName =$activeRfs->getReferringProvider()->getFullName();
                                $attentionPhoneNo =$activeRfs->getReferringProvider()->getPhoneNo();
                                $attentionFaxNo =$activeRfs->getReferringProvider()->getFaxNo();
                            }
                        }


                    }

                    $attention = null;
                    $phoneNo = null;
                    $faxNo = null;
                    if($patientLetter_form['patient_referring_provider_desc'] != '') {
                        $attention = $attentionRf->getReferringProvider()->getFullName();
                        $phoneNo = $attentionRf->getReferringProvider()->getPhoneNo();
                        $faxNo = $attentionRf->getReferringProvider()->getFaxNo();
                    } else if($patientLetter_form['patient_referring_health_facility_desc'] != '') {
                        $attention = $attentionName;
                        $phoneNo = $attentionPhoneNo;
                        $faxNo = $attentionFaxNo;
                    } else {
                        $attention = $attentionIns->getInsurance()->getDescription();
                        $phoneNo = $attentionIns->getInsurance()->getPhoneNo();
                        $faxNo = $attentionIns->getInsurance()->getFaxNo();
                    }

                    $session = $this->get('session')->get('userData');
                    $patient = $em->getReference('RxConnexionBundle:PatientEntity', base64_decode($patientLetter_form['patient']));

                    $patientLetter->setAttention($attention);
                    $patientLetter->setRecipient($patient->getFullName());
                    $patientLetter->setLetterType($patientLetterType['letter_type']);
                    $patientLetter->setDate(date_create('now')->format('Y-m-d H:i:s'));
                    $patientLetter->setPhoneNo($phoneNo);
                    $patientLetter->setFaxNo($faxNo);
                    $patientLetter->setName($session['fullName']);
                    $patientLetter->setCarbonCopy('');

                    if(isset($patientLetter_form['faxCoverSelection'])){
                        $faxCoverSelection = implode(',' , $patientLetter_form['faxCoverSelection']);
                        $patientLetter->setFaxCoverSelection($faxCoverSelection);
                    } else {
                        $patientLetter->setFaxCoverSelection(null);
                    }
                    if(isset($patientLetter_form['faxBranchSelection'])) {
                        $faxBranchSelection = implode(',', $patientLetter_form['faxBranchSelection']);
                        $patientLetter->setFaxBranchSelection($faxBranchSelection);
                    } else {
                        $patientLetter->setFaxBranchSelection(null);
                    }

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

                    $newAT = new AuditTrailEntity(
                        'Patient Letter',
                        $em->getClassMetadata(PatientLetterEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientLetter;
                    $newAT->parseOriginalDetails();

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

                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();
                        if(isset($_FILES['form'])) {
                            if(!empty($_FILES['form']['tmp_name']['file1'])){
                                $baseName = $patientLetter->getId() . '-1-' . uniqid() . '.' . pathinfo($_FILES['form']['name']['file1'], PATHINFO_EXTENSION);
                                $uploadFile = $patientLetter->getUploadRootDir() . '/' . $baseName;

                                if (move_uploaded_file($_FILES['form']['tmp_name']['file1'], $uploadFile)) {
                                    $patientLetter->removePhoto();
                                    $patientLetter->setPhotoDesc($_FILES['form']['name']['file1']);
                                    $patientLetter->setParsedPhotoDesc($baseName);
                                    $em->flush();

                                }
                            }
                            if(!empty($_FILES['form']['tmp_name']['file2'])){
                                $baseName = $patientLetter->getId() . '-2-' . uniqid() . '.' . pathinfo($_FILES['form']['name']['file2'], PATHINFO_EXTENSION);
                                $uploadFile = $patientLetter->getUploadRootDir() . '/' . $baseName;

                                if (move_uploaded_file($_FILES['form']['tmp_name']['file2'], $uploadFile)) {
                                    $patientLetter->removePhoto2();
                                    $patientLetter->setPhotoDesc2($_FILES['form']['name']['file2']);
                                    $patientLetter->setParsedPhotoDesc2($baseName);
                                    $em->flush();

                                }
                            }

                            $em->flush();
                        }



                        $formPatientLetterFile = $request->get('otherForm');
                        $patientLetterFile = $em->getRepository('RxConnexionBundle:PatientLetterFileEntity')->findBy(array(
                            'patientLetter' => $patientLetter->getId(),
                            'isDeleted' => false
                        ));


                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $newPatientLetterFile = new PatientLetterFileEntity();
                                    $newPatientLetterFile->setPatientLetter($patientLetter);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $newPatientLetterFile->getUploadRootDir() . '/' . $baseName;

                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $newPatientLetterFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $newPatientLetterFile->setParsedFileDesc($baseName);
                                        $em->persist($newPatientLetterFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }

                        if(isset($formPatientLetterFile)) {
                            foreach($patientLetterFile as $plf) {
                                if(!in_array($plf->getIdEncoded(), $formPatientLetterFile['files'])) {
                                    $patientLetterFile2 = $em->getRepository('RxConnexionBundle:PatientLetterFileEntity')->find($plf->getId());
                                    $patientLetterFile2->removeFile();
                                    $patientLetterFile2->setIsDeleted(true);
                                    $em->flush();
                                }
                            }
                        } else {
                            foreach ($patientLetterFile as $plf2) {
                                $plf2->removeFile();
                                $plf2->setIsDeleted(true);
                                $em->flush();
                            }

                        }

                        if($patientLetterType['letter_type'] == 'Specialist Referral') {
                            $specialistReferral = $em->getRepository('RxConnexionBundle:PatientLetterSpecialistReferralEntity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $specialistReferral->setPatientLetter($patientLetter);
                            $specialistReferral->setContactNo($specialistReferralForm['contactNo']);
                            $specialistReferral->setIsAssessment(isset($specialistReferralForm['isAssessment']) ? true : false);
                            $specialistReferral->setIsResult(isset($specialistReferralForm['isResult']) ? true : false);
                            $specialistReferral->setIsRecommendation(isset($specialistReferralForm['isRecommendation']) ? true : false);
                            $specialistReferral->setIsHsatCompleted(isset($specialistReferralForm['isHsatCompleted']) ? true : false);
                            $specialistReferral->setHsatCompletedDate($specialistReferralForm['hsatCompletedDate']);
                            $specialistReferral->setIsLevelOnePsgCompleted(isset($specialistReferralForm['isLevelOnePsgCompleted']) ? true : false);
                            $specialistReferral->setNote($specialistReferralForm['note']);
                            $specialistReferral->setIsOsa(isset($specialistReferralForm['isOsa']) ? true : false);
                            $specialistReferral->setIsRefusedCpap(isset($specialistReferralForm['is_refused_cpap']) ? true : false);
                            $specialistReferral->setIsMildOsa(isset($specialistReferralForm['is_mild_osa']) ? true : false);
                            $specialistReferral->setIsNormalHsat(isset($specialistReferralForm['is_normal_hsat']) ? true : false);
                            $specialistReferral->setIsReassess(isset($specialistReferralForm['is_reassess']) ? true : false);
                            $specialistReferral->setIsComplexSleep(isset($specialistReferralForm['is_complex_sleep']) ? true : false);
                            $specialistReferral->setIsComplexSleep(isset($specialistReferralForm['is_complex_titration']) ? true : false);
                            $specialistReferral->setIsIncreaseBmChfOcpd(isset($specialistReferralForm['is_increase_bm_chf_ocpd']) ? true : false);
                            $specialistReferral->setIsNonRespiratorySleepDisorder(isset($specialistReferralForm['is_non_respiratory_sleep_disorder']) ? true : false);
                            $specialistReferral->setIsRequestingOralAppliance(isset($specialistReferralForm['is_requesting_oral_appliance']) ? true : false);
                            $specialistReferral->setIsSleepPhysician(isset($specialistReferralForm['is_sleep_physician']) ? true : false);
                            $specialistReferral->setIsRespirologist(isset($specialistReferralForm['is_respirologist'])? true : false);
                            $specialistReferral->setIsInternalMedicine(isset($specialistReferralForm['is_internal_medicine']) ? true : false);
                            $specialistReferral->setIsDentalConsultation(isset($specialistReferralForm['is_dental_consultation']) ? true : false);
                            $specialistReferral->setComment($specialistReferralForm['comment']);
//                            $em->persist($specialistReferral);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription') {
                            $prescription = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionEntity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $prescription->setPatientLetter($patientLetter);
                            $prescription->setDateOfStudy($prescriptionForm['dateOfStudy']);
                            $prescription->setInterpretationCompletedDoctor($prescriptionForm['interpretationCompletedDoctor']);
                            $prescription->setFindingConsistent($prescriptionForm['findingConsistent']);
                            $prescription->setRecommendation($prescriptionForm['recommendation']);
                            $prescription->setAhi($prescriptionForm['ahi']);
                            $prescription->setRdi($prescriptionForm['rdi']);
                            $prescription->setIsCpapTheraphy(isset($prescriptionForm['rdi']) ? true : false);
                            $prescription->setCpapTheraphyOne($prescriptionForm['cpap_therapy_value_one']);
                            $prescription->setCpapTheraphyTwo($prescriptionForm['cpap_therapy_value_two']);
                            $prescription->setCpapTheraphyThree($prescriptionForm['cpap_therapy_value_three']);
                            $prescription->setIsReferralToSleepSpecialist(isset($prescriptionForm['isLevelOnePsg']) ? true : false);
                            $prescription->setIsOralAppliance(isset($prescriptionForm['isOralAppliance']) ? true : false);
//                            $em->persist($prescription);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription (FRSC)') {
                            $prescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIEntity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $prescriptionFrsi->setPatientLetter($patientLetter);
                            $prescriptionFrsi->setDate($prescriptionFrsiForm['date']);
                            $prescriptionFrsi->setDiagnosis($prescriptionFrsiForm['diagnosis']);
                            $prescriptionFrsi->setInterpretationCompletedDoctor($prescriptionFrsiForm['interpretationCompletedDoctor']);
//                            $prescription->setFindingConsistent($prescriptionForm['findingConsistent']);
                            $prescriptionFrsi->setRecommendation($prescriptionFrsiForm['recommendation']);
                            $prescriptionFrsi->setAhi($prescriptionFrsiForm['ahi']);
                            $prescriptionFrsi->setRdi($prescriptionFrsiForm['rdi']);
                            $prescriptionFrsi->setIsCpapTheraphy(isset($prescriptionFrsiForm['rdi']) ? true : false);
                            $prescriptionFrsi->setCpapTheraphyOne($prescriptionFrsiForm['cpap_therapy_value_one']);
                            $prescriptionFrsi->setCpapTheraphyTwo($prescriptionFrsiForm['cpap_therapy_value_two']);
                            $prescriptionFrsi->setCpapTheraphyThree($prescriptionFrsiForm['cpap_therapy_value_three']);
                            $prescriptionFrsi->setIsReferralToSleepSpecialist(isset($prescriptionFrsiForm['isLevelOnePsg']) ? true : false);
                            $prescriptionFrsi->setIsOralAppliance(isset($prescriptionFrsiForm['isOralAppliance']) ? true : false);
//                            $em->persist($prescriptionFrsi);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription (FRSC) v2') {
                            $prescriptionFrsiV2 = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIv2Entity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $prescriptionFrsiV2->setPatientLetter($patientLetter);
                            $prescriptionFrsiV2->setDate($prescriptionFrsiFormV2['date']);
                            $prescriptionFrsiV2->setInterpretingPhysician($prescriptionFrsiFormV2['interpretationCompletedDoctor']);
                            $prescriptionFrsiV2->setRecommendation($prescriptionFrsiFormV2['recommendation']);
                            $prescriptionFrsiV2->setAhi($prescriptionFrsiFormV2['ahi']);
                            $prescriptionFrsiV2->setRdi($prescriptionFrsiFormV2['rdi']);
                            $prescriptionFrsiV2->setOsa($prescriptionFrsiFormV2['osa']);
                            $prescriptionFrsiV2->setCpapTheraphyOne($prescriptionFrsiFormV2['cpap_therapy_value_one']);
                            $prescriptionFrsiV2->setCpapTheraphyTwo($prescriptionFrsiFormV2['cpap_therapy_value_two']);
                            $prescriptionFrsiV2->setCpapTheraphyThree($prescriptionFrsiFormV2['cpap_therapy_value_three']);
                            $prescriptionFrsiV2->setIsReferralToSleepSpecialist(isset($prescriptionFrsiFormV2['referralToSleepSpecialist']) ? true : false);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Alice Night One (FRSC)'
                            || $patientLetterType['letter_type'] == 'Alice Night One - Mixed Apnea (PSS)'
                            || $patientLetterType['letter_type'] == 'Alice Night One - OSA (PSS)') {
                            $aliceNightOne = $em->getRepository('RxConnexionBundle:PatientLetterAliceNightOneEntity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $aliceNightOne->setPatientLetter($patientLetter);
                            $aliceNightOne->setDate($aliceNightOneForm['date']);
                            $aliceNightOne->setInterpretingPhysician($aliceNightOneForm['interpretationCompletedDoctor']);
                            $aliceNightOne->setRecommendation($aliceNightOneForm['recommendation']);
                            $aliceNightOne->setAhi($aliceNightOneForm['ahi']);
                            $aliceNightOne->setOsa($aliceNightOneForm['osa']);
                            $aliceNightOne->setCpapTheraphyOne($aliceNightOneForm['cpap_therapy_value_one']);
                            $aliceNightOne->setCpapTheraphyTwo($aliceNightOneForm['cpap_therapy_value_two']);
                            $aliceNightOne->setCpapTheraphyThree($aliceNightOneForm['cpap_therapy_value_three']);
                            $aliceNightOne->setIsReferralToSleepSpecialist(isset($aliceNightOneForm['referralToSleepSpecialist']) ? true : false);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'General Prescription (FRSC)') {
                            $prescriptionGeneralPrescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterGeneralPrescriptionFRSIEntity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $prescriptionGeneralPrescriptionFrsi->setPatientLetter($patientLetter);
                            $prescriptionGeneralPrescriptionFrsi->setDateOfStudy($generalPrescriptionFrsi['dateOfStudy']);
                            $prescriptionGeneralPrescriptionFrsi->setInterpretationCompletedDoctor($generalPrescriptionFrsi['interpretationCompletedDoctor']);
                            $prescriptionGeneralPrescriptionFrsi->setFindingConsistent($generalPrescriptionFrsi['findingConsistent']);
                            $prescriptionGeneralPrescriptionFrsi->setRecommendation($generalPrescriptionFrsi['recommendation']);
                            $prescriptionGeneralPrescriptionFrsi->setAhi($generalPrescriptionFrsi['ahi']);
                            $prescriptionGeneralPrescriptionFrsi->setRdi($generalPrescriptionFrsi['rdi']);
                            $prescriptionGeneralPrescriptionFrsi->setIsCpapTheraphy(isset($generalPrescriptionFrsi['isCpapTheraphy']) ? true : false);
                            $prescriptionGeneralPrescriptionFrsi->setCpapTheraphyOne($generalPrescriptionFrsi['cpap_therapy_value_one']);
                            $prescriptionGeneralPrescriptionFrsi->setCpapTheraphyTwo($generalPrescriptionFrsi['cpap_therapy_value_two']);
                            $prescriptionGeneralPrescriptionFrsi->setCpapTheraphyThree($generalPrescriptionFrsi['cpap_therapy_value_three']);
                            $prescriptionGeneralPrescriptionFrsi->setIsReferralToSleepSpecialist(isset($generalPrescriptionFrsi['isLevelOnePsg']) ? true : false);
                            $prescriptionGeneralPrescriptionFrsi->setIsOralAppliance(isset($generalPrescriptionFrsi['isOralAppliance']) ? true : false);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Prescription (PSS)') {
                            $prescriptionPss = new PatientLetterPrescriptionPSSEntity();
                            $prescriptionPss->setPatientLetter($patientLetter);
                            $prescriptionPss->setDate($prescriptionPssForm['date']);
                            $prescriptionPss->setDiagnosis($prescriptionPssForm['diagnosis']);
                            $prescriptionPss->setInterpretationCompletedDoctor($prescriptionPssForm['interpretationCompletedDoctor']);
//                            $prescription->setFindingConsistent($prescriptionForm['findingConsistent']);
                            $prescriptionPss->setRecommendation($prescriptionPssForm['recommendation']);
                            $prescriptionPss->setAhi($prescriptionPssForm['ahi']);
                            $prescriptionPss->setRdi($prescriptionPssForm['rdi']);
                            $prescriptionPss->setIsCpapTheraphy(isset($prescriptionPssForm['rdi']) ? true : false);
                            $prescriptionPss->setCpapTheraphyOne($prescriptionPssForm['cpap_therapy_value_one']);
                            $prescriptionPss->setCpapTheraphyTwo($prescriptionPssForm['cpap_therapy_value_two']);
                            $prescriptionPss->setCpapTheraphyThree($prescriptionPssForm['cpap_therapy_value_three']);
                            $prescriptionPss->setIsReferralToSleepSpecialist(isset($prescriptionPssForm['isLevelOnePsg']) ? true : false);
                            $prescriptionPss->setIsOralAppliance(isset($prescriptionPssForm['isOralAppliance']) ? true : false);
//                            $em->persist($prescriptionPss);
                            $em->flush();
                        }

                        if($patientLetterType['letter_type'] == 'Refusal of Care Against Medical Advice (FRSC)') {
                            $refusalCare = $em->getRepository('RxConnexionBundle:PatientLetterRefusalCareEntity')->findOneBy(array(
                                'patientLetter' => $patientLetter->getId(),
                            ));
                            $refusalCare->setPatientLetter($patientLetter);
                            $refusalCare->setPatientStatement($refusalCareForm['patientStatement']);
                            $refusalCare->setName($refusalCareForm['patientStatementName']);
                            $refusalCare->setPatientStatementDate($refusalCareForm['patientStatementDate']);
                            $refusalCare->setWitnessInfoDate($refusalCareForm['witnessInfoDate']);
                            $refusalCare->setWitnessInfoName($refusalCareForm['witnessInfoName']);
//                                $em->persist($refusalCare);
                            $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(
                        'Patient Letter',
                        $em->getClassMetadata(PatientLetterEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientLetter;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientLetter);
                        $patientLetter->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("/letter/download/{id}", name="patient_letter_file_download")
     */
    public function patient_letter_file_downloadAction($id) {

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

            $patientLetterFile = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientLetterFileEntity')->find(base64_decode($id));

            header('Content-Disposition: attachment; filename="' . $patientLetterFile->getFileDesc() . '"');

            $handle = fopen(realpath($patientLetterFile->getUploadRootDir()) . '/' . $patientLetterFile->getParsedFileDesc(), 'rb');
            $chunkSize = 1024*1024;

            if($handle !== false) {

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

                fclose($handle);
            }
        }

        exit();
    }

    /**
     * @Route("/email/download/{id}", name="patient_email_file_download")
     */
    public function patient_email_file_downloadAction($id) {

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

            $patientEmailFile = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientEmailFileEntity')->find(base64_decode($id));

            header('Content-Disposition: attachment; filename="' . $patientEmailFile->getFileDesc() . '"');

            $handle = fopen(realpath($patientEmailFile->getUploadRootDir()) . '/' . $patientEmailFile->getParsedFileDesc(), 'rb');
            $chunkSize = 1024*1024;

            if($handle !== false) {

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

                fclose($handle);
            }
        }

        exit();
    }

    /**
     * @Route(
     *      "/patient_letter/export_to_pdf/{patientLetter_id}/{letter_type}",
     *      name = "patient_letter_export_to_pdf"
     * )
     */
    public function patient_letter_export_to_pdf_send_faxAction(Request $request, $patientLetter_id, $letter_type) {

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

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

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        /**@var PatientLetterEntity $patientLetter*/
        $patientLetter = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->find(base64_decode($patientLetter_id));
        $patientPrescription = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $prescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $prescriptionFrsiV2 = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIv2Entity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $aliceNightOne = $em->getRepository('RxConnexionBundle:PatientLetterAliceNightOneEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $patientLetterGeneralPrescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterGeneralPrescriptionFRSIEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $prescriptionPss = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionPSSEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $patientSpecialistReferral = $em->getRepository('RxConnexionBundle:PatientLetterSpecialistReferralEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $patientLetterRefusalCare = $em->getRepository('RxConnexionBundle:PatientLetterRefusalCareEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));

        $generatedLetter = $this->patient_letter_generate(
            $letter_type,
            $patientLetter,
            $patientPrescription,
            $prescriptionFrsi,
            $prescriptionFrsiV2,
            $aliceNightOne,
            $patientLetterGeneralPrescriptionFrsi,
            $prescriptionPss,
            $patientSpecialistReferral,
            $patientLetterRefusalCare);
        $generatedLetter_fileName = $patientLetter->getPatient()->getFullName().'-'. $patientLetter->getId() . '-' . uniqid() . '.pdf';
        //$generatedLetter_dir = $patientLetter->getTmpRootDir() . '/' . $generatedLetter_fileName;
        //file_put_contents($generatedLetter_dir, $generatedLetter);

        $receiverFaxNum = null;
        $receiverFaxNumTwo = null;

        if($patientLetter->getPatientReferringHealthFacility()){
            $receiverFaxNum = $patientLetter->getPatientReferringHealthFacility()->getReferringHealthFacility()->getFaxNo();
            $receiverFaxNumTwo = $patientLetter->getPatientReferringHealthFacility()->getReferringHealthFacility()->getFaxNoTwo();
            $ref = 'Health Facility';

            $patient = $patientLetter->getPatient();

            if($receiverFaxNum == '' || $receiverFaxNum == null){
                foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
                    if(date_format($prhf->getStartDate(),'Y-m-d') <= date('Y-m-d') && ($prhf->getEndDate() == null || date_format($prhf->getEndDate(),'Y-m-d') > date('Y-m-d'))){
                        $receiverFaxNum = $prhf->getReferringHealthFacility()->getFaxNo();
                    }
                }
            }

            if($receiverFaxNumTwo == '' || $receiverFaxNumTwo == null){
                foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
                    if(date_format($prhf->getStartDate(),'Y-m-d') <= date('Y-m-d') && ($prhf->getEndDate() == null || date_format($prhf->getEndDate(),'Y-m-d') > date('Y-m-d'))){
                        $receiverFaxNumTwo = $prhf->getReferringHealthFacility()->getFaxNoTwo();
                    }
                }
            }

        } elseif($patientLetter->getPatientReferringProvider()) {
            $receiverFaxNum = $patientLetter->getPatientReferringProvider()->getReferringProvider()->getFaxNo();
            $receiverFaxNumTwo = $patientLetter->getPatientReferringProvider()->getReferringProvider()->getFaxNoTwo();
            $ref = 'Provider';
            $rp = $patientLetter->getPatientReferringProvider()->getReferringProvider();
            $patient = $patientLetter->getPatient();

//            foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
//                if(date_format($prhf->getStartDate(),'Y-m-d') <= date('Y-m-d') && ($prhf->getEndDate() == null || date_format($prhf->getEndDate(),'Y-m-d') > date('Y-m-d'))){
//                    $receiverFaxNum = $prhf->getReferringHealthFacility()->getFaxNo();
//                }
//            }

            if($receiverFaxNum == '' || $receiverFaxNum == null){
                foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
                    foreach ($rp->getReferringHealthFacilityProviders() as $rhfp){
                        if($prhf->getReferringHealthFacility()->getId() == $rhfp->getReferringHealthFacility()->getId()){
                            $receiverFaxNum = $prhf->getReferringHealthFacility()->getFaxNo();
                        }
                    }
                }
            }
            if($receiverFaxNumTwo == '' || $receiverFaxNumTwo == null){
                foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
                    foreach ($rp->getReferringHealthFacilityProviders() as $rhfp){
                        if($prhf->getReferringHealthFacility()->getId() == $rhfp->getReferringHealthFacility()->getId()){
                            $receiverFaxNumTwo = $prhf->getReferringHealthFacility()->getFaxNoTwo();
                        }
                    }
                }
            }
        } elseif($patientLetter->getPatientInsurance()) {
            $receiverFaxNum = $patientLetter->getPatientInsurance()->getInsurance()->getFaxNo();
            $receiverFaxNumTwo = $patientLetter->getPatientInsurance()->getInsurance()->getFaxNoTwo();
            $ref = 'Insurance';
        }else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Patient does not have referral information. Please update patient details.');
            return $this->redirect($this->generateUrl('patient_detail',array(
                'patient_id' => base64_encode($patientLetter->getPatient()->getId()),
                'tab'       => 'l'
            )), 302);
        }

        $receiver = preg_replace("/[^0-9]/", "", $receiverFaxNum );
        if($receiver == '' && $receiver == null){
            $receiver = preg_replace("/[^0-9]/", "", $receiverFaxNumTwo );
        }

        if($receiver != null && $receiver != ''){
            /**@var SRFaxService $srFax*/
            $srFax = $this->get('rx_connexion.SRFaxService');
            $cc = $patientLetter->getPatientLetterCcFaxNumForSrFax();
            $faxType = $srFax::FAX_TYPE_SINGLE;
            if(!empty($cc) && !is_null($cc)){
                $receiver = implode('|', array($receiver,$cc));
                $faxType = $srFax::FAX_TYPE_BROADCAST;
            }
            $newFaxTranOut = new FaxTranOutboundEntity();
            $newFaxTranOut->setSource(FaxTranOutboundEntity::SOURCE_PATIENT_LETTER);
            $newFaxTranOut->setPatientLetter($patientLetter);
            $newFaxTranOut->setFaxType($faxType);
            $newFaxTranOut->setFaxNo($receiver);
            $newFaxTranOut->setFileName($generatedLetter_fileName);

            $queueOptions = array();
            $queueOptions['sFaxType'] = $faxType;
            $queueOptions['sToFaxNumber'] = $receiver;
            $queueOptions['sFileName_1'] = $generatedLetter_fileName;
            $queueOptions['sFileContent_1'] = base64_encode($generatedLetter->getContent());
            $queueOptions['sNotifyURL'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . $this->generateUrl('fax_status_receipt');
            $status = $srFax->Queue_Fax($queueOptions);

            $newFaxTranOut->setStatus($status);

            if($status){
                $newFaxTranOut->setFaxId($srFax->getRequestResponse());
                $newFaxTranOut->setMsg('Fax successfully queued.');
                $patientLetter->setPatientLetterStatus($em->getRepository('RxConnexionBundle:PatientLetterStatusEntity')->findOneBy(array(
                    'description' => 'Sent'
                )));
                $this->get('session')->getFlashBag()->set('success_messages', 'Fax successfully queued.');
            } else {
                $newFaxTranOut->setMsg($srFax->getRequestResponse());
                $this->get('session')->getFlashBag()->set('error_messages', $srFax->getRequestResponse());
            }

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

        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Referring ' . $ref . ' Doesn\'t have fax number.');
        }

        return $this->redirect($this->generateUrl('patient_detail',array(
            'patient_id' => base64_encode($patientLetter->getPatient()->getId()),
            'tab'       => 'l'
        )), 302);

    }

    /**
     * @Route(
     *      "/patient_letter/preview/{patientLetter_id}/{letter_type}",
     *      name = "patient_letter_preview"
     * )
     */
    public function patient_letter_previewAction(Request $request, $patientLetter_id, $letter_type) {

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

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

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $patientLetter = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->find(base64_decode($patientLetter_id));
        $patientPrescription = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $patientLetterGeneralPrescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterGeneralPrescriptionFRSIEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $prescriptionFrsi = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $prescriptionFrsiV2 = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionFRSIv2Entity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $aliceNightOne = $em->getRepository('RxConnexionBundle:PatientLetterAliceNightOneEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $prescriptionPss = $em->getRepository('RxConnexionBundle:PatientLetterPrescriptionPSSEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $patientSpecialistReferral = $em->getRepository('RxConnexionBundle:PatientLetterSpecialistReferralEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $patientLetterRefusalCare = $em->getRepository('RxConnexionBundle:PatientLetterRefusalCareEntity')->findOneBy(array(
            'patientLetter' => base64_decode($patientLetter_id),
        ));
        $generatedLetter = $this->patient_letter_generate(
            $letter_type,
            $patientLetter,
            $patientPrescription,
            $prescriptionFrsi,
            $prescriptionFrsiV2,
            $aliceNightOne,
            $patientLetterGeneralPrescriptionFrsi,
            $prescriptionPss,
            $patientSpecialistReferral,
            $patientLetterRefusalCare);
        return $generatedLetter;
    }

    private function patient_letter_generate(
        $letter_type,
        $patientLetter,
        $patientPrescription,
        $prescriptionFrsi,
        $prescriptionFrsiV2,
        $aliceNightOne,
        $patientLetterGeneralPrescriptionFrsi,
        $prescriptionPss,
        $patientSpecialistReferral,
        $patientLetterRefusalCare){

        $patientLetter_id = $patientLetter->getIdEncoded();
        $em = $this->getDoctrine()->getManager();

        $view = null;
        $footer = null;
        $header = null;
        $page_title = null;
        switch($letter_type){
            //Freedom Template
            case 'HSAT - No Book (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'HSAT No Rebook (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'HSAT Refuse to repeat HSAT (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'HSAT Unable to Contact (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'HST Refuse - Wants to speak with their Doctor first (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'HST Refuse - Had HSAT Already (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'HST Refuse - No Coverage-No Insurance (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Negative OSA (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Negative OSA (No RDI) (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Oximetry Inconclusive (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Oximetry Negative (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'FAX for Referral Acknowledgement (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Refusal of Care Against Medical Advice (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_refusal_care_against_medical_advice.wkpdf.twig';
                break;
            case 'No Booking Under 18 years of age (FSRC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/no_booking_under_eighteen_years_of_age.wkpdf.twig';
                break;
            case 'Prescription (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_prescription.wkpdf.twig';
                break;
            case 'Prescription (FRSC) v2':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_prescription_v_2_0.wkpdf.twig';
                break;
            case 'Alice Night One (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_alice_night_one.wkpdf.twig';
                break;
            case 'Marketing Letter (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_marketing_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_blank_letter.wkpdf.twig';
                break;
            case 'General Prescription (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_marketing_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/GeneralPrescription.wkpdf.twig';
                break;
            case 'CPAP refused not interested (Severe to Very Severe) (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Negative Inconclusive (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Fax Acknowledgement for PFT Only (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Fax Acknowledgement for PFT & HSAT Referral (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Adherence Report (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'AISH Calgary and Edmonton (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'CPAP no book (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'CPAP no re-book (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Travel Letter (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Appointment Notice (General) (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Appointment Status Update (General) (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Specialist Referral (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'Letter (General) (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;
            case 'CPAP Quote (Pre-Determination for AISH) (FRSC)':
                $header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_letter.wkpdf.twig';
                break;

            //End Freedom Templates

            //Perfect Sleep Templates
            case 'Acknowledgement of Referral (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('Acknowledgement of Referral');
                break;
            case 'Prescription (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_prescription.wkpdf.twig';
                $page_title = strtoupper('Abnormal Sleep Study Results - Prescription');
                break;
            case 'Negative OSA (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('Negative OSA');
                break;
            case 'Negative Inconclusive (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('Negative Inconclusive');
                break;
            case 'HSAT Unable to Contact (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('HSAT Unable to Contact');
                break;
            case 'HSAT No Book (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('HSAT No Book');
                break;
            case 'CPAP-refused not interested (Very Mild to Moderate) (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('CPAP-refused not interested (Very Mild to Moderate)');
                break;
            case 'CPAP No Book (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('CPAP No Book');
                break;
            case 'CPAP no book Trial (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('CPAP no book Trial');
                break;
            case 'Adherence Report (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_letter.wkpdf.twig';
                $page_title = strtoupper('Adherence Report');
                break;
            case 'Alice Night One - Mixed Apnea (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_alice_night_one.wkpdf.twig';
                $page_title = strtoupper('Alice Night One - Mixed Apnea (PSS)');
                break;
            case 'Alice Night One - OSA (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_alice_night_one.wkpdf.twig';
                $page_title = strtoupper('Alice Night One - OSA (PSS)');
                break;
            case 'Travel Letter (PSS)':
                $header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_alice_night_one.wkpdf.twig';
                $page_title = strtoupper('Travel Letter (PSS)');
                break;
            //End Perfect Sleep Templates

            case 'Adherence':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Adherence.wkpdf.twig';
                break;
            case 'AISH (Cgy)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/AISH (Cgy).wkpdf.twig';
                break;
            case 'AISH (Edm)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/AISH (Edm).wkpdf.twig';
                break;
            // case 'ALBERTA WORKS (Cgy)':
            //     $view = '@RxConnexion/Patient/FaxTemplate/ALBERTA WORKS (Cgy).wkpdf.twig';
            //     break;
            // case 'ALBERTA WORKS (Edm)':
            //     $view = '@RxConnexion/Patient/FaxTemplate/ALBERTA WORKS (Edm).wkpdf.twig';
            //     break;
            case 'CPAP Pressure Change':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP Pressure Change.wkpdf.twig';
                break;
            case 'CPAP refuse -- Medical issues':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Medical issues.wkpdf.twig';
                break;
            case 'CPAP refuse -- No Funds-No Insurance-Note About Discussion Regarding Financing Options':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- No Funds-No Insurance-Note About Discussion Regarding Financing Options.wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants alternative therapy -consult ENT':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants alternative therapy -consult ENT.wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants alternative therapy - Oral Appliance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants alternative therapy - Oral Appliance.wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants to Talk to Dr. prior to starting therapy (Very Mild to Moderate)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants to Talk to Dr. prior to starting therapy (Very Mild to Moderate).wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants to Talk to Dr. prior to starting therapy (Severe & Very Severe)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants to Talk to Dr. prior to starting therapy (Severe & Very Severe).wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants to think about it (Severe & Very Severe)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants to think about it (Severe & Very Severe).wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants to think about it (Very Mild to Moderate)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants to think about it (Very Mild to Moderate).wkpdf.twig';
                break;
            case 'CPAP -- refused not interested (Severe to Very Severe)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP -- refused not interested (Severe to Very Severe).wkpdf.twig';
                break;
            case 'CPAP -- refused not interested (Very Mild to Moderate)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP -- refused not interested (Very Mild to Moderate).wkpdf.twig';
                break;
            case 'CPAP no book':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP no book.wkpdf.twig';
                break;
            case 'CPAP no-rebook':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP no-rebook.wkpdf.twig';
                break;
            case 'HSAT Refuse -- Had HSAT already':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Refuse -- Had HSAT already.wkpdf.twig';
                break;
            case 'HSAT Refuse -- No coverage-No Insurance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Refuse -- No coverage-No Insurance.wkpdf.twig';
                break;
            case 'HSAT No Book':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT No Book.wkpdf.twig';
                break;
            case 'HSAT No Rebook':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT No Rebook.wkpdf.twig';
                break;
            case 'HSAT Refuse -- Not interested at this time. Wants to go back and speak with their Doctor first':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Refuse -- Not interested at this time. Wants to go back and speak with their Doctor first.wkpdf.twig';
                break;
            case 'HSAT Refuse to Repeat HSAT':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Refuse to Repeat HSAT.wkpdf.twig';
                break;
            case 'HSAT Unable to Contact':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Unable to Contact.wkpdf.twig';
                break;
            case 'Negative OSA':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Negative OSA.wkpdf.twig';
                break;
            case 'Negative OSA (No RDI)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Negative OSA (No RDI).wkpdf.twig';
                break;
            case 'Negative OSA (RDI and AHI)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Negative OSA (RDI and AHI).wkpdf.twig';
                break;
            case 'Oximetry Inconclusive':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry Inconclusive.wkpdf.twig';
                break;
            case 'Oximetry Negative':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry Negative.wkpdf.twig';
                break;
            case 'Oximetry Positive':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry Positive.wkpdf.twig';
                break;
            case 'Oximetry Refuse':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry refuse.wkpdf.twig';
                break;
            case 'Oximetry No Book':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry no book.wkpdf.twig';
                break;
            case 'Prescription':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Prescription.wkpdf.twig';
                break;
            case 'Return CPAP -- Buy Online':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- Buy Online.wkpdf.twig';
                break;
            case 'Return CPAP -- No Funds':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- No funds.wkpdf.twig';
                break;
            case 'Return CPAP -- No Insurance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- No insurance.wkpdf.twig';
                break;
            // case 'Return CPAP -- Try alternative':
//                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
//                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
            //     $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- Try alternative.wkpdf.twig';
            //     break;
            case 'Return CPAP -- Unable to Tolerate':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- Unable to tolerate.wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) Buy online':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- (No Stats) Buy online.wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) No insurance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- (No Stats) No insurance.wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) No Funds':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- (No Stats) No Funds.wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) Try alternative treatment':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- (No Stats) Try alternative treatment.wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) Unable to tolerate (Severe to Very Severe)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- (No Stats) Unable to tolerate (Severe to Very Severe).wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) Unable to tolerate (Very Mild to Moderate)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- (No Stats) Unable to tolerate (Very Mild to Moderate).wkpdf.twig';
                break;
            case 'Specialist Referral':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Specialist Referral.wkpdf.twig';
                break;
            case 'Acknowledgement':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Acknowledgement.wkpdf.twig';
                break;
            case 'Negative Inconclusive':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Negative Inconclusive.wkpdf.twig';
                break;
            // case 'Oral Appliance':
            //     $view = '@RxConnexion/Patient/FaxTemplate/Oral Appliance.wkpdf.twig';
            //     break;
            // case 'Devices and Pediatric Oximetry Letter':
            //     $view = '@RxConnexion/Patient/FaxTemplate/Devices and Pediatric Oximetry Letter.wkpdf.twig';
            //     break;
            case 'Unable to Proceed HSAT Due to High BMI':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Unable to Proceed HSAT Due to High BMI.wkpdf.twig';
                break;

            // THE FOLLOWING LIST BELOW IS FOR THE PURPOSE ON VIEWING OF OLD LETTERS ONLY

            case 'ALBERTA WORKS (Cgy)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/ALBERTA WORKS (Cgy).wkpdf.twig';
                break;
            case 'ALBERTA WORKS (Edm)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/ALBERTA WORKS (Edm).wkpdf.twig';
                break;
            case 'CPAP refuse -- No funds-no insurance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- No funds-no insurance.wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants to Talk to Dr. prior to starting therapy':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants to Talk to Dr. prior to starting therapy.wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants to think about it':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants to think about it.wkpdf.twig';
                break;
            case 'CPAP refused not interested':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refused not interested.wkpdf.twig';
                break;
            case 'HSAT Refuse -- No coverage-insurance ':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Refuse -- No coverage-insurance.wkpdf.twig';
                break;
            case 'HSAT -- No Book':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT -- No Book.wkpdf.twig';
                break;
            case 'HSAT -- No Rebook':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT -- No Rebook.wkpdf.twig';
                break;
            case 'HSAT Refuse -- Refuse repeat HSAT':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT Refuse -- Refuse repeat HSAT.wkpdf.twig';
                break;
            case 'HSAT -- Unable to Contact':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/HSAT -- Unable to Contact.wkpdf.twig';
                break;
            case 'Indian Affairs':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Indian Affairs.wkpdf.twig';
                break;
            case 'Negative OSA (-RDI)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Negative OSA (-RDI).wkpdf.twig';
                break;
            case 'Negative OSA (-RDI, AHI)':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Negative OSA (-RDI, AHI).wkpdf.twig';
                break;
            case 'Oximetry refuse':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry refuse.wkpdf.twig';
                break;
            case 'Oximetry no book':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oximetry no book.wkpdf.twig';
                break;
            case 'Return CPAP -- No funds':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- No funds.wkpdf.twig';
                break;
            case 'Return CPAP -- No insurance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- No insurance.wkpdf.twig';
                break;
            case 'Return CPAP -- Try alternative':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- Try alternative.wkpdf.twig';
                break;
            case 'Return CPAP -- Unable to tolerate':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP -- Unable to tolerate.wkpdf.twig';
                break;
            case 'Return CPAP (no stats) -- Buy online':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP (no stats) -- Buy online.wkpdf.twig';
                break;
            case 'Return CPAP (no stats) -- No insurance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP (no stats) -- No insurance.wkpdf.twig';
                break;
            case 'Return CPAP (no stats) -- No funds':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP (no stats) -- No funds.wkpdf.twig';
                break;
            case 'Return CPAP -- (No Stats) Try alternative':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP (no stats) -- Try alternative.wkpdf.twig';
                break;
            case 'Return CPAP (no stats) -- Unable to tolerate':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Return CPAP (no stats) -- Unable to tolerate.wkpdf.twig';
                break;
            case 'Devices and Pediatric Oximetry Letter':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Devices and Pediatric Oximetry Letter.wkpdf.twig';
                break;
            case 'Oral Appliance':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/Oral Appliance.wkpdf.twig';
                break;
            case 'CPAP refuse -- Wants alternative therapy -MAD':
                $header = '@RxConnexion/Patient/FaxTemplate/header.wkpdf.twig';
                $footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
                $view = '@RxConnexion/Patient/FaxTemplate/CPAP refuse -- Wants alternative therapy -MAD.wkpdf.twig';
                break;
        }

        $patientLetterCreatedBy = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->patientLetterCreatedBy(base64_decode($patientLetter_id));

        if($view != ''){
            $userData = $this->get('session')->get('userData');

            $xml2 = null;
            if($letter_type == 'General Prescription (FRSC)') {
                $content2 = $this->renderView('@RxConnexion/Patient/FaxTemplate/FreedomTemplate/GeneralPrescriptionForm.wkpdf.twig', array(
                    'page_title' => $page_title,
                    'patientLetter' => $patientLetter,
                    'patientLetterGeneralPrescriptionFrsi' => $patientLetterGeneralPrescriptionFrsi,
                    'dateToday' => date('F j, Y'),
                    'userData'  => $userData,
                    'cover'     =>  'pr' // u-urgent/fr-for review/pc-please comment/pr-please reply
                ));
                $xml2 = $this->get('knp_snappy.pdf')->getOutputFromHtml($content2, array(
                    'page-size' => 'Letter',
                    'margin-top' => '20mm',
                    'margin-right' => '15mm',
                    'margin-left' => '15mm',
                    'margin-bottom' => '20mm',
                    'dpi' => 72,
                    // 'disable-smart-shrinking',
                    'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
                ));
            }

            $content = $this->renderView($view, array(
                'page_title' => $page_title,
                'patientLetter' => $patientLetter,
                'patientPrescription' => $patientPrescription,
                'prescriptionFrsi' => $prescriptionFrsi,
                'prescriptionFrsiV2' => $prescriptionFrsiV2,
                'aliceNightOne' => $aliceNightOne,
                'patientLetterGeneralPrescriptionFrsi' => $patientLetterGeneralPrescriptionFrsi,
                'prescriptionPss' => $prescriptionPss,
                'patientSpecialistReferral' => $patientSpecialistReferral,
                'patientLetterRefusalCare' => $patientLetterRefusalCare,
                'patientLetterCreatedBy' => $patientLetterCreatedBy,
                'dateToday' => date('F j, Y'),
                'userData'  => $userData,
                'cover'     =>  'pr' // u-urgent/fr-for review/pc-please comment/pr-please reply
            ));
            $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
                'page-size' => 'Letter',
                'margin-top' => '40mm',
                'margin-right' => '15mm',
                'margin-left' => '15mm',
                'margin-bottom' => '40mm',
                'header-html' => $this->renderView($header, array(
                    'patientLetter' => $patientLetter,
                )),
                'footer-html' => $this->renderView($footer),
                'header-spacing' => 35,
                'footer-spacing' => 10,
                'dpi' => 72,
                // 'disable-smart-shrinking',
                'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
            ));
            try {
                $tmpLetter2 = null;
                $gs = $this->getParameter('ghostscript');

                $pdf = new \PDFMerger();

                // save the LETTER temporarily
                $tmpLetter = $patientLetter->getTmpRootDir() . '/' . $patientLetter->getId() . '-' . uniqid() . '.pdf';
                file_put_contents($tmpLetter, $xml);

                $pdf->addPDF($tmpLetter, 'all');

                if($letter_type == 'General Prescription (FRSC)') {
                    $tmpLetter2 = $patientLetter->getTmpRootDir() . '/' . $patientLetter->getId() . '-general-prescription-' . uniqid() . '.pdf';
                    file_put_contents($tmpLetter2, $xml2);

                    $pdf->addPDF($tmpLetter2, 'all');
                }

                $letterAttachment = $em->getRepository('RxConnexionBundle:PatientLetterFileEntity')->findBy(array(
                    'patientLetter' => base64_decode($patientLetter_id),
                    'isDeleted' => false,
                ));

                //The PDF version that you want to convert
                //the file into.
                $pdfVersion = "1.4";
                $newFiles = array();
                if ($letterAttachment) {
                    foreach($letterAttachment as $letterAttachments) {
                        //The path that you want to save the new file to
                        $newFile = $letterAttachments->getUploadRootDir2().'/'.$letterAttachments->getParsedFileDesc();

                        //The path of the file that you want to convert
                        $currentFile = $letterAttachments->getUploadRootDir().'/'.$letterAttachments->getParsedFileDesc();

                        //Execute command of Ghostscript
                        shell_exec($gs.' -sDEVICE=pdfwrite -dCompatibilityLevel='.$pdfVersion.' -dPDFSETTINGS=/printer -dNOPAUSE -dBATCH -sOutputFile='.$newFile.' '.$currentFile.'');

                        $pdf->addPDF($newFile, 'all');
                        $newFiles[] = $newFile;
                    }
                }


                $binaryContent = $pdf->merge('string', "mergedpdf.pdf");
                $response = new Response($binaryContent);
                $response->headers->set('Content-type' , 'application/pdf');

                //DELETE TEMP LETTER PDF FILE
                unlink($tmpLetter);

                if ($letter_type == 'General Prescription (FRSC)') {
                    unlink($tmpLetter2);
                }

                foreach($newFiles as $newFile){
                    unlink($newFile);
                }

                return $response;

            } catch(\Exception $e){
                return $this->redirect($this->generateUrl('patient_detail',array(
                    'patient_id' => base64_encode($patientLetter->getPatient()->getId())
                )), 302);
            }
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'No such document to preview.');
            return $this->redirect($this->generateUrl('patient_detail',array(
                'patient_id' => base64_encode($patientLetter->getPatient()->getId())
            )), 302);
        }
        
    }

    /*private function sendFax($receiverFaxNum, $fileName, $file){
        $srFax = $this->get('rx_connexion.SRFaxService');
        $send = $srFax->Queue_Fax(array(
            //'sCallerID'        =>  '8332624798', // Our Fax Number
            //'sSenderEmail'     =>  'dummy.email@moldedcraft.com', // Our Email Address
            'sFaxType'         =>  $srFax::FAX_TYPE_SINGLE, // Single Fax
            'sToFaxNumber'     =>  $receiverFaxNum,
            'sFileName_1'      =>  $fileName,
            'sFileContent_1'   =>  (($file))
        ));
        // return true if success, false if not
        if($send){
            $return = array('success' => true, 'msg' => $srFax->getRequestResponse());
        } else {
            $return = array('success' => false, 'msg' => $srFax->getRequestResponse());
        }
        return $return;
    }*/

    //PATIENT LETTER NOTE

//    /**
//     * @Route("/patient_letter_note_ajax_list", name="patient_letter_note_ajax_list")
//     */
//    public function patient_letter_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 Patient Letter Note Update'), false);
//
//            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientLetterNoteEntity')->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-patient-letter-note-form' data-action='u' data-id='$id'>Update</a>";
//                }
//
//                $values = array(
//                    $row['note'],
//                    $action
//                );
//
//                $result['data'][] = $values;
//            }
//
//            $result['recordsTotal'] = $data['total'];
//            $result['recordsFiltered'] = $data['total'];
//        }
//
//        return new JsonResponse($result);
//    }

    /**
     * @Route(
     *      "/patient_letter_note/form/{patient_letter_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_letter_note_form"
     * )
     */
    public function patient_letter_note_formAction($patient_letter_id, $action, $id) {

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

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

        if(!$patientLetterNote) {
            $patientLetterNote = new PatientLetterNoteEntity();
        }

        $formOptions = array(
            'action' => $action,
            'patient_letter_id' => $id
        );
        $form = $this->createForm(PatientLetterNoteForm::class, $patientLetterNote, $formOptions);

        $title = 'New Reply';

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

    /**
     * @Route(
     *      "/patient_letter_note/save_action",
     *      name = "patient_letter_note_save"
     * )
     */
    public function patient_letter_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 Patient Letter Note', 'Admin Patient Letter Note'))) return $authService->redirectToHome();

        $patientLetterNote_form = $request->get('patient_letter_note');
        $em = $this->getDoctrine()->getManager();
        $patientLetterNote = $em->getRepository('RxConnexionBundle:PatientLetterNoteEntity')->find($patientLetterNote_form['id']);
        if(!$patientLetterNote) {
            $patientLetterNote = new PatientLetterNoteEntity();
        }

        $formOptions = array(
            'action' => $patientLetterNote_form['action'],
            'patient_letter_id' => $patientLetterNote_form['patient_letter']
        );
        $form = $this->createForm(PatientLetterNoteForm::class, $patientLetterNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientLetterNoteEntity')->validate($patientLetterNote_form);

        if(!count($errors)) {

            switch($patientLetterNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        $newAT = new AuditTrailEntity(
                            'Patient Letter Note',
                            $em->getClassMetadata(PatientLetterNoteEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientLetterNote;
                        $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(
                        'Patient Letter Note',
                        $em->getClassMetadata(PatientLetterNoteEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientLetterNote;
                    $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(
                        'Patient Letter Note',
                        $em->getClassMetadata(PatientLetterNoteEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientLetterNote;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $patientLetterNote->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(
     *      "/patient_letter_note_view",
     *      name = "patient_letter_note_view"
     * )
     */
    public function patientLetterNoteViewAction(Request $request) {

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $session = $this->get('session');
        $userData = $session->get('userData');

        $em = $this->getDoctrine()->getManager();
        $patientLetterNote = $em->getRepository('RxConnexionBundle:PatientLetterNoteEntity')->patientLetterNoteView(array(
            'patientLetterId' => base64_decode($request->request->get('patientLetterId')),
            'username' => $userData['username']
        ));

        return new JsonResponse($patientLetterNote);
    }



    /**
     * @Route("/patient_note_ajax_list", name="patient_note_ajax_list")
     */
    public function patient_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 Patient Note Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Note Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Note' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$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("/patient_note_clinical_ajax_list", name="patient_note_clinical_ajax_list")
     */
    public function patient_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 Patient Note Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Note Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Note' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$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("/patient_note_billing_ajax_list", name="patient_note_billing_ajax_list")
     */
    public function patient_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 Patient Note Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Note Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Note' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$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("/patient_note_appointment_ajax_list", name="patient_note_appointment_ajax_list")
     */
    public function patient_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 Patient Note Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Note Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Note' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$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("/patient_note_specialist_ajax_list", name="patient_note_specialist_ajax_list")
     */
    public function patient_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 Patient Note Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Note Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Note' value='$id' class='patient-transfer-checkbox'>";
                }


                $values = array(
                    $transferLink.$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("/patient_note_letter_ajax_list", name="patient_note_letter_ajax_list")
     */
    public function patient_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 Patient Note Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Note Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Note' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$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(
     *      "/patient_note/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_note_form"
     * )
     */
    public function patient_note_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientNoteForm::class, $patientNote, $formOptions);


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

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

    /**
     * @Route(
     *      "/patient_note/save_action",
     *      name = "patient_note_save"
     * )
     */
    public function patient_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 Patient Note New', 'Admin Patient Note Update'))) return $authService->redirectToHome();

        $patientNote_form = $request->get('patient_note');
        $em = $this->getDoctrine()->getManager();
        $patientNote = $em->getRepository('RxConnexionBundle:PatientNoteEntity')->find($patientNote_form['id']);
        if(!$patientNote) {
            $patientNote = new PatientNoteEntity();
        }
        $formOptions = array(
            'action' => $patientNote_form['action'],
            'patient_id' => $patientNote_form['patient']
        );
        $form = $this->createForm(PatientNoteForm::class, $patientNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientNoteEntity')->validate($patientNote_form);

        if(!count($errors)) {

            switch($patientNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientNote);
                        $patientNote->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("/patient_schedule_ajax_list", name="patient_schedule_ajax_list")
     */
    public function patient_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 Patient Schedule Update'), false);
            //$hasPreview = $authService->isUserHasAccesses(array('Admin Appointment Notice Pdf Preview'), false);
            $hasAppointmentNotice = $authService->isUserHasAccesses(array('Admin Appointment Notice'), false);



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

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

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

                /*if($hasFax) {
                    $action .= "<a class='action-button-style href-patient-appointment-notice-form' href='javascript:void(0)' data-action='u' data-patient-id='$patientId' data-schedule-id='$id' data-id=''>Appointment Notice</a>";
                }*/

                /*if($hasAppointmentNotice) {
                    $action .= "<a class='action-button-style href-patient-appointment-notice-form' href='javascript:void(0);' data-action='u' data-patient-id='$patientId' data-schedule-id='$id' data-id=''>Appointment Notice</a>";
                }*/


                /*if($hasPreview) {
                    $faxPreviewUrl = $this->generateUrl('appointment_fax_preview', array(
                        'patient_id' =>$get['patient_id'],
                        'action' => 'u',
                        'schedule_id' => $id
                    ));
                    $action .= "<a class='action-button-style' href='$faxPreviewUrl' target='_blank'>Fax Preview</a>";
                }*/

                if($hasUpdate) {
                    $url = $this->generateUrl('patient_schedule_form', array(
                        'patient_id' =>$get['patient_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['provider_fullName'],
                    $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);
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*					Appointment Notice																	  */
    /*--------------------------------------------------------------------------------------------------------*/

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

            $hasPreview = $authService->isUserHasAccesses(array('Admin Appointment Notice Pdf Preview'), false);
            $hasFax = $authService->isUserHasAccesses(array('Admin Appointment Fax Pdf'), false);

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

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

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

                if($hasFax) {
                    $faxUrl = $this->generateUrl('appointment_fax_export_to_pdf', array(
                        'anf_id' => $id
                    ));
                    $action .= "<a class='action-button-style ask-continue' data-message='Are you sure you want to fax $recipient?' href='$faxUrl'>Fax ({$row['faxCtr']})</a>";
                }

                if($hasPreview) {
                    $faxPreviewUrl = $this->generateUrl('appointment_fax_preview', array(
                        'anf_id' => $id
                    ));
                    $action .= "<a class='action-button-style' href='$faxPreviewUrl' target='_blank'>Fax Preview</a>";
                }

                $values = array(
                    $row['createdAt'],
                    $row['scheduleId'],
                    $row['affiliateType'],
                    $row['affiliateName'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/appointment_fax/export_to_pdf/{anf_id}",
     *      name = "appointment_fax_export_to_pdf"
     * )
     */
    public function appointment_fax_export_to_pdfAction($anf_id) {

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

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        //$patient_record = $em->getRepository('RxConnexionBundle:AppointmentNoticeFaxEntity')->appointmentLetterPdf(base64_decode($patient_id), base64_decode($schedule_id));
        $anf = $em->getRepository('RxConnexionBundle:AppointmentNoticeFaxEntity')->find(base64_decode($anf_id));
        $scheduleBranch = $em->getRepository('RxConnexionBundle:ScheduleEntity')->findOneBy(array(
            'id' => $anf->getSchedule()
        ));

        $template_header = null;
        $template = null;
        $template_footer = null;
        switch ($scheduleBranch->getHealthFacility()->getCompany()->getDescription()) {
            case 'Freedom Respiratory & Sleep Centre' :
                $template_header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $template = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_appointment_notice.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                break;
            case 'Perfect Sleep Solutions WC Inc.' :
                $template_header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $template = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_appointment_notice.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                break;
            default:
                $template_header = '@RxConnexion/Patient/FaxTemplate/appointment_notice_header.wkpdf.twig';
                $template = '@RxConnexion/Patient/FaxTemplate/Appointment.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
        }

        $page_title = 'Appointment Notice Letter';
        $content = $this->renderView($template, array(
            'page_title' => $page_title,
            'anf' => $anf
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'page-size' => 'Letter',
            'margin-top' => '40mm',
            'margin-right' => '15mm',
            'margin-left' => '15mm',
            'margin-bottom' => '40mm',
            'footer-html' => $this->renderView($template_footer),
            'header-html' => $this->renderView($template_header, array(
                'anf' => $anf
            )),
            'header-spacing' => 35,
            'footer-spacing' => 10,
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));




        /*//$fileName = $patient_record['patient_fullName'].'-.pdf';
        $receiverFaxNum = null;
        $receiverFaxNumTwo = null;
        if($patient_record['referringAffiliate_desc']){
            $receiverFaxNum = $patient_record['referringAffiliate_fax'];
            $receiverFaxNumTwo = $patient_record['referringAffiliate_faxTwo'];
            $ref = 'Health Facility';
        } elseif($patient_record['referring_provider_fullName']) {
            $receiverFaxNum = $patient_record['referring_provider_faxNo'];
            $receiverFaxNumTwo = $patient_record['referring_provider_faxNo_two'];
            $ref = 'Provider';
        } elseif($patient_record['insurance']) {
            $receiverFaxNum = $patient_record['insuranceFax'];
            $receiverFaxNumTwo = $patient_record['insuranceFaxTwo'];
            $ref = 'Insurance';
        }else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Patient does not have referral information. Please update patient details.');
            return $this->redirect($this->generateUrl('patient_detail',array(
                'patient_id' => base64_encode($patient_record['patient_id']),
            )), 302);
        }*/

        switch($anf->getAffiliateType()) {
            /*case AppointmentNoticeFaxEntity::AFFILIATE_TYPE['Referring Affiliate']:
                $hf = $anf->getPatientReferringHealthFacility()->getReferringHealthFacility();
                $receiverFaxNum = $hf->getFaxNo();
                $receiverFaxNumTwo = $hf->getFaxNoTwo();
                break;*/
            case AppointmentNoticeFaxEntity::AFFILIATE_TYPE['Referring Physician']:
                $rp = $anf->getPatientReferringProvider()->getReferringProvider();
                $patient = $anf->getPatient();
                $receiverFaxNum = $rp->getFaxNo();
                $receiverFaxNumTwo = $rp->getFaxNoTwo();
                if($receiverFaxNum != '' || $receiverFaxNum != null){
                    $receiverFaxNum = $rp->getFaxNo();
                }else{
                    $receiverFaxNum = '';
                    foreach ($patient->getPatientReferringHealthFacilities() as $prhf){
                        foreach ($rp->getReferringHealthFacilityProviders() as $rhfp){
                            if($prhf->getReferringHealthFacility()->getId() == $rhfp->getReferringHealthFacility()->getId()){
                                $receiverFaxNum = $rhfp->getReferringHealthFacility()->getFaxNo();
                            }
                        }
                    }
                }
                break;
            default: // Insurance
                $insurance = $anf->getPatientInsurance()->getInsurance();
                $receiverFaxNum = $insurance->getFaxNo();
                $receiverFaxNumTwo = $insurance->getFaxNoTwo();
                break;
        }

        $receiver = preg_replace("/[^0-9]/", "", $receiverFaxNum);
        if($receiver == '' || $receiver == null){
            $receiver = preg_replace("/[^0-9]/", "", $receiverFaxNumTwo);
        }

        if($receiver != null || $receiver != ''){

            /*$send = $this->sendFax($receiver,$fileName, base64_encode($xml));
            if($send['success']){
                $this->get('session')->getFlashBag()->set('success_messages', 'Fax successfully queued.');
            } else {
                $this->get('session')->getFlashBag()->set('error_messages', $send['msg']);
            }*/

            $fileName = 'Appointment Notice No. ' . $anf->getId() . uniqid() . '.pdf';
            $srFax = $this->get('rx_connexion.SRFaxService');

            $newFaxTranOut = new FaxTranOutboundEntity();
            $newFaxTranOut->setSource(FaxTranOutboundEntity::SOURCE_SCHEDULE_NOTICE);
            $newFaxTranOut->setAppointmentNoticeFax($anf);
            $newFaxTranOut->setFaxType($srFax::FAX_TYPE_SINGLE);
            $newFaxTranOut->setFaxNo($receiver);
            $newFaxTranOut->setFileName($fileName);

            $queueOptions = array();
            $queueOptions['sFaxType'] = $srFax::FAX_TYPE_SINGLE; // Single Fax;
            $queueOptions['sToFaxNumber'] = $receiver;
            $queueOptions['sFileName_1'] = $fileName;
            $queueOptions['sFileContent_1'] = ((base64_encode($xml)));
            $queueOptions['sNotifyURL'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . $this->generateUrl('patient_appointment_fax_status_receipt');
            $status = $srFax->Queue_Fax($queueOptions);

            $newFaxTranOut->setStatus($status);

            if($status){
                $newFaxTranOut->setFaxId($srFax->getRequestResponse());
                $newFaxTranOut->setMsg('Fax successfully queued.');
                $this->get('session')->getFlashBag()->set('success_messages', 'Fax successfully queued.');
            } else {
                $newFaxTranOut->setMsg($srFax->getRequestResponse());
                $this->get('session')->getFlashBag()->set('error_messages', $srFax->getRequestResponse());
            }

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

        } else {
            $this->get('session')->getFlashBag()->set('error_messages', 'Affiliate Doesn\'t have fax number.');
        }


        return $this->redirect($this->generateUrl('patient_detail',array(
            'patient_id' => $anf->getPatient()->getIdEncoded(),
            'tab' => 's'
        )), 302);
    }

    /**
     * @Route(
     *      "/appointment_fax_preview/export_to_pdf/{anf_id}",
     *      name = "appointment_fax_preview"
     * )
     */
    public function patient_appointment_notice_fax_pdfViewAction($anf_id) {

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

        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $em = $this->getDoctrine()->getManager();
        $appointmentNoticeFax = $em->getRepository('RxConnexionBundle:AppointmentNoticeFaxEntity')->find(base64_decode($anf_id));
        $scheduleBranch = $em->getRepository('RxConnexionBundle:ScheduleEntity')->findOneBy(array(
            'id' => $appointmentNoticeFax->getSchedule()
        ));

        $template_header = null;
        $template = null;
        $template_footer = null;

        switch ($scheduleBranch->getHealthFacility()->getCompany()->getDescription()) {
            case 'Freedom Respiratory & Sleep Centre' :
                $template_header = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_header.wkpdf.twig';
                $template = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_appointment_notice.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/FreedomTemplate/frsi_footer.wkpdf.twig';
                break;
            case 'Perfect Sleep Solutions WC Inc.' :
                $template_header = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_header.wkpdf.twig';
                $template = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_appointment_notice.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/PerfectSleepTemplate/pss_footer.wkpdf.twig';
                break;
            default:
                $template_header = '@RxConnexion/Patient/FaxTemplate/appointment_notice_header.wkpdf.twig';
                $template = '@RxConnexion/Patient/FaxTemplate/Appointment.wkpdf.twig';
                $template_footer = '@RxConnexion/Patient/FaxTemplate/footer.wkpdf.twig';
        }

        $page_title = 'Appointment Notice Preview';
        $content = $this->renderView($template, array(
            'page_title' => $page_title,
            'anf' => $appointmentNoticeFax
        ));

        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'page-size' => 'Letter',
            'margin-top' => '40mm',
            'margin-right' => '15mm',
            'margin-left' => '15mm',
            'margin-bottom' => '40mm',
            'footer-html' => $this->renderView($template_footer),
            'header-html' => $this->renderView($template_header, array(
                'anf' => $appointmentNoticeFax
            )),
            'header-spacing' => 40,
            'footer-spacing' => 10,
            'dpi' => 72,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1
        ));

        $pdfResponse = array(
            'success' => true,
            'msg' => 'PDF was successfully generated.',
            'pdfBase64' => base64_encode($xml)
        );
        if($pdfResponse['success']) {
            $pdfContent = $pdfResponse['pdfBase64'];
            return new Response(base64_decode($pdfContent), 200, array(
                'Content-Type' => 'application/pdf',
            ));
        } else {
            $this->get('session')->getFlashBag()->set('error_messages', $pdfResponse['msg']);
            return $this->redirect($this->generateUrl('patient_detail', 302));
        }
    }

    /**
     * @Route(
     *      "/appointment_notice/form",
     *      name = "appointment_notice_form"
     * )
     */
    public function patient_appointment_fax_formAction(Request $request) {

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

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

        $patientId = $request->query->get('patient_id');
        $scheduleId = $request->query->get('schedule_id');

        $formOptions = array(
            'action' => 'n',
            'patient_id' => $patientId,
            'schedule_id' => $scheduleId
        );
        $form = $this->createForm(AppointmentNoticeFaxForm::class, $appointmentFax, $formOptions);

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

            $form->handleRequest($request);

            if($form->isValid()) {

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

                $newAT = new AuditTrailEntity(
                    'Appointment Notice Fax',
                    $em->getClassMetadata(AppointmentNoticeFaxEntity::class)->getTableName(),
                    AuditTrailEntity::AXN_NEW
                );
                $newAT->entity = $appointmentFax;
                $newAT->parseDetails();
                $em->persist($newAT);

                $em->flush();

                $this->get('session')->getFlashBag()->set('success_messages', 'Appointment notice was successfully created.');

            } else {
                $this->get('session')->getFlashBag()->set('error_messages', 'Something went wrong. Please try again.');
            }

            return $this->redirect($this->generateUrl('patient_schedule_form', array(
                'patient_id' => $patientId,
                'action' => 'u',
                'id' => $scheduleId
            )), 302);
        }

        $title = 'Appointment Notice';

        $result['html'] =  $this->renderView('@RxConnexion/Schedule/appointment_notice_fax.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            //'action' => $action,
            //'sendFax' => $faxUrl,
            'patient_id' => $patientId,
            'schedule_id' => $scheduleId,
            //'id' => $id
        ));
        $result['success'] = true;

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_appointment_fax_status_receipt",
     *      name = "patient_appointment_fax_status_receipt"
     * )
     */
    public function patient_appointment_fax_status_receiptAction(Request $request) {
        $result['success'] = false;
        $result['msg'] = 'No matching remote id.';
        $filName = $request->get('FileName');
        $sentStatus = $request->get('SentStatus');
        $dateQueued = $request->get('DateQueued');
        $dateSent = $request->get('DateSent');
        $toFaxNumber = $request->get('ToFaxNumber');
        $noPage = $request->get('Pages');
        //$duration = $request->get('Duration');
        $fileNameDetails = explode('|', $filName);
        $remoteId = $fileNameDetails[1];
        $faxDetails = array(
            'fileName' => $filName,
            'sentStatus' => $sentStatus,
            'dateQueued' => $dateQueued,
            'dateSent' => $dateSent,
            'toFaxNumber' => $toFaxNumber,
            'pages' => $noPage
        );

        $em = $this->getDoctrine()->getManager();
        $faxTranOutBound = $em->getRepository('RxConnexionBundle:FaxTranOutboundEntity')->findOneBy(array(
            'faxId' => $remoteId
        ));

        $fileType = $em->getRepository('RxConnexionBundle:FileTypeEntity')->findOneBy(array(
            'description' => 'Fax Confirmation'
        ));

        if($faxTranOutBound){
            if($faxTranOutBound->getAppointmentNoticeFax()){
                $patient = $faxTranOutBound->getAppointmentNoticeFax()->getPatient();
                $content = $this->renderView('@RxConnexion/Referral/FaxTemplate/FaxReceipt.wkpdf.twig', array(
                    'response' => $faxDetails
                ));
                $fileName = $remoteId . ' - Fax Confirmation';
                $patientFile = new PatientFileEntity();
                $patientFile->setNote('Appointment Notice');
                $patientFile->setFileType($fileType);
                $patientFile->setPatient($patient);
                $em->persist($patientFile);
                $em->flush();
                $baseName = $patientFile->getId() . '-' . time() . '.pdf';
                $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;
                $this->get('knp_snappy.pdf')->generateFromHtml($content, $uploadFile);
                $patientFile->removeFile();
                $patientFile->setDescription($fileName.'.pdf');
                $patientFile->setParsedDescription($baseName);
                $em->flush();

                $this->faxEmail(array(
                    'patient' => $patient,
                    'uploadedFile' => $uploadFile
                ));

                $result['success'] = true;
                $result['msg'] = 'Confirmation received.';
            }
        }

        $logData = '[' . date('Y-m-d H:i:s') . ']';
        $logData .= ' Post Data: ' . json_encode($faxDetails);
        $logData .= '[' . date('Y-m-d H:i:s') . ']';

        $logFileName = $this->getParameter('fax_api_log_dir') . '/notify/fax_notify.log';
        if(file_exists($logFileName)){
            $logFile = fopen($logFileName, "a+");
            fwrite($logFile, PHP_EOL . $logData);
        }else{
            $logFile = fopen($logFileName, "w");
            fwrite($logFile, $logData);
        }
        fclose($logFile);
        $logSize = $this->getParameter('api_log_max_size');
        if($logSize >= $this->getParameter('api_log_max_size')) {
            rename($logFileName, $this->getParameter('fax_api_log_dir') . '/notify/fax_notify' . '-' . date('Y-m-d-H-i-s') . '.log');
        }

        return new JsonResponse($result);

    }


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

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

        $em = $this->getDoctrine()->getManager();
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));

        $schedule = $em->getRepository('RxConnexionBundle:ScheduleEntity')->find(base64_decode($id));
        if(!$schedule) {
            $schedule = new ScheduleEntity();
        }else{
            $appointmentFax = new AppointmentNoticeFaxEntity();
            $formOptions2 = array(
                'action' => 'n',
                'patient_id' => $patient_id,
                'schedule_id' => $id
            );

            $form2 = $this->createForm(AppointmentNoticeFaxForm::class, $appointmentFax, $formOptions2);
        }

        $formOptions = array(
            'patient_id' => $patient_id,
            'action' => $action
        );
        $form = $this->createForm(PatientScheduleForm::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('patient_detail',array(
                        'patient_id' => $patient_id,
                        'tab' => 's'
                    )), 302);
                } else if($result['redirect'] === 'schedule_form_detail') {
                    return $this->redirect($this->generateUrl('patient_schedule_form', array(
                        'patient_id' => $patient_id,
                        'action' => 'u',
                        'id' => $result['schedule_id'],
                        'tab' => 's'
                    )), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('patient_schedule_form', array(
                        'patient_id' => $patient_id,
                        'action' => 'u',
                        'id' => base64_encode($result['id']),
                        'tab' => 's'
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('patient_schedule_form'), 302);
                }
            } else {
                $form->submit($schedule_form, false);
            }

        }

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

        return $this->render('@RxConnexion/Patient/schedule_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/patient/patient_schedule_form.js?v=1.0.5'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'patient_id' => $patient_id,
            'form2' =>  isset($form2) ? $form2->createView() : array(),
            'noteTemplateAccess' => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
        ));
    }

    private function scheduleProcessForm($schedule_form, $schedule, $form, Request $request) {
        $oldNotes = $schedule->getNote();
        $oldChartType = $schedule->getChartType() ? $schedule->getChartType()->getId() : 0;
        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:ScheduleEntity')->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->getScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));

                        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->persist($schedule);
                        $patientChart = new PatientChartEntity();
                        $patientChart->setSchedule($schedule);
                        $patientChart->setHealthFacility($schedule->getHealthFacility());
                        $patientChart->setProvider($schedule->getProvider());
                        $patientChart->setPatient($schedule->getPatient());
                        $patientChart->setChartType($schedule->getChartType());
                        if($chartStatus){
                            $patientChart->setChartStatus($chartStatus);
                        }
                        $patientChart->setChartDate($schedule->getScheduleDateAsString());
                        $em->persist($patientChart);
                        $patientChartNote = new PatientChartNoteEntity();
                        $patientChartNote->setPatientChart($patientChart);
                        $patientChartNote->setNote($schedule->getNote());
                        $em->persist($patientChartNote);
                        $patientNote = new PatientNoteEntity();
                        $patientNote->setPatient($schedule->getPatient());
                        $patientNote->setType($schedule_form['note_type']);
                        $patientNote->setNote($schedule->getNote());
                        $em->persist($patientNote);

                        if($schedule->getChartType()->getMethods()){
                            $patientChartTypeMethod = new PatientChartTypeMethodEntity();
                            $note = '<p>CPAP SET UP&nbsp;&nbsp;</p><p>Date ___________</p><p>MACHINE</p><p>Pressure range __________</p><p>Ramp time and pressure ___________</p><p>Mask used ___________</p><p>Tubing __________</p><p>Booked for End Evaluation: ____________</p><p>Insurance Coverage and Plan for Payment: ___________, offered ____________ payment plan.</p>';
                            foreach ($schedule->getChartType()->getMethods() as $chartTypeMethod){
                                $patientChartTypeMethod->setPatientChart($patientChart);
                                $patientChartTypeMethod->setChartTypeMethod($chartTypeMethod);
                                $patientChartTypeMethod->setNote($note);
                                $em->persist($patientChartTypeMethod);
                                $em->flush();
                            }
                        }
                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Schedule',
                            $em->getClassMetadata(ScheduleEntity::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'] = 'schedule_form_detail';
                        $result['schedule_id'] = $schedule->getIdEncoded();

                    } 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(
                        'Schedule',
                        $em->getClassMetadata(ScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $schedule;
                    $newAT->parseOriginalDetails();

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

                        $patientChart->setHealthFacility($schedule->getHealthFacility());
                        $patientChart->setProvider($schedule->getProvider());
                        $patientChart->setPatient($schedule->getPatient());
                        $patientChart->setChartType($schedule->getChartType());
                        if($patientChart->getChartStatus()){
                            $scheduleStatus = $em->getRepository('RxConnexionBundle:ScheduleStatusEntity')->findOneBy(array(
                                'description' => $patientChart->getChartStatus()->getDescription()
                            ));
                        }else{
                            $scheduleStatus = array();
                        }

                        $chartStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findOneBy(array(
                            'description' => $schedule->getScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));
                        if($chartStatus && $scheduleStatus){
                            $patientChart->setChartStatus($chartStatus);
                        }
                        if($schedule->getNote() != $oldNotes){
                            $patientChartNote = new PatientChartNoteEntity();
                            $patientChartNote->setPatientChart($patientChart);
                            $patientChartNote->setNote($schedule->getNote());
                            $em->persist($patientChartNote);
                            $patientNote = new PatientNoteEntity();
                            $patientNote->setPatient($schedule->getPatient());
                            $patientNote->setType($schedule_form['note_type']);
                            $patientNote->setNote($schedule->getNote());
                            $em->persist($patientNote);
                        }
                        if($schedule->getChartType()->getId() != $oldChartType){
                            $note = '<p>CPAP SET UP&nbsp;&nbsp;</p><p>Date ___________</p><p>MACHINE</p><p>Pressure range __________</p><p>Ramp time and pressure ___________</p><p>Mask used ___________</p><p>Tubing __________</p><p>Booked for End Evaluation: ____________</p><p>Insurance Coverage and Plan for Payment: ___________, offered ____________ payment plan.</p>';
                            $newPatientChartTypeMethod = new PatientChartTypeMethodEntity();
                            if($schedule->getPatientChart()->getChartTypeMethods()){
                                foreach ($schedule->getPatientChart()->getChartTypeMethods() as $patientChartTypeMethod){
                                    //$em->remove($patientChartTypeMethod);
                                    $patientChartTypeMethod->setIsDeleted(true);
                                    $em->flush();
                                }
                                foreach ($schedule->getChartType()->getMethods() as $chartTypeMethod){
                                    $newPatientChartTypeMethod->setPatientChart($patientChart);
                                    $newPatientChartTypeMethod->setChartTypeMethod($chartTypeMethod);
                                    $newPatientChartTypeMethod->setNote($note);
                                    $em->persist($newPatientChartTypeMethod);
                                    $em->flush();
                                }
                            }
                        }
                        $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(
                        'Schedule',
                        $em->getClassMetadata(ScheduleEntity::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("/patient_chart_note_ajax_list", name="patient_chart_note_ajax_list")
     */
    public function patient_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 Patient Chart Note Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientChartNoteEntity')->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-patient-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(
     *      "/patient_chart_note/form/{patientChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_note_form"
     * )
     */
    public function patient_chart_note_formAction($patientChart_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patientChart_id' => $patientChart_id
        );
        $form = $this->createForm(PatientChartNoteForm::class, $patientChartNote, $formOptions);


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

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

    /**
     * @Route(
     *      "/patient_chart_note/save_action",
     *      name = "patient_chart_note_save"
     * )
     */
    public function patient_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 Patient Chart Note New', 'Admin Patient Chart Note Update'))) return $authService->redirectToHome();

        $patientChartNote_form = $request->get('patient_chart_note');
        $em = $this->getDoctrine()->getManager();
        $patientChartNote = $em->getRepository('RxConnexionBundle:PatientChartNoteEntity')->find($patientChartNote_form['id']);
        if(!$patientChartNote) {
            $patientChartNote = new PatientChartNoteEntity();
        }
        $formOptions = array(
            'action' => $patientChartNote_form['action'],
            'patientChart_id' => $patientChartNote_form['patientChart']
        );
        $form = $this->createForm(PatientChartNoteForm::class, $patientChartNote, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientChartNoteEntity')->validate($patientChartNote_form);

        if(!count($errors)) {

            switch($patientChartNote_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {
                        $em->persist($patientChartNote);
                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote('From chart no. ' . $patientChartNote->getPatientChart()->getPatientChartIdWithLink(). ' - ' . $patientChartNote->getNote());
                        $patientNote->setType(PatientNoteEntity::TYPE_CLINICAL);
                        $patientNote->setPatient($patientChartNote->getPatientChart()->getPatient());
                        $em->persist($patientNote);
                        $em->flush();
//
//                        $newAT = new AuditTrailEntity(
//                            'Patient Chart Note',
//                            $em->getClassMetadata(PatientChartNoteEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $patientNote;
//                        $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 = $patientChartNote;
                    $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 = $patientChartNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseInformation('Delete');
                    $em->persist($newAT);*/

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

    /*--------------------------------------------------------------------------------------------------------*/
    /*					UPDATE REPORT STATUS IS_DONE							    						  */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @Route(
     *      "/patient_chart_update_is_done/form/{action}/{patientChart_id}",
     *      defaults = {
     *          "action":  "n",
     *          "patientChart_id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_update_is_done"
     * )
     */
    public function patient_chart_update_is_done_formAction($action, $patientChart_id) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
//        if(!$authService->isUserHasAccesses(array('Admin Report Encounter Update Status', 'Admin Report Encounter Update Status'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->find($patientChart_id);
        if(!$patientChart) {
            $patientChart = new PatientChartEntity();
        }

        $patientChartNote = $em->getRepository('RxConnexionBundle:PatientChartNoteEntity')->findBy(array(
            'patientChart' => $patientChart_id
        ));

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

        $title = 'Update Status';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_chart_update_is_done_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'action' => $action,
            'patientNote' => $patientChartNote,
            'patientChart_id' => $patientChart_id,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }


    /**
     * @Route(
     *      "/patient_chart_update_is_done/save_action",
     *      name = "patient_chart_update_is_done_save"
     * )
     */
    public function patient_chart_update_is_done_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('Access Report', 'Admin Report'))) return $authService->redirectToHome();

        $patientChartUpdateIsDone_form = $request->get('patient_chart_update_is_done');
        $em = $this->getDoctrine()->getManager();
        $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->find($patientChartUpdateIsDone_form['id']);
        $patient = $patientChart->getPatient();
        if(!$patientChart) {
            $patientChart = new PatientChartEntity();
        }
        $formOptions = array(
            'action' => $patientChartUpdateIsDone_form['action'],
        );
        $form = $this->createForm(PatientChartUpdateIsDoneForm::class, $patientChart, $formOptions);

        $errors = $em->getRepository('RxConnexionBundle:PatientChartEntity')->validate_is_done_form($patientChartUpdateIsDone_form);

        if(!count($errors)) {

            switch($patientChartUpdateIsDone_form['action']) {
                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Patient Dashboard Encounter',
                        $em->getClassMetadata(PatientChartEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_NEW
                    );
                    $newAT->entity = $patientChart;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();
                        $internalStatus = $em->getRepository('RxConnexionBundle:InternalStatusEntity')->find($patientChartUpdateIsDone_form['internal_status']);
                        /*if($patientChartUpdateIsDone_form['ticketId'] != ''){
                            $ticketId = $patientChartUpdateIsDone_form['ticketId'];
                            $ticketUrl = $url = $this->generateUrl('ticket_form', array(
                                'action' => 'u',
                                'id' => base64_encode($ticketId)
                            ));
                            $endorsedNote = "<a href='$ticketUrl' target='_blank'>$ticketId</a>";
                        }*/
                        if($internalStatus->getDescription() == 'Endorsed'){
                            $ticketStatus = $em->getRepository('RxConnexionBundle:TicketStatusEntity')->find($patientChartUpdateIsDone_form['ticketStatus']);
                            $ticketSeverity = $em->getRepository('RxConnexionBundle:TicketSeverityEntity')->find($patientChartUpdateIsDone_form['ticketSeverity']);
                            $accountUser = $em->getRepository('RxConnexionBundle:AccountUserEntity')->find($patientChartUpdateIsDone_form['ticketUserAssignment']);
                            $ticket  = new TicketEntity();
                            $ticket->setTicketStatus($ticketStatus);
                            $ticket->setTicketSeverity($ticketSeverity);
                            $ticket->setAccountUser($accountUser);
                            $em->persist($ticket);
                            $em->flush();
                            $ticketNote = new TicketNoteEntity();
                            $ticketNote->setTicket($ticket);
                            $ticketNote->setNote($patientChartUpdateIsDone_form['note']);
                            $em->persist($ticketNote);
                            $ticketId = $ticket->getId();
                            $ticketUrl = $url = $this->generateUrl('ticket_form', array(
                                'action' => 'u',
                                'id' => base64_encode($ticketId)
                            ));
                            $endorsedNote = "<a href='$ticketUrl' target='_blank'>$ticketId</a>";
                            $patientChartNote = new PatientChartNoteEntity();
                            $patientChartNote->setNote('Endorsed : [ Ticket No. '. $endorsedNote . ' ] - ' . $patientChartUpdateIsDone_form['note']);
                            $patientChartNote->setPatientChart($patientChart);
                            $em->persist($patientChartNote);
                            $ticketPatientChart = new PatientChartTicketEntity();
                            $ticketPatientChart->setTicket($ticket);
                            $ticketPatientChart->setPatientChart($patientChart);
                            $em->persist($ticketPatientChart);
                            $ticketPatient = new PatientTicketEntity();
                            $ticketPatient->setTicket($ticket);
                            $ticketPatient->setPatient($patientChart->getPatient());
                            $em->persist($ticketPatient);
                            $patientNote = new PatientNoteEntity();
                            $patientNote->setNote('Endorsed : [ Ticket No. '. $endorsedNote . ' ] - ' . $patientChartUpdateIsDone_form['note']);
                            $patientNote->setType($patientChartUpdateIsDone_form['note_type']);
                            $patientNote->setPatient($patient);
                            $em->persist($patientNote);
                        }else{

                            if (isset($patientChartUpdateIsDone_form['chartType']) || $patientChartUpdateIsDone_form['chartType'] != null || $patientChartUpdateIsDone_form['chartType'] != '') {
                                $newPatientChart = new PatientChartEntity();
                                $newPatientChart->setPatient($patient);
                                $newPatientChart->setHealthFacility($patient->getActivePatientHealthFacility()->getHealthFacility());
                                $newPatientChart->setProvider($patientChart->getProvider());
                                $newPatientChart->setChartType($em->getReference('RxConnexionBundle:ChartTypeEntity', $patientChartUpdateIsDone_form['chartType']));
                                $newPatientChart->setChartStatus($em->getReference('RxConnexionBundle:ChartStatusEntity', $patientChartUpdateIsDone_form['chartStatus']));
                                $newPatientChart->setChartDate(date("Y-m-d"));
                                $em->persist($newPatientChart);
                            }


                            $patientChartNote = new PatientChartNoteEntity();
                            $patientChartNote->setNote($patientChartUpdateIsDone_form['note']);
                            $patientChartNote->setPatientChart($patientChart);
                            $em->persist($patientChartNote);

                            $patientNote = new PatientNoteEntity();
                            $patientNote->setNote($patientChartUpdateIsDone_form['note']);
                            $patientNote->setType($patientChartUpdateIsDone_form['note_type']);
                            $patientNote->setPatient($patient);
                            $em->persist($patientNote);
                        }
                        $em->flush();
                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                        $result['success'] = true;
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;
            }
        } else {

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



    //PATIENT ENCOUNTER DEVICES
    /**
     * @Route("/patient_chart_device_ajax_list", name="patient_chart_device_ajax_list")
     */
    public function patient_chart_device_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 Patient Chart Device Update'), false);

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

                $values = array(
                    $row['code'],
                    $row['item_description'],
                    $row['description'],
                    $row['startDate'],
                    $row['endDate'],
                    $row['quantity'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_chart_device/form/{patientChart_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_chart_device_form"
     * )
     */
    public function patient_chart_device_formAction($patientChart_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patientChart_id' => $patientChart_id
        );
        $form = $this->createForm(PatientChartDeviceForm::class, $patientChartNote, $formOptions);


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

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

    /**
     * @Route(
     *      "/patient_chart_device/save_action",
     *      name = "patient_chart_device_save"
     * )
     */
    public function patient_chart_device_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 Patient Chart Device New', 'Admin Patient Chart Device Update'))) return $authService->redirectToHome();

        $patientChartDevice_form = $request->get('patient_chart_device_form');
        $em = $this->getDoctrine()->getManager();
        $patientChartDevice = $em->getRepository('RxConnexionBundle:PatientChartDeviceEntity')->find($patientChartDevice_form['id']);
        if(!$patientChartDevice) {
            $patientChartDevice = new PatientChartDeviceEntity();
        }
        $formOptions = array(
            'action' => $patientChartDevice_form['action'],
            'patientChart_id' => $patientChartDevice_form['patientChart']
        );
        $form = $this->createForm(PatientChartDeviceForm::class, $patientChartDevice, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientChartNoteEntity')->validate($patientChartDevice_form);

        if(!count($errors)) {

            switch($patientChartDevice_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $em->persist($patientChartDevice);
                        $em->flush();
                        /*$newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $patientChartNote;
                        $newAT->setRefTable('provider');
                        $newAT->parseInformation('New');
                        $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 = $patientChartNote;
                    $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 = $patientChartNote;
                    $newAT->setRefTable('provider');
                    $newAT->parseInformation('Delete');
                    $em->persist($newAT);*/

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientChartDevice);
                        $patientChartDevice->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("/patient_red_flag_ajax_list", name="patient_red_flag_ajax_list")
     */
    public function patient_red_flag_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 Patient Red Flag Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Red Flag Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Red Flag' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$row['startDate'],
                    $row['endDate'],
                    $row['red_flag_note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

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

            $hasBilling = $authService->isUserHasAccesses(array('Admin Patient Billing Update'), false);
	        $hasReturn = $authService->isUserHasAccesses(array('Admin Patient Purchased Items Return'), false);

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

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

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

                if($hasBilling) {
                    $action .= "<a class='action-button-style href-patient-purchased-items-form' data-billing_id='$billing_id'>Invoice Details</a>";
                }

	            $status = $row['status'];
	            if ($row['is_trial'] == 1) {
		            $status .= $row['is_trial_returned'] == 1 ? ' - Returned' : '';
		            if ($hasReturn && $row['is_trial_returned'] != 1) {
			            $url = $this->generateUrl('patient_purchased_items_return', ['patientBillingInventory_id'=>$id]);
			            $action .= "<a class='action-button-style href-patient-purchased-items-return' data-url='$url'>Return Trial</a>";
		            }
	            }

                $values = array(
                    $row['item'],
                    $row['serial_no'],
                    $row['invoice_no'],
                    $row['billingDate'],
                    $status,
                    $action
                );

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

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

        return new JsonResponse($result);
    }
	/**
	 * @Route(
	 *      "/purchased-items/return",
	 *      name = "patient_purchased_items_return"
	 * )
	 */
	public function patient_purchased_items_return(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 Patient Purchased Items Return'))) return $authService->redirectToHome();

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

		/**@var PatientBillingInventoryEntity $patientBillingInventory*/
		if ($patientBillingInventory = $em->getRepository(PatientBillingInventoryEntity::class)->find(base64_decode($request->get('patientBillingInventory_id')))) {
			$patientBillingInventory->setIsTrialReturned(TRUE);
			/*if ($inventorySerialNo = $patientBillingInventory->getInventorySerialNos()->first()) {
				$inventorySerialNo->setStatus(InventorySerialNoEntity::STATUS_1);
				$inventorySerialNo->setPatientBillingInventory(null);
				$patientBillingInventory->removeInventorySerialNo($inventorySerialNo);
			}*/
			$inventoryService = new InventoryService($em, $this->container);
			$inventoryService->recordMovement('Patient Billing Inventory Removed', array(
				'patientBillingInventory' => $patientBillingInventory,
				'TRIAL_RETURN' => true,
			));
			$em->flush();

			$result['success'] = TRUE;
			$result['successMessages'][] = 'Trial item successfully returned';
		}


		return new JsonResponse($result);
	}

    /**
     * @Route(
     *      "/patient_red_flag/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_red_flag_form"
     * )
     */
    public function patient_red_flag_formAction($patient_id, $action, $id) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Red Flag New', 'Admin Patient Red Flag Update'))) return $authService->redirectToHome();

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientRedFlagForm::class, $patientRedFlag, $formOptions);

        $title = $action === 'n' ? 'New Red Flag' : 'Update Red Flag';

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

    /**
     * @Route(
     *      "/patient_red_flag/save_action",
     *      name = "patient_red_flag_save"
     * )
     */
    public function patient_red_flag_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 Patient Red Flag New', 'Admin Patient Red Flag Update'))) return $authService->redirectToHome();

        $patientRedFlag_form = $request->get('patientRedFlag');
        $em = $this->getDoctrine()->getManager();
        $patientRedFlag = $em->getRepository('RxConnexionBundle:PatientRedFlagEntity')->find($patientRedFlag_form['id']);
        if(!$patientRedFlag) {
            $patientRedFlag = new PatientRedFlagEntity();
        }
        $formOptions = array(
            'action' => $patientRedFlag_form['action'],
            'patient_id' => $patientRedFlag_form['patient']
        );
        $form = $this->createForm(PatientRedFlagForm::class, $patientRedFlag, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientRedFlagEntity')->validate($patientRedFlag_form);

        if(!count($errors)) {

            switch($patientRedFlag_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Patient Red Flag',
                            $em->getClassMetadata(PatientRedFlagEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientRedFlag;
                        $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(
                        'Patient Red Flag',
                        $em->getClassMetadata(PatientRedFlagEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientRedFlag;
                    $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(
                        'Patient Red Flag',
                        $em->getClassMetadata(PatientRedFlagEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientRedFlag;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

    //PATIENT REMINDER(S)
    /**
     * @Route("/patient_reminder_ajax_list", name="patient_reminder_ajax_list")
     */
    public function patient_reminder_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 Patient Reminder Update'), false);
            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Reminder Transfer'), false);

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

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Reminder' value='$id' class='patient-transfer-checkbox'>";
                }

                $values = array(
                    $transferLink.$row['reminderType_description'],
                    $row['assigned_to'],
                    $row['startDate'],
                    $row['endDate'],
                    $row['status'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_reminder/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_reminder_form"
     * )
     */
    public function patient_reminder_formAction($patient_id, $action, $id) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Reminder New', 'Admin Patient Reminder Update'))) return $authService->redirectToHome();

        $session = $this->get('session');
        $accountUser = $session->get('userData');

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

        $formOptions = array(
            'action' => $action,
            'account_user_id' => $accountUser['id'],
            'patient' => $patient_id
        );

//        var_dump($action);
//        die();
        $form = $this->createForm(PatientReminderForm::class, $patientReminder, $formOptions);

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

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

    /**
     * @Route(
     *      "/patient_reminder/save_action",
     *      name = "patient_reminder_save"
     * )
     */
    public function patient_reminder_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 Patient Reminder New', 'Admin Patient Reminder Update'))) return $authService->redirectToHome();

        $session = $this->get('session');
        $accountUser = $session->get('userData');

        $patientReminder_form = $request->get('patientReminder');
        $em = $this->getDoctrine()->getManager();
        $patientReminder = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->find($patientReminder_form['id']);
        if(!$patientReminder) {
            $patientReminder = new AccountUserReminderEntity();
        }
        $formOptions = array(
            'action' => $patientReminder_form['action'],
            'account_user_id' => $accountUser['id'],
            'patient' => $patientReminder_form['patient']
        );
        $form = $this->createForm(PatientReminderForm::class, $patientReminder, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:AccountUserReminderEntity')->patient_reminder_validate($patientReminder_form);

        if(!count($errors)) {

            switch($patientReminder_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

                        $patientReminderRef = new AccountUserReminderRefPatientEntity();
                        $patientReminderRef->setPatient($em->getReference('RxConnexionBundle:PatientEntity', $patientReminder_form['patient']));
                        $patientReminderRef->setAccountUserReminder($patientReminder);

                        $em->persist($patientReminderRef);
                        $em->persist($patientReminder);
                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Patient Reminder',
                            $em->getClassMetadata(AccountUserReminderEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientReminder;
                        $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(
                        'Patient Reminder',
                        $em->getClassMetadata(AccountUserReminderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientReminder;
                    $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(
                        'Patient Reminder',
                        $em->getClassMetadata(AccountUserReminderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientReminder;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientNote);
                        $patientReminder->setIsDeleted(true);

                        $em->flush();

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

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

                    } else {

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

                    break;
            }
        } else {

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


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

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

        $result = array(
            'query' => 'patients',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientEntity')->autocomplete_suggestions($q, $this->get('session')->get('userData'))
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/autocomplete_for_billing", name="patient_autocomplete_for_billing")
     */
    public function autocomplete_for_billingAction(Request $request) {

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

        $result = array(
            'query' => 'patients',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientEntity')->autocomplete_for_billing_suggestions($q, $this->get('session')->get('userData'))
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/autocomplete/account-user/reminder", name="patient_autocomplete_for_account_user_reminder")
     */
    public function autocomplete_for_account_user_reminderAction(Request $request) {

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

        $result = array(
            'query' => 'patients',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientEntity')->autocomplete_for_account_user_reminder($q, $this->get('session')->get('userData'))
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_referring_provider_autocomplete", name="patient_referring_provider_autocomplete")
     */
    public function patient_referring_provider_autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_referring_health_facility_autocomplete", name="patient_referring_health_facility_autocomplete")
     */
    public function patient_referring_health_facility_autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_insurance_autocomplete", name="patient_insurance_autocomplete")
     */
    public function patient_insurance_autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_encounter_billing_autocomplete", name="patient_encounter_billing_autocomplete")
     */
    public function patient_encounter_billing_autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

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

            $hasTransfer = $authService->isUserHasAccesses(array('Admin Patient Billing Transfer'), false);
            $hasUpdate = $authService->isUserHasAccesses(array('Admin Patient Billing Update'), false);
            $hasPreview = $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Preview'), false);
            $hasHl7 = $authService->isUserHasAccesses(array('Admin Patient Export HL7'), false);

	        $bypassInvoiceHiding = $this->getDoctrine()->getManager()->getRepository(SystemParameterEntity::class)->getValueByDesc('Show Invoice Print On Invoice With No Selected Serial No', SystemParameterEntity::TYPE_2) == 1;

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

	        $inventoryImplementation_date = new \DateTime('2021-03-28');

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

                $this->setBillingAmountsRefund($row['id']);

	            $billingDate = new \DateTime($row['billingDate']);

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

                if($hasUpdate) {
                    $action = "<a class='action-button-style href-patient-billing-form' data-action='u' data-id='$id'>Details</a>";
                }
                if($hasPreview /*&& (($row['withSerialNoCount'] >= $row['itemisedCount']) || $bypassInvoiceHiding)*/) {

                	if(!$bypassInvoiceHiding && $billingDate >= $inventoryImplementation_date &&
		                (
			                ($row['itemisedCount'] > 0 && ($row['itemisedCount'] > $row['withSerialNoCount'])) ||
			                ($row['pbi_itemisedCount'] > 0 && ($row['pbi_itemisedCount'] > $row['pbi_itemisedWithSerialCount'])) ||
			                ($row['pbi_nonInventoryCount'] > 0 && (is_null($row['pbi_nonInventoryCount_pbiCtr']) || $row['pbi_nonInventoryCount_pbiCtr'] <= 0))
		                )
	                ) {
		                $action .= "<button type='button' style='background: #dcdcdc; color: #c1bcbc!important;' onclick='global.flashMessage(\"warning\", [\"Please select the correct item(s) and/or serial no(s) to be deducted on the inventory.\"])' class='action-button-style'>Invoice Preview</button>";
	                } else {
		                $url = $this->generateUrl('patient_billing_invoice_preview', array('id' => $id));
		                $action .= "<a href='$url' target='_blank' class='action-button-style'>Invoice Preview</a>";
	                }

                }
                if($hasHl7) {
                    $urlHl7 = $this->generateUrl('patient_export_hl7', array('patient_id' => $patientId, 'type' => 'DFT-P03', 'tx_id'=>$row['id']));
                    $action .= "<a href='$urlHl7' title='Export to HL7 Format' class='action-button-style'><i class='fa fa-file-code-o'></i></a>";
                }

                $transferLink = '';
                if($hasTransfer) {
                    $transferLink = "<input type='checkbox' style='margin:10px;' data-id='$id'  data-type='Billing' value='$id' class='patient-transfer-checkbox'>";
                }

                $healthFacility = null;
                $date = date_create("2020-10-03");
                if($row['healthFacility'] == 'Freedom Hazeldean' && date_format(date_create($row['created_at']), 'Y-m-d') < date_format($date,'Y-m-d')) {
                    $healthFacility = 'Freedom Eastwood';
                } else if($row['healthFacility'] == 'Freedom Eastwood' && date_format(date_create($row['created_at']), 'Y-m-d')  <  date_format($date,'Y-m-d')) {
                    $healthFacility = 'Freedom Hazeldean';
                } else {
                    $healthFacility = $row['healthFacility'];
                }
	            /*$action .= $row['itemisedCount'];
	            $action .= '-';
	            $action .= $row['withSerialNoCount'];
	            $action .= '-';
	            $action .= $row['pbi_itemisedCount'];
	            $action .= '-';
	            $action .= $row['pbi_itemisedWithSerialCount'];*/

	            $values = array(
                    $transferLink.$row['billingDate'],
                    $row['invoiceNo'],
                    $row['status'],
                    $row['billingBranch'],
                    $healthFacility,
                    $row['payer'],
                    number_format($row['amountDue'], 2),
                    number_format($row['amountPaid'], 2),
                    number_format($row['amountRefunded'], 2),
                    intval($row['amountBal']) < 0 ? number_format(0, 2) : number_format($row['amountBal'], 2),
                    $action
                );


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

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


        }

        return new JsonResponse($result);
    }

    public function setBillingAmountsRefund($id) {
        $em = $this->getDoctrine()->getManager();
        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($id);
        $patientBilling->setAmtPaidAmtBalanceRefund();
        $em->flush();
    }

    /**
     * @Route(
     *      "/patient_billing/form",
     *      name = "patient_billing_form"
     * )
     */
    public function patient_billing_formAction(Request $request) {

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

        $patient_id = $request->query->get('patient_id');
        $action = $request->query->get('action');
        $id = $request->query->get('id');

        $em = $this->getDoctrine()->getManager();
        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find(base64_decode($id));
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));
        $defaultHealthFacility_id = '';
        $defaultHealthFacility = '';
        if($action == 'n' && $patient->getActivePatientHealthFacility()){
            $defaultHealthFacility_id = $patient->getActivePatientHealthFacility()->getHealthFacility()->getId();
            $defaultHealthFacility = $patient->getActivePatientHealthFacility()->getHealthFacility()->getDescription();
        }

        if(!$patientBilling) {
            $patientBilling = new PatientBillingEntity();
        } else {
            $defaultHealthFacility_id = $patientBilling->getHealthFacility() ? $patientBilling->getHealthFacility()->getId() : '';
            $defaultHealthFacility = $patientBilling->getHealthFacility() ? $patientBilling->getHealthFacility()->getDescription() : '';
            $patientBilling->setAmountsValue();
            $em->flush();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id,
            'defaultHealthFacility_id' => $defaultHealthFacility_id,
            'defaultHealthFacility' => $defaultHealthFacility
        );
        $form = $this->createForm(PatientBillingForm::class, $patientBilling, $formOptions);

        $title = $action === 'n' ? 'New Billing' : date_format($patientBilling->getBillingDate(), 'ym') . '-' . sprintf('%006d', $patientBilling->getId()) . "(" . $patientBilling->getBillingStatus() . ")";

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_billing_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'patientBilling' => $patientBilling,
            'paymentDays' => $this->generateDaysArray(),
        ));
        $result['success'] = true;

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_billing/download/{patientFile_id}",
     *
     *      name = "patient_billing_download"
     * )
     */
    public function patient_billing_downloadAction($patientFile_id){

        $em = $this->getDoctrine()->getManager();
        $patientFile = $em->getRepository('RxConnexionBundle:PatientFileEntity')->find(base64_decode($patientFile_id));
        header('Content-Disposition: attachment; filename="' . $patientFile->getDescription() . '"');
        if($patientFile->getFileType()){
            if ($patientFile->getFileType()->getDescription() == 'Insurance Accessory Package' ||
                $patientFile->getFileType()->getDescription() == 'Insurance CPAP Package' ||
                $patientFile->getFileType()->getDescription() == 'Insurance Cross Claim Package' ||
                $patientFile->getFileType()->getDescription() == 'Insurance Package (Medical Supplies)'){
                $fileName = $patientFile->getParsedDescription();
                $uploadDir = $patientFile->getUploadRootDir() ;
            }else{
                $fileName = $patientFile->getParsedDescription();
                $uploadDir = $patientFile->getUploadRootDir() ;
            }
        } else {
            $fileName = $patientFile->getParsedDescription();
            $uploadDir = $patientFile->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();
    }

    private function generateDaysArray() {
        $arr = array();
        for($i=1; $i<=31; $i++) $arr[$this->ordinal($i)] = $i;
        return $arr;
    }

    private function ordinal($number) {
        $ends = array('th','st','nd','rd','th','th','th','th','th','th');
        return ((($number % 100) >= 11) && (($number%100) <= 13)) ? $number. 'th' : $number. $ends[$number % 10];
    }

    /**
     * @Route(
     *      "/patient_billing/save_action",
     *      name = "patient_billing_save"
     * )
     */
    public function patient_billing_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 Patient Billing New', 'Admin Patient Billing Update'))) return $authService->redirectToHome();

        $patientBilling_form = $request->get('patientBilling');
        $em = $this->getDoctrine()->getManager();
        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($patientBilling_form['id']);
        if(!$patientBilling) {
            $patientBilling = new PatientBillingEntity();
        }
        $formOptions = array(
            'action' => $patientBilling_form['action'],
            'patient_id' => $patientBilling_form['patient']
        );
        $form = $this->createForm(PatientBillingForm::class, $patientBilling, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->validate($patientBilling_form);
        $oldPatientId = $patientBilling_form['patient'];

	    $result['action'] = $patientBilling_form['action'];

	    if(!count($errors)) {

            switch($patientBilling_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);
                    //$form->submit($patientBilling_form, false);

                    if($form->isValid()) {

                        //$healthFacilityForAddress = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($patientBilling_form['healthFacilityForAddress']);
                        //$nextInvoiceNo = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->nextInvoiceNo($healthFacilityForAddress);
                        //$patientBilling->setInvoiceNo($nextInvoiceNo);

                        /*$conn = $this->getDoctrine()->getConnection();
                        $query = $conn->executeQuery("
                            SET @invNoCompany = (
                                SELECT c.`last_or_number` * 1 as last_or_number
                                FROM `company` c
                                WHERE c.`id` = :healthFacilityForAddress_company_id
                                LIMIT 1
                            );
                            SET @invNoBilling = (
                                SELECT pb.`invoice_no` * 1 as invoice_no
                                FROM `patient_billing` pb
                                LEFT JOIN `health_facility` hf on pb.`health_facility_for_address_id` = hf.`id`
                                LEFT JOIN `health_facility` hf on pb.`health_facility_for_address_id` = hf.`id`
                                WHERE hf.`company_id` = :healthFacilityForAddress_company_id
                                ORDER BY invoice_no DESC
                                LIMIT 1
                            );
                        ", array('healthFacilityForAddress_company_id' => $healthFacilityForAddress->getCompany()->getId()));
                        $query = $conn->executeQuery("SELECT @invNoCompany as company, @invNoBilling as billing;");
                        die(var_dump($query->fetch(0)));*/

                        $patientBilling_id = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->nativeInsert($patientBilling_form);
                        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($patientBilling_id);

                        $patientBilling->setInvoiceAmountDue($patientBilling->getAmountDue());

                        //$em->persist($patientBilling);
                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientBilling_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientBilling->getPatient());
                        $em->persist($patientNote);
                        $em->flush();

                        foreach($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setAmountBalance($patientBillingBreakdown->getAmount());
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                            }
                            $patientBillingBreakdown->setAmountValue();
                        }
                        $patientBilling->setInvoiceAmountBalance($patientBilling->getAmountBalance());
                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {
                            $patientFile = new PatientFileEntity();
                            $baseName = $patientBilling->getId() . '-' . time() . '.' . pathinfo($_FILES['form']['name']['file'], PATHINFO_EXTENSION);
                            $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;
                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $patientFile->setPatient($patientBilling->getPatient());
                                $patientFile->setFileType($em->getReference('RxConnexionBundle:FileTypeEntity', $_POST['form']['file_type_id']));
                                $patientFile->removeFile();
                                $patientFile->setDescription($_FILES['form']['name']['file']);
                                $patientFile->setParsedDescription($baseName);
                                $patientBilling->setPatientFile($patientFile);
                                $em->persist($patientFile);
                                $em->flush();
                            }
                        }

                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
	                    $nonInventoryCtr = 0;
                        foreach ($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown) {
	                        $nonInventoryCtr += intval($patientBillingBreakdown->getItem()->getIsNonInventory() && $patientBillingBreakdown->getItemType() != 'Part of CPAP Package');
                            $patientBillingInventory = new PatientBillingInventoryEntity();
                            $patientBillingInventory->setPatientBilling($patientBilling);
                            $patientBillingInventory->setItem($patientBillingBreakdown->getItem());
                            $patientBillingInventory->setQuantity($patientBillingBreakdown->getQuantity());
                            $patientBillingInventory->setInventory($patientBillingBreakdown->getItem()->getFirstInventoryByBranchIdAndStatus($patientBilling->getHealthFacility()->getId(), InventoryEntity::STATUS_STOCK_ON_HAND, true));
	                        $patientBillingInventory->setSoldValue($patientBillingBreakdown->getAmount());
	                        $patientBillingInventory->setIsTrial(false);
                            $em->persist($patientBillingInventory);
                            $patientBilling->addPatientBillingInventory($patientBillingInventory);
                        }

                        /*$inventoryService = $this->get('rx_connexion.inventoryService');
                        $inventoryService->recordMovement('Patient Billing - Invoice', array(
                            'patientBilling' => $patientBilling,
                            'action' => $patientBilling_form['action'],
                        ));*/

                        $newAT = new AuditTrailEntity(
                            'Patient Billing',
                            $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientBilling;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

                        $result['success'] = true;
                        $result['patient_billing_id'] = $patientBilling->getIdEncoded();
                        $result['successMessages'][] = 'Record Successfully Saved.';
	                    if ($nonInventoryCtr > 0) {
		                    $result['successMessages'][] = 'You have selected ' . $nonInventoryCtr . ' non-inventory item. Please select it\'s corresponding item/s.';
	                    } else {
		                    $result['successMessages'][] = 'Please select the correct item/s to be deducted on the inventory and hit save again.';
	                    }

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

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Patient Billing',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientBilling;
                    $newAT->parseOriginalDetails();

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

                        if($oldPatientId != $patientBilling_form['patient']){
                            if($patientBilling->getPatientPayments()->count()){
                                foreach ($patientBilling->getPatientPayments() as $patientPayment){
                                    $patientPayment->setPatient($em->getReference('RxConnexionBundle:PatientEntity',$patientBilling_form['patient']));
                                    $em->flush();
                                }
                            }
                        }
                        if($patientBilling->getIsPaymentPlan()){
                            $patientBillingFinancingPaymentDetail_form = $request->get('patientBillingFinancingPaymentDetail');

                            $patientBillingFinancingPaymentDetail = $patientBilling->getPatientBillingFinancingPaymentDetail();
                            $patientBillingFinancingPaymentDetail->setStartDate($patientBillingFinancingPaymentDetail_form['start_date']);
                            $patientBillingFinancingPaymentDetail->setEndDate($patientBillingFinancingPaymentDetail_form['end_date']);
                            $patientBillingFinancingPaymentDetail->setPaymentDay($patientBillingFinancingPaymentDetail_form['payment_day']);
                        }

                        foreach($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setAmountValue();
                        }

                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {
                            $patientFile = new PatientFileEntity();
                            $baseName = $patientBilling->getId() . '-' . time() . '.' . pathinfo($_FILES['form']['name']['file'], PATHINFO_EXTENSION);
                            $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;
                            if (move_uploaded_file($_FILES['form']['tmp_name']['file'], $uploadFile)) {
                                $patientFile->setPatient($patientBilling->getPatient());
                                $patientFile->setFileType($em->getReference('RxConnexionBundle:FileTypeEntity', $_POST['form']['file_type_id']));
                                $patientFile->removeFile();
                                $patientFile->setDescription($_FILES['form']['name']['file']);
                                $patientFile->setParsedDescription($baseName);
                                $patientBilling->setPatientFile($patientFile);
                                $em->persist($patientFile);
                                $em->flush();
                            }
                        }

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

                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientBilling_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientBilling->getPatient());
                        $em->persist($patientNote);
                        $em->flush();



                        $patient_billing_inventories = $request->get('patient_billing_inventories');
                        $inventoryService = $this->get('rx_connexion.inventoryService');
                        if($patient_billing_inventories) {

                            // CHECK FOR REMOVED ITEM
                            $pbi_ids = array_column($patient_billing_inventories, 'id');
                            foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
                                if (!in_array($patientBillingInventory->getId(), $pbi_ids)) {
                                    $patientBilling = $inventoryService->recordMovement('Patient Billing Inventory Removed', array(
                                        'patientBillingInventory' => $patientBillingInventory,
                                    ));
                                }
                            }


                            // CHECK FOR REMOVED INVENTORY SERIAL NO
                            /**@var PatientBillingInventoryEntity $patientBillingInventory */
                            /**@var InventorySerialNoEntity $inventorySerialNo */
                            foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
                                foreach ($patient_billing_inventories as $patient_billing_inventory) {
                                	if(isset($patient_billing_inventory['inventory_serial_no'])){
		                                if($patientBillingInventory->getId() == $patient_billing_inventory['id']) {
			                                $isn_ids = $patient_billing_inventory['inventory_serial_no'];
			                                foreach ($patientBillingInventory->getInventorySerialNos() as $inventorySerialNo) {
				                                if (!in_array($inventorySerialNo->getId(), $isn_ids)) {
					                                /*$inventoryService->recordMovement('Patient Billing Inventory Serial No Removed', array(
						                                'inventorySerialNo' => $inventorySerialNo,
					                                ));*/
					                                $inventorySerialNo->setStatus(InventorySerialNoEntity::STATUS_1);
					                                $inventorySerialNo->setPatientBillingInventory(null);
					                                $patientBillingInventory->removeInventorySerialNo($inventorySerialNo);
				                                }
			                                }
			                                break;
		                                }
	                                } else {
		                                foreach ($patientBillingInventory->getInventorySerialNos() as $inventorySerialNo) {
			                                /*$inventoryService->recordMovement('Patient Billing Inventory Serial No Removed', array(
				                                'inventorySerialNo' => $inventorySerialNo,
			                                ));*/
			                                $inventorySerialNo->setStatus(InventorySerialNoEntity::STATUS_1);
			                                $inventorySerialNo->setPatientBillingInventory(null);
			                                $patientBillingInventory->removeInventorySerialNo($inventorySerialNo);
		                                }
	                                }
                                }
                            }


                            foreach ($patient_billing_inventories as $patient_billing_inventory) {

	                            if($item = $em->getRepository(ItemEntity::class)->find($patient_billing_inventory['item'])){
		                            if(isset($patient_billing_inventory['id']) && !empty($patient_billing_inventory['id'])) {
			                            $patientBillingInventory = $patientBilling->getPatientBillingInventoryById($patient_billing_inventory['id']);
		                            } else {
			                            $parentPBI = $patientBilling->getPatientBillingInventoryById($patient_billing_inventory['patient_billing_inventory']);
			                            $patientBillingInventory = new PatientBillingInventoryEntity();
			                            $patientBillingInventory->setPatientBilling($patientBilling);
			                            $patientBillingInventory->setPatientBillingInventory($parentPBI);
			                            $em->persist($patientBillingInventory);
			                            $patientBilling->addPatientBillingInventory($patientBillingInventory);
			                            if($parentPBI) {
				                            $parentPBI->addPatientBillingInventory($patientBillingInventory);
			                            }
		                            }
		                            $patientBillingInventory->setItem($item);
		                            $patientBillingInventory->setIsTrial(isset($patient_billing_inventory['is_trial']));
		                            $item->addPatientBillingInventory($patientBillingInventory);

		                            if($item->getIsItemised()) {
			                            if(isset($patient_billing_inventory['inventory_serial_no'])) {
				                            foreach ($patient_billing_inventory['inventory_serial_no'] as $isn) {
					                            /**@var InventorySerialNoEntity $inventorySerialNo*/
					                            $inventorySerialNo = $em->getRepository(InventorySerialNoEntity::class)->find($isn);
					                            if($inventorySerialNo) {
						                            $patientBillingInventory->setInventory($inventorySerialNo->getInventory());
						                            $inventorySerialNo->setPatientBillingInventory($patientBillingInventory);
						                            $patientBillingInventory->addInventorySerialNo($inventorySerialNo);
						                            $patientBillingInventory->setSerialNo($inventorySerialNo->getSerialNo());
					                            }
				                            }
			                            }
		                            } else {
			                            if(isset($patient_billing_inventory['serial_no'])) {
				                            $serial_no = array_filter($patient_billing_inventory['serial_no']);
				                            $qty = count($serial_no);
				                            $patientBillingInventory->setSerialNo(json_encode($serial_no));
				                            $patientBillingInventory->setQuantity($qty);
			                            }
		                            }
		                            $patientBillingInventory->setQuantity(intval($patient_billing_inventory['quantity']));
	                            }



                            }
                        } else {
                            foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
                                $patientBilling = $inventoryService->recordMovement('Patient Billing Inventory Removed', array(
                                    'patientBillingInventory' => $patientBillingInventory,
                                ));
                            }
                        }

	                    foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
		                    if($patientBillingBreakdownEquivalent = $patientBilling->getPatientBillingBreakdownByItemId($patientBillingInventory->getItem()->getId())) {
			                    $patientBillingInventory->setSoldValue($patientBillingBreakdownEquivalent->getAmount());
		                    } elseif($patientBillingInventory->getPatientBillingInventory()) {
			                    $x = ($patientBillingInventory->getQuantity() * $patientBillingInventory->getItem()->getAveCostByHealthFacility($patientBilling->getHealthFacility()));
			                    $y = 0;
			                    $z = $patientBillingInventory->getPatientBillingInventory()->getSoldValue();
			                    foreach ($patientBillingInventory->getPatientBillingInventory()->getPatientBillingInventories() as $pbi) {
				                    $y += ($pbi->getQuantity() * $pbi->getItem()->getAveCostByHealthFacility($patientBilling->getHealthFacility()));
			                    }
			                    $patientBillingInventory->setSoldValue($y > 0 ? ($x / $y * $z) : $x);
		                    }
                        }
                        $inventoryService->recordMovement('Patient Billing - Invoice', array(
                            'patientBilling' => $patientBilling,
                            'action' => $patientBilling_form['action'],
                        ));

                        $result['success'] = true;
                        $result['patient_billing_id'] = $patientBilling->getIdEncoded();
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                        /**@var FormError $error*/
                        foreach ($form->getErrors(true, true) as $error) {
                            $result['errorMessages'][] = $error->getMessage();
                        }
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Patient Billing',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientBilling;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientBilling);
                        $patientBilling->setIsDeleted(true);
                        $em->flush();

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

                    } else {

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

                    break;

                case 'v' :

                    $newAT = new AuditTrailEntity(
                        'Patient Billing',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientBilling;
                    $newAT->parseOriginalDetails();

                    if(!count($patientBilling->getPatientPaymentsNotVoid())){
                        $patientBilling->setBillingStatus(PatientBillingEntity::BILLING_STATUS_VOID);
                        foreach($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus('v');
                            }
                        }
                        $inventoryService = $this->get('rx_connexion.inventoryService');
                        foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
                            $inventoryService->recordMovement('Patient Billing Inventory Removed', array(
                                'patientBillingInventory' => $patientBillingInventory,
                            ));
                        }
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

                        $result['success'] = true;
                        $result['successMessages'][] = 'Billing transaction successfully voided.';
                    }else{
                        $result['success'] = false;
                        $result['errorMessages'][] = 'Invoice already has payment(s).';
                    }

                    break;

                case 'ret' :

                    $newAT = new AuditTrailEntity(
                        'Patient Billing',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientBilling;
                    $newAT->parseOriginalDetails();

                    $patientBilling->setBillingStatus(PatientBillingEntity::BILLING_STATUS_RETURNED);
                    if(!$patientBilling->getPatientPayments()->count()){
                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
                        foreach($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus('ret');
                            }
                        }
	                    /*$inventoryService = $this->get('rx_connexion.inventoryService');
	                    foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
		                    $inventoryService->recordMovement('Patient Billing Inventory Removed', array(
			                    'patientBillingInventory' => $patientBillingInventory,
		                    ));
	                    }*/
                        $newAT->parseDetails();
                        $em->persist($newAT);

                        $result['success'] = true;
                    }else{
                        foreach ($patientBilling->getPatientPayments() as $patientPayment){
                            $patientPayment->setPaymentStatus('Returned');
                        }
                        $result['success'] = true;
                    }
	                $inventoryService = $this->get('rx_connexion.inventoryService');
	                foreach ($patientBilling->getPatientBillingInventories() as $patientBillingInventory) {
		                $inventoryService->recordMovement('Patient Billing Inventory Removed', array(
			                'patientBillingInventory' => $patientBillingInventory,
		                ));
	                }
                    $result['successMessages'][] = 'Billing transaction successfully returned.';
                    $em->flush();

                    break;

                case 'ref' :

                    $newAT = new AuditTrailEntity(
                        'Patient Billing',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientBilling;
                    $newAT->parseOriginalDetails();

                    $patientBilling->setBillingStatus(PatientBillingEntity::BILLING_STATUS_REFUND);
                    if(!$patientBilling->getPatientPayments()->count()){
                        foreach($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus('ref');
                            }
                        }

                        $result['success'] = true;
                    }else{
                        foreach ($patientBilling->getPatientPayments() as $patientPayment){
                            $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_REFUNDED);
                        }
                        $result['success'] = true;
                    }
                    $newAT->parseDetails();
                    $em->persist($newAT);
                    $em->flush();
                    $result['successMessages'][] = 'Billing transaction successfully refunded.';

                    break;

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

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

        return new JsonResponse($result);
    }

    //Patient Rental
    /**
     * @Route("/patient_rental_ajax_list", name="patient_rental_ajax_list")
     */
    public function patient_rental_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 Patient Rental Update'), false);
            $hasHl7 = $authService->isUserHasAccesses(array('Admin Patient Export HL7'), false);

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

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

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

                if($hasUpdate) {
                    $action = "<a class='action-button-style href-patient-rental-form' data-action='u' data-id='$id'>Details</a>";
                }
                if($hasHl7) {
                    $urlHl7 = $this->generateUrl('patient_export_hl7', array('patient_id' => $patientId, 'type' => 'DFT-P03', 'tx_id'=>$row['id']));
                    $action .= "<a href='$urlHl7' title='Export to HL7 Format' class='action-button-style'><i class='fa fa-file-code-o'></i></a>";
                }

                ;

                $values = array(
//                    $row['invoiceNo'],
                    $row['startDate'],
                    $row['endDate'],
                    $row['healthFacility'],
                    $row['payer'],
                    $this->ordinal($row['paymentDay']),
                    number_format($row['amortization_amount'], 2),
                    number_format($row['amountDue'], 2),
                    number_format($row['amountBal'], 2),
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_rental/form",
     *      name = "patient_rental_form"
     * )
     */
    public function patient_rental_formAction(Request $request) {

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

        $patient_id = $request->query->get('patient_id');
        $action = $request->query->get('action');
        $id = $request->query->get('id');

        $em = $this->getDoctrine()->getManager();
        $patientRental = $em->getRepository('RxConnexionBundle:PatientRentalEntity')->find(base64_decode($id));
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));
        $defaultHealthFacility_id = '';
        $defaultHealthFacility = '';
        if($action == 'n' && $patient->getActivePatientHealthFacility()){
            $defaultHealthFacility_id = $patient->getActivePatientHealthFacility()->getHealthFacility()->getId();
            $defaultHealthFacility = $patient->getActivePatientHealthFacility()->getHealthFacility()->getDescription();
        }

        if(!$patientRental) {
            $patientRental = new PatientRentalEntity();
        } else {
            $defaultHealthFacility_id = $patientRental->getHealthFacility() ? $patientRental->getHealthFacility()->getId() : '';
            $defaultHealthFacility = $patientRental->getHealthFacility() ? $patientRental->getHealthFacility()->getDescription() : '';
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id,
            'defaultHealthFacility_id' => $defaultHealthFacility_id,
            'defaultHealthFacility' => $defaultHealthFacility
        );
        $form = $this->createForm(PatientRentalForm::class, $patientRental, $formOptions);

        $title = $action === 'n' ? 'New Rental' : date_format($patientRental->getStartDate(), 'ym') . '-' . sprintf('%006d', $patientRental->getId()) . "";

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_rental_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'patientRental' => $patientRental,
            'paymentDays' => $this->generateDaysArray(),
        ));
        $result['success'] = true;

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_rental/save_action",
     *      name = "patient_rental_save"
     * )
     */
    public function patient_rental_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 Patient Rental New', 'Admin Patient Rental Update'))) return $authService->redirectToHome();

        $patientRental_form = $request->get('patientRental');
        $em = $this->getDoctrine()->getManager();
        $patientRental = $em->getRepository('RxConnexionBundle:PatientRentalEntity')->find($patientRental_form['id']);
        if(!$patientRental) {
            $patientRental = new PatientRentalEntity();
        }
        $formOptions = array(
            'action' => $patientRental_form['action'],
            'patient_id' => $patientRental_form['patient']
        );
        $form = $this->createForm(PatientRentalForm::class, $patientRental, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientRentalEntity')->validate($patientRental_form);
        $oldPatientId = $patientRental_form['patient'];

        if(!count($errors)) {

            switch($patientRental_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);
                    //$form->submit($patientBilling_form, false);

                    if($form->isValid()) {

                        //$healthFacilityForAddress = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($patientBilling_form['healthFacilityForAddress']);
                        //$nextInvoiceNo = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->nextInvoiceNo($healthFacilityForAddress);
                        //$patientBilling->setInvoiceNo($nextInvoiceNo);

                        /*$conn = $this->getDoctrine()->getConnection();
                        $query = $conn->executeQuery("
                            SET @invNoCompany = (
                                SELECT c.`last_or_number` * 1 as last_or_number
                                FROM `company` c
                                WHERE c.`id` = :healthFacilityForAddress_company_id
                                LIMIT 1
                            );
                            SET @invNoBilling = (
                                SELECT pb.`invoice_no` * 1 as invoice_no
                                FROM `patient_billing` pb
                                LEFT JOIN `health_facility` hf on pb.`health_facility_for_address_id` = hf.`id`
                                WHERE hf.`company_id` = :healthFacilityForAddress_company_id
                                ORDER BY invoice_no DESC
                                LIMIT 1
                            );
                        ", array('healthFacilityForAddress_company_id' => $healthFacilityForAddress->getCompany()->getId()));
                        $query = $conn->executeQuery("SELECT @invNoCompany as company, @invNoBilling as billing;");
                        die(var_dump($query->fetch(0)));*/

                        $patientRental_id = $em->getRepository('RxConnexionBundle:PatientRentalEntity')->nativeInsert($patientRental_form);
                        $patientRental = $em->getRepository('RxConnexionBundle:PatientRentalEntity')->find($patientRental_id);

                        //$em->persist($patientBilling);
                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientRental_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientRental->getPatient());
                        $em->persist($patientNote);
                        $em->flush();

                        foreach($patientRental->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                            }
                        }

                        $newAT = new AuditTrailEntity(
                            'Patient Rental',
                            $em->getClassMetadata(PatientRentalEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientRental;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

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

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Patient Rental',
                        $em->getClassMetadata(PatientRentalEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientRental;
                    $newAT->parseOriginalDetails();

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

                        if($oldPatientId != $patientRental_form['patient']){
                            if($patientRental->getPatientPayments()->count()){
                                foreach ($patientRental->getPatientPayments() as $patientPayment){
                                    $patientPayment->setPatient($em->getReference('RxConnexionBundle:PatientEntity',$patientRental_form['patient']));
                                    $em->flush();
                                }
                            }
                        }

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

                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientRental_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientRental->getPatient());
                        $em->persist($patientNote);

                        $em->flush();

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Patient Rental',
                        $em->getClassMetadata(PatientRentalEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientRental;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientBilling);
                        $patientRental->setIsDeleted(true);
                        $em->flush();

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

                    } else {

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

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_billing/item_return/save_action/{patient_billing_breakdown_id}",
     *      name = "patient_billing_item_return_save"
     * )
     */
    public function patient_billing_item_refund_saveAction(Request $request, $patient_billing_breakdown_id) {

        $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 Patient Billing Return', 'Admin Patient Billing Return'))) return $authService->redirectToHome();

        $patientBilling_form = $request->get('patientBilling');
        $em = $this->getDoctrine()->getManager();
        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($patientBilling_form['id']);
        $patientBillingBreakdown = $em->getRepository('RxConnexionBundle:PatientBillingBreakdownEntity')->find($patient_billing_breakdown_id);

        $formOptions = array(
            'action' => $patientBilling_form['action'],
            'patient_id' => $patientBilling_form['patient']
        );


        $errors = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->validate_return($patientBilling_form);
        if(!count($errors)) {

            switch($patientBilling_form['action']) {

                case 'ret': // new
                    $newAT = new AuditTrailEntity(
                        'Patient Billing Return Item',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );

                    if($patientBilling) {
                        $newAT->entity = $patientBilling;
                        $newAT->parseOriginalDetails();

                        $patientBillingBreakdown->setStatus(PatientBillingBreakdownEntity::STATUS_RETURN);
                        $patientBilling->updateBillingIfReturned($patientBillingBreakdown->getId());
//                        $patientBilling->setAmountDue($patientBilling->getAmountDue() - $patientBillingBreakdown->getAmount());
//                        $patientBilling->setAmountBalance($patientBilling->getAmountBalance() - $patientBillingBreakdown->getAmount());



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

                        $result['success'] = true;
                        $result['successMessages'][] = 'You successfully return an item.';

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

                    break;



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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_billing/void_action",
     *      name = "patient_billing_void"
     * )
     */
    /*public function patient_billing_voidAction(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 Patient Billing New', 'Admin Patient Billing Update'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $patientBilling_form = $request->get('patientBilling');
        $id = $patientBilling_form['id'];
        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($id);

        switch($patientBilling_form['action']) {
            case 'u': // update
                if(!$patientBilling->getPatientPayments()->count()){
                    $patientBilling->setBillingStatus(PatientBillingEntity::BILLING_STATUS_VOID);

                    //foreach ($patientBilling->getPatientPayments() as $patientPayment){
                      //  $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_VOID);
                       // $em->flush();
                    //}

                    $newAT = new AuditTrailEntity(
                        'Patient Billing',
                        $em->getClassMetadata(PatientBillingEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientBilling;
                    $newAT->parseOriginalDetails();
                    $newAT->parseDetails();
                    $em->persist($newAT);
                    $em->flush();

                    $result['success'] = true;
                    $result['successMessages'][] = 'Billing transaction successfully voided.';
                }else{
                    $result['success'] = false;
                    $result['errorMessages'][] = 'Invoice already has payment(s).';
                }

        }

        return new JsonResponse($result);
    }*/

    /**
     * @Route(
     *      "/patient_billing/invoice/preview",
     *      name = "patient_billing_invoice_preview"
     * )
     */
    public function patient_billing_invoice_previewAction(Request $request) {

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

        $id = $request->query->get('id');
        $patientBilling = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientBillingEntity')->find(base64_decode($id));
        $patientBilling->setAmountsValue();
        $this->getDoctrine()->getManager()->flush();
        $return = $this->render('@RxConnexion/Patient/patient_billing_invoice.wkhtml.twig', array(
            'patientBilling' => $patientBilling,
            'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
        ));
        if($patientBilling->getHealthFacilityForAddress()){
            switch ($patientBilling->getHealthFacilityForAddress()->getCompany()->getDescription()) {
                case 'Dyna Sleep Sales':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_dss.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'AMS Edmonton':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_ams.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Metro Medical Supplies':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_mms.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Finance Underwriting & Investment Capital':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_fuic.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Modern Medical Supplies':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_modern.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'One Life Medical Supplies Inc':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_onelife.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Alberta CPAP Sales':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_acs.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Calgary CPAP Sales':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_ccs.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Stampede Medical Supplies':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_scs.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Freedom Respiratory & Sleep Centre':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_frsi.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Perfect Sleep Solutions WC Inc.':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_pss.wkhtml.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                default:
            }
        }
        return $return;
    }

    /**
     * @Route(
     *      "/patient_billing/invoice/print",
     *      name = "patient_billing_invoice_print"
     * )
     */
    public function patient_billing_invoice_printAction(Request $request) {

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

        $id = $request->query->get('id');
        $patientBilling = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientBillingEntity')->find(base64_decode($id));

        $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice.wkpdf.twig', array(
            'patientBilling' => $patientBilling
        ));
        if($patientBilling->getHealthFacilityForAddress()) {
            switch ($patientBilling->getHealthFacilityForAddress()->getCompany()->getDescription()) {
                case 'Dyna Sleep Sales':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_dss.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'AMS Edmonton':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_ams.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Metro Medical Supplies':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_mms.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Finance Underwriting & Investment Capital':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_fuic.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Modern Medical Supplies':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_modern.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'One Life Medical Supplies Inc':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_onelife.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Alberta CPAP Sales':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_acs.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Calgary CPAP Sales':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_ccs.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Stampede Medical Supplies':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_scs.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Freedom Respiratory & Sleep Centre':
                    $content = $this->renderView('@RxConnexion/Patient/patient_billing_invoice_frsi.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                case 'Perfect Sleep Solutions WC Inc.':
                    $return = $this->render('@RxConnexion/Patient/patient_billing_invoice_pss.wkpdf.twig', array(
                        'patientBilling' => $patientBilling,
                        'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Billing Invoice Print'), false)
                    ));
                    break;
                default:
            }
        }
        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content, array(
            'dpi' => 96,
            // 'disable-smart-shrinking',
            'zoom' => 'LINUX' == strtoupper(PHP_OS) ? 0.78 : 1,
            'images' => true
        ));

        return new Response($xml, 200, array(
            'Content-Type' => 'application/pdf',
//            'Content-Disposition'   => 'attachment; filename="Invoice no. ' . $patientBilling->getInvoiceNo() . '.pdf"'
        ));
    }

    /**
     * @Route(
     *      "/patient-billing/breakdown-data",
     *      name = "patient_billing_breakdown_data"
     * )
     */
    public function patient_billing_breakdown_dataAction(Request $request){

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

        $em = $this->getDoctrine()->getManager();
        $result = array();
        $id = $request->get('id');
        $patientBilling = $em->getRepository(PatientBillingEntity::class)->find($id);
        $patientPayment = $em->getRepository(PatientPaymentEntity::class)->findBy(array(
            'patientBilling' => $patientBilling->getId(),
        ));

        $patientBilling->setAmountsValue();
        $amountBalance = 0;
        $amountPaid = 0;

        //TODO: Itemized payment wala pa.
        if($patientBilling->getBillingStatus() != 'Paid' && !$patientBilling->getPatientPayments()->count()) {
            foreach ($patientBilling->getPatientBillingBreakdowns() as $patientBillingBreakdown) {
                $amountBalance = $patientBillingBreakdown->getAmount();
                $patientBillingBreakdown->setAmountBalance($amountBalance);
            }

        }

        $em->flush();

        $result['success'] = true;
        $result['html'] = $this->renderView('@RxConnexion/Patient/patient_payment_breakdown_datalist.html.twig', array(
            'patientBilling' => $patientBilling
        ));

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_refund/breakdown-refund-data",
     *      name = "patient_refund_breakdown_data"
     * )
     */
    public function patient_refund_breakdown_dataAction(Request $request){

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

        $em = $this->getDoctrine()->getManager();
        $result = array();
        $id = $request->get('id');
        $patientBilling = $em->getRepository(PatientBillingEntity::class)->find($id);
        $patientBilling->setAmountsValue();
        $em->flush();

        $result['success'] = true;
        $result['html'] = $this->renderView('@RxConnexion/Patient/patient_refund_breakdown_datalist.html.twig', array(
            'patientBilling' => $patientBilling
        ));

        return new JsonResponse($result);
    }

    /**
     * @Route("/patient_payment_ajax_list", name="patient_payment_ajax_list")
     */
    public function patient_payment_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 Patient Payment Update'), false);
            $hasPreview = $authService->isUserHasAccesses(array('Admin Patient Payment Receipt Preview'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientPaymentEntity')->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-patient-payment-form' data-action='u' data-id='$id'>Details</a>";
                }
                if($hasPreview) {
                    $url = $this->generateUrl('patient_payment_receipt_preview', array('id' => $id));
                    $action .= "<a href='$url' target='_blank' class='action-button-style'>Receipt Preview</a>";
                }

                $values = array(
                    $row['invoiceNo'],
                    $row['healthFacility'],
                    $row['status'],
                    /*$row['payNo'],*/
                    $row['payDate'],
                    $row['payType'],
                    number_format($row['amount'], 2),
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_payment/form",
     *      name = "patient_payment_form"
     * )
     */
    public function patient_payment_formAction(Request $request) {

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

        $patient_id = $request->query->get('patient_id');
        $action = $request->query->get('action');
        $id = $request->query->get('id');

        $em = $this->getDoctrine()->getManager();
        $patientPayment = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->find(base64_decode($id));
        if(!$patientPayment) {
            $patientPayment = new PatientPaymentEntity();
        } else {
            $patientPayment->getPatientBilling()->setAmountsValue();
            $em->flush();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id,
            'payment_status' => $action == 'u' ? $patientPayment->getPaymentStatus() : PatientPaymentEntity::PAYMENT_STATUS_POSTED,
        );
        $form = $this->createForm(PatientPaymentForm::class, $patientPayment, $formOptions);


        $title = $action === 'n' ? 'New Payment' : sprintf('%006d', $patientPayment->getId()) ."(" . $patientPayment->getPaymentStatus() . ")";

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_payment_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'patientPayment' => $patientPayment
        ));
        $result['success'] = true;

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_payment/void_action",
     *      name = "patient_payment_void"
     * )
     */
    public function patient_payment_voidAction(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 Patient Payment New', 'Admin Patient Payment Update'))) return $authService->redirectToHome();

        $em = $this->getDoctrine()->getManager();
        $patientPayment_form = $request->get('patientPayment');
        $id = $patientPayment_form['id'];
        $patientPayment = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->find($id);

        switch($patientPayment_form['action']) {
            case 'u': // update

                $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_VOID);
                foreach($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                    if($patientBillingBreakdown->getPatientChart()){
                        $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                    }
                }
                $newAT = new AuditTrailEntity(
                    'Patient Payment',
                    $em->getClassMetadata(PatientPaymentEntity::class)->getTableName(),
                    AuditTrailEntity::AXN_UPDATE
                );
                $newAT->entity = $patientPayment;
                $newAT->parseOriginalDetails();
                $newAT->parseDetails();
                $em->persist($newAT);
                $em->flush();

                $result['success'] = true;
                $result['successMessages'][] = 'Payment transaction successfully voided.';

        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_payment/save_action",
     *      name = "patient_payment_save"
     * )
     */
    public function patient_payment_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 Patient Payment New', 'Admin Patient Payment Update'))) return $authService->redirectToHome();

        $patientPayment_form = $request->get('patientPayment');
        $patientPaymentBreakdown_form = $request->get('patientPaymentBreakdown');

        $em = $this->getDoctrine()->getManager();
        /**@var PatientPaymentEntity $patientPayment*/
        $patientPayment = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->find($patientPayment_form['id']);
        if(!$patientPayment) {
            $patientPayment = new PatientPaymentEntity();
        }
        $formOptions = array(
            'action' => $patientPayment_form['action'],
            'patient_id' => $patientPayment_form['patient'],
            'payment_status' => $patientPayment_form['payment_status'],
        );

        $form = $this->createForm(PatientPaymentForm::class, $patientPayment, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->validate($patientPayment_form, $patientPaymentBreakdown_form);

        if(!count($errors)) {

            switch($patientPayment_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        foreach($patientPaymentBreakdown_form as $ppb){
                            //if(!empty($ppb['amount']) && floatval($ppb['amount']) > 0) {
                            $patientPaymentBreakdown = new PatientPaymentBreakdownEntity();
                            $patientPaymentBreakdown->setPatientPayment($patientPayment);
                            $patientPaymentBreakdown->setPatientBillingBreakdown($em->getReference(PatientBillingBreakdownEntity::class, $ppb['patient_billing_breakdown_id']));
                            $patientPaymentBreakdown->setAmount($ppb['amount']);
                            $em->persist($patientPaymentBreakdown);
                            //}
                        }

                        $em->flush();

                        if($patientPayment_form['pay_type'] == PatientPaymentEntity::PAY_TYPE_FINANCING){
                            $patientBillingOld = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($patientPayment_form['patientBilling']);
                            $financingCompany = $em->getRepository('RxConnexionBundle:FinancingCompanyEntity')->find($patientPayment_form['financingCompany']);
                            $healthFacility  = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findOneBy(array('description'=>$financingCompany->getDescription()));

                            $patientBilling = new PatientBillingEntity();
                            $nextInvoiceNo = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->nextInvoiceNoFinancing($patientPayment_form['financingCompany']);
                            $patientBilling->setInvoiceNo($nextInvoiceNo);
                            $patientPayment->setNewInvoiceNoForFinancing($nextInvoiceNo);
                            /*$patientBilling->setInvoiceNo($patientPayment_form['newInvoiceNoForFinancing']);*/
                            $patientBilling->setBillingDate($patientBillingOld->getBillingDateAsString());
                            $patientBilling->setDueDate($patientBillingOld->getDueDateAsString());
                            $patientBilling->setPayerType(PatientBillingEntity::PAYER_TYPE_FINANCING);
                            $patientBilling->setPatient($patientBillingOld->getPatient());
                            $patientBilling->setAmountDue(intval(str_replace(',','',$patientPayment_form['amount'])) /*+ $patientBillingOld->getAmountPaid()*/);
                            $patientBilling->setInvoiceAmountDue(intval(str_replace(',','',$patientPayment_form['amount'])) /*+ $patientBillingOld->getAmountPaid()*/);
                            $patientBilling->setPatientPaymentFinancing($patientPayment);
                            $patientBilling->setAmountPaid(/*$patientBillingOld->getAmountPaid()*/0);
                            $patientBilling->setHealthFacilityForAddress($healthFacility);
                            $patientBilling->setHealthFacility($patientBillingOld->getHealthFacility());
                            $em->persist($patientBilling);

                            foreach ($patientBillingOld->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                                /**@var PatientBillingBreakdownEntity $newPatientBillingBreakdown*/
                                $newPatientBillingBreakdown = clone $patientBillingBreakdown;
                                $newPatientBillingBreakdown->setPatientBilling($patientBilling);
                                /*foreach($patientPaymentBreakdown_form as $ppb){
                                    if($ppb['patient_billing_breakdown_id'] == $patientBillingBreakdown->getId()){
                                        $newPatientBillingBreakdown->setAmount($ppb['amount']);
                                        break;
                                    }
                                }*/
                                $newPatientBillingBreakdown->setAmountPaid(0);
                                $newPatientBillingBreakdown->setAmountBalance(0);
                                $em->persist($newPatientBillingBreakdown);
                                $em->flush();
                            }

                            /*NOTE: STORE PATIENT BILLING PAYMENT DETAILS FOR FINANCING */
                            if(isset($patientPayment_form['is_payment_plan'])){
                                $patientBilling->setIsPaymentPlan(true);
                                $patientBillingFinancingPaymentDetail = new PatientBillingFinancingPaymentDetailEntity();
                                $patientBillingFinancingPaymentDetail->setPatientBilling($patientBilling);
                                $patientBillingFinancingPaymentDetail->setPaymentPlanType($patientPayment_form['payment_plan_type']);
                                $patientBillingFinancingPaymentDetail->setStartDate($patientPayment_form['start_date']);
                                $patientBillingFinancingPaymentDetail->setEndDate($patientPayment_form['end_date']);
                                $patientBillingFinancingPaymentDetail->setAmount($patientPayment_form['amortization_amount']);
                                $patientBillingFinancingPaymentDetail->setPaymentDay($patientPayment_form['payment_day']);
                                $em->persist($patientBillingFinancingPaymentDetail);
                                $em->flush();
                            } else {
                                $patientBilling->setIsPaymentPlan(false);
                            }

                            /*$newPatientBillingBreakdown = new PatientBillingBreakdownEntity();
                            $newPatientBillingBreakdown->setType('Other');
                            $newPatientBillingBreakdown->setDescription('Financing Balance');
                            $newPatientBillingBreakdown->setQuantity(1);
                            $newPatientBillingBreakdown->setPrice($patientPayment_form['amount']);
                            $newPatientBillingBreakdown->setAmount($patientPayment_form['amount']);
                            $newPatientBillingBreakdown->setPatientBilling($patientBilling);
                            $em->persist($newPatientBillingBreakdown);*/

                            $this->check_financing_billing_today($patientBillingOld->getPatient());
                        }

                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientPayment_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientPayment->getPatient());
                        $em->persist($patientNote);
                        $em->flush();

                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
                        foreach($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setAmountValue();
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                            }
                        }


                        $newAT = new AuditTrailEntity(
                            'Patient Payment',
                            $em->getClassMetadata(PatientPaymentEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientPayment;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

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

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Patient Payment',
                        $em->getClassMetadata(PatientPaymentEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientPayment;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    /*TODO: ISVALID RETURNS FALSE ALWAYS*/
                    if ($form->isValid()) {

                        foreach($patientPaymentBreakdown_form as $ppb){
                            $patientPaymentBreakdown = $em->getRepository(PatientPaymentBreakdownEntity::class)->find($ppb['id']);
                            if(!$patientPaymentBreakdown){
                                $patientPaymentBreakdown = new PatientPaymentBreakdownEntity();
                                $patientPaymentBreakdown->setPatientPayment($patientPayment);
                                $patientPaymentBreakdown->setPatientBillingBreakdown($em->getReference(PatientBillingBreakdownEntity::class, $ppb['patient_billing_breakdown_id']));
                            }
                            $patientPaymentBreakdown->setAmount($ppb['amount']);
                            //$em->persist($patientPaymentBreakdown);
                        }

                        $em->flush();
                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
                        foreach($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setAmountValue();
                        }

                        if($patientPayment->getPatientBilling()->getPayerType() === PatientPaymentEntity::PAY_TYPE_FINANCING && $patientPayment_form['payment_status'] === PatientPaymentEntity::PAYMENT_STATUS_PENDING && intval($patientPayment_form['amount']) > 0){
                            $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_POSTED);
                        }

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

                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientPayment_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientPayment->getPatient());
                        $em->persist($patientNote);

                        $em->flush();

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Patient Payment',
                        $em->getClassMetadata(PatientPaymentEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientPayment;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {


                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
                        foreach($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setAmountValue();
                        }
                        //$em->remove($patientPayment);
                        $patientPayment->setIsDeleted(true);
                        $em->flush();

                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
                        foreach($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setAmountValue();
                        }
                        $em->flush();

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

                    } else {

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

                    break;

                case 'v': // void

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_VOID);
	                    if($patientPayment->getPatientBillingFinancing()) {
		                    $patientPayment->getPatientBillingFinancing()->setBillingStatus(PatientBillingEntity::BILLING_STATUS_VOID);
	                    }
                        //$em->flush();
                        foreach ($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown) {
                            $patientBillingBreakdown->setAmountValue();
                            if ($patientBillingBreakdown->getPatientChart()) {
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                            }
                        }


                        $newAT = new AuditTrailEntity(
                            'Patient Payment',
                            $em->getClassMetadata(PatientPaymentEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_UPDATE
                        );
                        $newAT->entity = $patientPayment;
                        $newAT->parseOriginalDetails();
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

                        $result['success'] = true;
                        $result['successMessages'][] = 'Payment transaction successfully voided.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }
                    break;

                case 'p': // post

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_POSTED);
                        $em->flush();
                        foreach ($patientPayment->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown) {
                            $patientBillingBreakdown->setAmountValue();
                            if ($patientBillingBreakdown->getPatientChart()) {
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                            }
                        }
                        $newAT = new AuditTrailEntity(
                            'Patient Payment',
                            $em->getClassMetadata(PatientPaymentEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_UPDATE
                        );
                        $newAT->entity = $patientPayment;
                        $newAT->parseOriginalDetails();
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

                        $result['success'] = true;
                        $result['successMessages'][] = 'Payment transaction successfully posted.';
                    }
                    break;

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

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

    /**
     * @Route(
     *      "/patient_payment/receipt/preview",
     *      name = "patient_payment_receipt_preview"
     * )
     */
    public function patient_payment_receipt_previewAction(Request $request) {

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

        $id = $request->query->get('id');
        $patientPayment = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientPaymentEntity')->find(base64_decode($id));
        $return = $this->render('@RxConnexion/Patient/patient_payment_receipt.wkhtml.twig', array(
            'patientPayment' => $patientPayment,
            'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Payment Receipt Print'), false)
        ));
        if($patientPayment->getPatientBilling()->getHealthFacilityForAddress()){
            if($patientPayment->getPatientBilling()->getHealthFacilityForAddress()->getCompany()->getDescription() === 'Dyna Sleep Sales'){
                $return = $this->render('@RxConnexion/Patient/patient_payment_receipt_dss.wkhtml.twig', array(
                    'patientPayment' => $patientPayment,
                    'hasPrintBtn' => $authService->isUserHasAccesses(array('Admin Patient Payment Receipt Print'), false)
                ));
            }
        }

        return $return;
    }

    /**
     * @Route("/patient_refund_ajax_list", name="patient_refund_ajax_list")
     */
    public function patient_refund_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 Patient Billing Refund Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->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-patient-billing-refund-form' data-action='u' data-id='$id'>Details</a>";
                }

                $values = array(
                    $row['invoiceNo'],
                    $row['refundDate'],
                    number_format($row['amount'], 2),
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_refund/form",
     *      name = "patient_refund_form"
     * )
     */
    public function patient_refund_formAction(Request $request) {

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

        $patient_id = $request->query->get('patient_id');
        $action = $request->query->get('action');
        $id = $request->query->get('id');

        $em = $this->getDoctrine()->getManager();
        $patientRefund = $em->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->find(base64_decode($id));
        if(!$patientRefund) {
            $patientRefund = new PatientBillingRefundEntity();
        } else {
            $patientRefund->getPatientBilling()->setAmountsValue();
            $em->flush();
        }

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id,
        );
        $form = $this->createForm(PatientBillingRefundForm::class, $patientRefund, $formOptions);


        $title = $action === 'n' ? 'New Patient Refund' : 'Update Patient Refund';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_refund_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'patientRefund' => $patientRefund
        ));
        $result['success'] = true;

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_refund/save_action",
     *      name = "patient_refund_save"
     * )
     */
    public function patient_refund_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 Patient Billing Refund New', 'Admin Patient Billing Refund Update'))) return $authService->redirectToHome();

        $patientBillingRefund_form = $request->get('patientBillingRefund');
        $patientBillingRefundBreakdown_form = $request->get('patientRefundBreakdown');

        $em = $this->getDoctrine()->getManager();
        $patientBilling = $em->getRepository('RxConnexionBundle:PatientBillingEntity')->find($patientBillingRefund_form['patientBilling']);
        $patientBillingRefund = $em->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->find($patientBillingRefund_form['id']);
        if(!$patientBillingRefund) {
            $patientBillingRefund = new PatientBillingRefundEntity();
        }
        $formOptions = array(
            'action' => $patientBillingRefund_form['action'],
            'patient_id' => $patientBillingRefund_form['patient'],
        );
        $form = $this->createForm(PatientBillingRefundForm::class, $patientBillingRefund, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientBillingRefundEntity')->validate($patientBillingRefund_form);

        if(!count($errors)) {

            switch($patientBillingRefund_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        foreach($patientBillingRefundBreakdown_form as $ppb){
                            $patientBillingRefundBreakdown = new PatientRefundBreakdownEntity();
                            $patientBillingRefundBreakdown->setPatientBillingRefund($patientBillingRefund);
                            $patientBillingRefundBreakdown->setPatientBillingBreakdown($em->getReference(PatientBillingBreakdownEntity::class, $ppb['patient_billing_breakdown_id']));
                            $patientBillingRefundBreakdown->setAmount($ppb['amount']);
                            $em->persist($patientBillingRefundBreakdown);
                        }

                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientBillingRefund_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientBillingRefund->getPatient());
                        $em->persist($patientNote);
                        $em->flush();

                        /**@var PatientBillingBreakdownEntity $patientBillingBreakdown*/
                        foreach($patientBillingRefund->getPatientBilling()->getPatientBillingBreakdowns() as $patientBillingBreakdown){
                            $patientBillingBreakdown->setRefundAmountValue();
                            if($patientBillingBreakdown->getPatientChart()){
                                $patientBillingBreakdown->getPatientChart()->updateBillingStatus(null);
                            }
                        }


                        $newAT = new AuditTrailEntity(
                            'Patient Billing Refund',
                            $em->getClassMetadata(PatientBillingRefundEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientBillingRefund;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

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

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Patient Billing Refund',
                        $em->getClassMetadata(PatientBillingRefundEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientBillingRefund;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);
                    /*TODO: ISVALID RETURNS FALSE ALWAYS*/
                    if ($form->isValid()) {

//                        foreach($patientBillingRefundBreakdown_form as $ppb){
//                            $patientBillingRefundBreakdown = new PatientRefundBreakdownEntity();
//                            $patientBillingRefundBreakdown->setPatientBillingRefund($patientBillingRefund);
//                            $patientBillingRefundBreakdown->setPatientBillingBreakdown($em->getReference(PatientBillingBreakdownEntity::class, $ppb['patient_billing_breakdown_id']));
//                            $patientBillingRefundBreakdown->setAmount($ppb['amount']);
//                            $em->persist($patientBillingRefundBreakdown);
//                        }


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

                        $patientNote = new PatientNoteEntity();
                        $patientNote->setNote($patientBillingRefund_form['note']);
                        $patientNote->setType(PatientNoteEntity::TYPE_BILLING);
                        $patientNote->setPatient($patientBillingRefund->getPatient());
                        $em->persist($patientNote);

                        $em->flush();

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Patient Billing Refund',
                        $em->getClassMetadata(PatientBillingRefundEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientBillingRefund;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($patientPayment);
                        $patientBillingRefund->setIsDeleted(true);
                        $em->flush();
                        $em->refresh($patientBilling);
                        $patientBilling->setAmountsValue();
                        $patientBilling->updateBillingStatus();
                        $em->flush();
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Deleted.';

                    } else {

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

                    break;

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

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


    /**
     * @Route("/patient_history_ajax_list", name="patient_history_ajax_list")
     */
    public function patient_history_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() && $this->container->getParameter('kernel.environment') != 'dev') {

            $authService->isUserHasAccesses(array('Admin Patient History'), false);

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

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

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

                $history = json_decode($row['patient_history'], true);
                $historyData = '';
                $labels = array();
                switch ($row['table_name']) {
                    case 'patient_chart' :
                        $labels = array(
                            'id' => 'Encounter ID',
                            'chart_date' => 'Encounter Date',
                            'chart_status' => array(
                                'Encounter Status',
                                'description'
                            ),
                            'chart_type' => array(
                                'Encounter Type',
                                'description'
                            ),
                            'provider' => array(
                                'Clinician ID',
                                'id'
                            ),
                            'health_facility' => array(
                                'Branch',
                                'description'
                            )
                        );
                        break;

                    case 'patient' :
                        $labels = array(
                            'id' => 'Patient ID',
                            'full_name' => 'Patient Name',
                            'gender' => 'Gender',
                            'birth_date' => 'Birth Date',
                            'personal_health_no' => 'Personal Health No.',
                            'address' => 'Address',
                            'referral_date' => 'Patient Referral Date',
                            'received_date' => 'Patient Received Date',
                            'is_active' => 'Active',
                            'is_endorsed' => 'Endorsed',
                            'is_specialist' => 'Specialist',
                            'endorsed_by' => 'Endorsed By',
                            'postal_code' => array(
                                'Postal Code',
                                'description'
                            ),
                            'health_facility' => array(
                                'Branch',
                                'description'
                            ),
                        );
                        break;

                    case 'schedule' :
                        $labels = array(
                            'id' => 'Schedule ID',
                            'schedule_date' => 'Date',
                            'start_time' => 'Start Time',
                            'end_time' => 'End Time',
                            'health_facility' => array(
                                'Branch',
                                'description'
                            ),
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                            'chart_type' => array(
                                'Encounter Type',
                                'description'
                            ),
                            'schedule_status' => array(
                                'Status',
                                'description'
                            ),
                            'note' => 'Note'
                        );
                        break;

                    case 'patient_insurance' :
                        $labels = array(
                            'id' => 'ID',
                            'insurance_no' => 'Insurance No',
                            'expire_date' => 'Expiry Date',
                            'start_date' => 'Start Date',
                            'end_date' => 'End Date',
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                        );
                        break;

                    case 'patient_referring_health_facility' :
                        $labels = array(
                            'id' => 'ID',
                            'referring_health_facility' => array(
                                'Referring Affiliate',
                                'description'
                            ),
                            'start_date' => 'Start Date',
                            'end_date' => 'End Date',
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            )
                        );
                        break;

                    case 'patient_referring_provider' :
                        $labels = array(
                            'id' => 'ID',
                            'referring_provider' => array(
                                'Referring Physician ID',
                                'id',
                            ),
                            'start_date' => 'Start Date',
                            'end_date' => 'End Date',
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            )
                        );
                        break;

                    case 'patient_file' :
                        $labels = array(
                            'id' => 'ID',
                            'description' => 'Description',
                            'note' => 'Notes',
                            'file_type' => array(
                                'File Type',
                                'description',
                            ),
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            )
                        );
                        break;

                    case 'patient_note' :
                        $labels = array(
                            'id' => 'ID',
                            'note' => 'Notes',
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            )
                        );
                        break;

                    case 'patient_diagnosis' :
                        $labels = array(
                            'id' => 'ID',
                            'start_date' => 'Start Date',
                            'end_date' => 'End Date',
                            'note' => 'Notes',
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            )
                        );
                        break;

                    case 'patient_letter' :
                        $labels = array(
                            'id' => 'ID',
                            'letter_type' => 'Letter Type',
                            'patient_letter_status' => array(
                                'Status',
                                'description'
                            ),
                            'patient_insurance' => array(
                                'Insurance ID',
                                'id'
                            ),
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                        );
                        break;

                    case 'patient_billing' :
                        $labels = array(
                            'id' => 'ID',
                            'invoice_no' => 'Invoice No.',
                            'billing_date' => 'Billing Date',
                            'amount_due' => 'Amount Due',
                            'amount_paid' => 'Amount Paid',
                            'amount_balance' => 'Amount Balance',
                            'billing_status' => 'Billing Status',
                            'payer_type' => 'Payer Type',
                            'note' => 'Note',
                            'patient_insurance' => array(
                                'Insurance ID',
                                'id'
                            ),
                            'patient_billing_breakdowns' => array(
                                'Breakdowns',
                                array(
                                    'type' => 'Type',
                                    'description' => 'Description',
                                    'quantity' => 'Quantity',
                                    'price' => 'Price',
                                    'amount' => 'Amount',
                                )
                            ),
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                        );
                        break;

                    case 'patient_payment' :
                        $labels = array(
                            'id' => 'ID',
                            'pay_type' => 'Pay Type',
                            'pay_date' => 'Pay Date',
                            'amount' => 'Amount',
                            'bill_due_amount' => 'Bill Due Amount',
                            'bill_bal_amount' => 'Bill Bal Amount',
                            'note' => 'Note',
                            'patient_billing' => array(
                                'Invoice No.',
                                'invoice_no'
                            ),
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                        );
                        break;

                    case 'patient_red_flag' :
                        $labels = array(
                            'id' => 'ID',
                            'start_date' => 'Start Date',
                            'end_date' => 'End Date',
                            'red_flag_note' => 'Red Flag Note',
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                        );
                        break;

                    case 'patient_service' :
                        $labels = array(
                            'id' => 'ID',
                            'start_date' => 'Start Date',
                            'end_date' => 'End Date',
                            'patient_service_type' => 'Patient Service Type',
                            'service' => array(
                                'description' => 'Description'
                            ),
                            'specialist' => array(
                                'first_name' => 'First Name',
                                'last_name' => 'Last Name'
                            ),
                            'health_facility' => array(
                                'description' => 'Description'
                            ),
                            'patient' => array(
                                'Patient Name',
                                'full_name'
                            ),
                        );
                        break;

//                    case 'patient_billing_refund' :
//                        $labels = array(
//                            'id' => 'ID',
//                            'start_date' => 'Start Date',
//                            'end_date' => 'End Date',
//                            'patient_service_type' => 'Patient Service Type',
//                            'service' => array(
//                                'description' => 'Description'
//                            ),
//                            'specialist' => array(
//                                'first_name' => 'First Name',
//                                'last_name' => 'Last Name'
//                            ),
//                            'health_facility' => array(
//                                'description' => 'Description'
//                            ),
//                            'patient' => array(
//                                'Patient Name',
//                                'full_name'
//                            ),
//                        );
//                        break;

                }

                if($row['axn'] == 'New' || $row['axn'] == 'Delete') {
                    foreach ($labels as $columnName => $label) {
                        $historyData .= (empty($historyData) ? '' : ' | ');

                        if(is_array($label)) {
                            $historyData .= $label[0] .':';
                            if (isset($history['Details'][$columnName])) {
                                if(is_array($label[1])) {
                                    foreach ($history['Details'][$columnName] as $idx => $detailsData) {
                                        $historyData .= ' ('.($idx+1).') ';
                                        $historyData2 = '';
                                        foreach($label[1] as $columnName2 => $label2) {
                                            $historyData2 .= (empty($historyData2) ? '' : ' &#8226; ').$label2.': ';
                                            if(isset($history['Details'][$columnName][$idx][$columnName2])) {
                                                $historyData2 .= $history['Details'][$columnName][$idx][$columnName2];
                                            }
                                        }
                                        $historyData .= $historyData2;
                                    }
                                } else {
                                    $historyData .= $history['Details'][$columnName][$label[1]];
                                }

                            }
                        } else {
                            $historyData .= $label.': ';
                            if(isset($history['Details'][$columnName])) {
                                $historyData .= $history['Details'][$columnName];
                            }
                        }

                    }
                }else{
                    foreach ($labels as $columnName => $label) {
                        if(is_array($label)) {
                            if(is_array($label[1])) {
                                $origValue = '';
                                $newValue = '';
                                if(isset($history['Original Details'][$columnName])) {
                                    foreach ($history['Original Details'][$columnName] as $idx => $detailsData) {
                                        $origValue .= ' ('.($idx+1).') ';
                                        $origValue2 = '';
                                        foreach($label[1] as $columnName2 => $label2) {
                                            $origValue2 .= (empty($origValue2) ? '' : ' &#8226; ').$label2.': ';
                                            if(isset($history['Original Details'][$columnName][$idx][$columnName2])) {
                                                $origValue2 .= $history['Original Details'][$columnName][$idx][$columnName2];
                                            }
                                        }
                                        $origValue .= $origValue2;
                                    }
                                }

                                if(isset($history['Details'][$columnName])) {
                                    foreach ($history['Details'][$columnName] as $idx => $detailsData) {
                                        $newValue .= ' ('.($idx+1).') ';
                                        $newValue2 = '';
                                        foreach($label[1] as $columnName2 => $label2) {
                                            $newValue2 .= (empty($newValue2) ? '' : ' &#8226; ').$label2.': ';
                                            if(isset($history['Details'][$columnName][$idx][$columnName2])) {
                                                $newValue2 .= $history['Details'][$columnName][$idx][$columnName2];
                                            }
                                        }
                                        $newValue .= $newValue2;
                                    }
                                }

                            } else {
                                $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName][$label[1]] : null;
                                $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName][$label[1]] : null;
                            }
                        } else {
                            $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName] : null;
                            $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName] : null;
                        }

                        if($origValue != $newValue) {
                            $historyData .= (empty($historyData) ? '' : ' | ');
                            $historyData .= (is_array($label) ? $label[0] : $label).' : ';
                            $historyData .= $origValue;

                            $historyData .= ' -> ';
                            $historyData .= $newValue;
                        }
                    }

                }

                $values = array(
                    $row['axn'],
                    $row['date'],
                    $row['user'],
                    $row['label'],
                    $historyData,
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_payment/receipt/print",
     *      name = "patient_payment_receipt_print"
     * )
     */
    public function patient_payment_receipt_printAction(Request $request) {

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

        $id = $request->query->get('id');
        $patientPayment = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PatientPaymentEntity')->find(base64_decode($id));

        $content = $this->renderView('@RxConnexion/Patient/patient_payment_receipt.wkhtml.twig', array(
            'patientPayment' => $patientPayment
        ));
        if($patientPayment->getPatientBilling()->getHealthFacilityForAddress()){
            if($patientPayment->getPatientBilling()->getHealthFacilityForAddress()->getCompany()->getDescription() === 'Dyna Sleep Sales'){
                $content = $this->renderView('@RxConnexion/Patient/patient_payment_receipt_dss.wkhtml.twig', array(
                    'patientPayment' => $patientPayment
                ));
            }
        }
        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content);

        return new Response($xml, 200, array(
            'Content-Type' => 'application/pdf',
            'Content-Disposition'   => 'attachment; filename="Payment no. ' . $patientPayment->getPaymentNoParsed() . '.pdf"'
        ));
    }

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

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

                $values = array(
                    $row['health_facility'],
                    $row['address'],
                    $row['phone_no'],
                    $row['fax_no'],
                    $row['start_date'],
                    $row['end_date'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_health_facility/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_health_facility_form"
     * )
     */
    public function patient_health_facility_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientHealthFacilityForm::class, $patientHealthFacility, $formOptions);

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

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

    /**
     * @Route(
     *      "/patient_health_facility/save_action",
     *      name = "patient_health_facility_save"
     * )
     */
    public function patient_health_facility_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 Patient Health Facility New', 'Admin Patient Health Facility Update'))) return $authService->redirectToHome();

        $patientHealthFacility_form = $request->get('patient_health_facility');
        $em = $this->getDoctrine()->getManager();
        $patientHealthFacility = $em->getRepository('RxConnexionBundle:PatientHealthFacilityEntity')->find($patientHealthFacility_form['id']);
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patientHealthFacility_form['patient']));
        if(!$patientHealthFacility) {
            $patientHealthFacility = new PatientHealthFacilityEntity();
        }

        $formOptions = array(
            'action' => $patientHealthFacility_form['action'],
            'patient_id' => $patientHealthFacility_form['patient']
        );
        $form = $this->createForm(PatientHealthFacilityForm::class, $patientHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientHealthFacilityEntity')->validate($patientHealthFacility_form);

        if(!count($errors)) {

            switch($patientHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        $activeHF = $patient->getActiveHealthFacility();
                        $patient->setHealthFacility($activeHF);

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

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

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

                        $em->flush();


                        $activeHF = $patient->getActiveHealthFacility();
                        $patient->setHealthFacility($activeHF);
                        $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(
                        'Patient Health Facility',
                        $em->getClassMetadata(PatientReferringHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientHealthFacility;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

    /*--------------------------------------------------------------------------------------------------------*/
    /*				           	PATIENT EMAIL						    				                      */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @Route("/patient_email_ajax_list", name="patient_email_ajax_list")
     */
    public function patient_email_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 Patient Email Update'), false);
            $hasSend = $authService->isUserHasAccesses(array('Admin Patient Email Send'), false);

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

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

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

                $sendUrl = $this->generateUrl('patient_email_send', array(
                    'patientEmail_id' => $id,
                ));

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

                if($hasSend) {
                    $action .= "<a class='action-button-style ask-continue' data-message='Are you sure you want to send an email?' href='$sendUrl'>Send</a>";
                }


                $attachmentWithLink = '';
                if(isset($row['attachmentFile'])){
                    $attachmentWithLinks = array();
                    $attachmentDetails = explode(',' , $row['attachmentFile']);
                    foreach ($attachmentDetails as $attachmentDetail){
                        $attachmentDetailForIds = explode('~', $attachmentDetail);
                        $attachmentLink = !empty($attachmentDetailForIds[0]) ? $this->generateUrl('patient_letter_file_download', array(
                            'id' => base64_encode($attachmentDetailForIds[0])
                        )) : 'javascript:void(0)';
                        $attachmentWithLinks[] = isset($attachmentDetailForIds[1]) ? "<a href='$attachmentLink' target='_blank'> $attachmentDetailForIds[1]</a>" : '';
                    }
                    $attachmentWithLink = implode('<br />' ,$attachmentWithLinks);
                }


                $values = array(
                    $row['createdAt'],
                    $row['email_template_description'],
                    $row['status'],
                    $attachmentWithLink,
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_email/form/{patient_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "patient_email_form"
     * )
     */
    public function patient_email_formAction($patient_id, $action, $id) {

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

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

        $formOptions = array(
            'action' => $action,
            'patient_id' => $patient_id
        );
        $form = $this->createForm(PatientEmailForm::class, $patientEmail, $formOptions);

        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));

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

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

    /**
     * @Route(
     *      "/patient_email/save_action",
     *      name = "patient_email_save"
     * )
     */
    public function patient_email_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 Patient Email New', 'Admin Patient Email Update'))) return $authService->redirectToHome();

        $patientEmail_form = $request->get('patient_email');
        $em = $this->getDoctrine()->getManager();
        $patientEmail = $em->getRepository('RxConnexionBundle:PatientEmailEntity')->find($patientEmail_form['id']);
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patientEmail_form['patient']));
        if(!$patientEmail) {
            $patientEmail = new PatientEmailEntity();
        }

        $formOptions = array(
            'action' => $patientEmail_form['action'],
            'patient_id' => $patientEmail_form['patient']
        );
        $form = $this->createForm(PatientEmailForm::class, $patientEmail, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:PatientEmailEntity')->validate($patientEmail_form);

        if(!count($errors)) {

            switch($patientEmail_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

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

                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $patientEmailFile = new PatientEmailFileEntity();
                                    $patientEmailFile->setPatientEmail($patientEmail);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $patientEmailFile->getUploadRootDir() . '/' . $baseName;
                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $patientEmailFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $patientEmailFile->setParsedFileDesc($baseName);
                                        $em->persist($patientEmailFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }


                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Patient Email',
                            $em->getClassMetadata(PatientEmailEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $patientEmail;
                        $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(
                        'Patient Email',
                        $em->getClassMetadata(PatientEmailEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $patientEmail;
                    $newAT->parseOriginalDetails();

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

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

                        $formPatientEmailFile = $request->get('otherForm');
                        $patientEmailFile = $em->getRepository('RxConnexionBundle:PatientEmailFileEntity')->findBy(array(
                            'patientEmail' => $patientEmail->getId(),
                            'isDeleted' => false
                        ));

                        if(isset($_FILES['files']['tmp_name'])) {
                            foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
                                if(!empty($tmpName)) {

                                    $newPatientEmailFile = new PatientEmailFileEntity();
                                    $newPatientEmailFile->setPatientEmail($patientEmail);

                                    $baseName = rand(0,999) . '-' . time() . '.' . pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
                                    $uploadFile = $newPatientEmailFile->getUploadRootDir() . '/' . $baseName;

                                    if(move_uploaded_file($tmpName, $uploadFile)) {
                                        $newPatientEmailFile->setFileDesc($_FILES['files']['name'][$key]);
                                        $newPatientEmailFile->setParsedFileDesc($baseName);
                                        $em->persist($newPatientEmailFile);
                                        $em->flush();
                                    }
                                }
                            }
                        }

                        if(isset($formPatientEmailFile)) {
                            foreach($patientEmailFile as $plf) {
                                if(!in_array($plf->getIdEncoded(), $formPatientEmailFile['files'])) {
                                    $patientEmailFile2 = $em->getRepository('RxConnexionBundle:PatientEmailEntity')->find($plf->getId());
                                    $patientEmailFile2->removeFile();
                                    $patientEmailFile2->setIsDeleted(true);
                                    $em->flush();
                                }
                            }
                        } else {
                            foreach ($patientEmailFile as $plf2) {
                                $plf2->removeFile();
                                $plf2->setIsDeleted(true);
                                $em->flush();
                            }

                        }

                        $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(
                        'Patient Email',
                        $em->getClassMetadata(PatientEmailEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $patientEmail;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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


    /*--------------------------------------------------------------------------------------------------------*/
    /*				           	PATIENT LETTER APPROVED FUNCTION						    				  */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @Route(
     *      "/patient_approve_letter/{patientLetter_id}",
     *      name = "patient_approve_letter"
     * )
     */
    public function patientLetterApproveAction($patientLetter_id, Request $request) {

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

        $patientLetter = $em->getRepository('RxConnexionBundle:PatientLetterEntity')->find(base64_decode($patientLetter_id));
        if(isset($patientLetter_id) || $patientLetter_id != '') {
            $patientLetterStatusApproved = $em->getRepository('RxConnexionBundle:PatientLetterStatusEntity')->findOneBy(array(
                'description' => 'Approved'
            ));

            $patientLetter->setPatientLetterStatus($patientLetterStatusApproved);
            $em->persist($patientLetter);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('patient_detail', array(
            'tab' => 'l',
            'patient_id' => base64_encode($patientLetter->getPatient()->getId())
        )));
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*				           	PATIENT Export HL7 	  						    						       */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @Route(
     *      "/export-hl7/{patient_id}",
     *      name = "patient_export_hl7"
     * )
     */
    public function patient_export_hl7Action($patient_id, Request $request) {

        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Export HL7'))) return $authService->redirectToHome();

        $type =  $request->query->get('type');
        $params =  $request->query->all();
        $patient = $em->getRepository('RxConnexionBundle:PatientEntity')->find(base64_decode($patient_id));
        $hl7Service = $this->get('rx_connexion.hl7Service');
        $hl7Data = $hl7Service->generate($type, $patient, $params);

        header("Content-type: text/plain");
        header("Content-Disposition: attachment; filename=".$type.'-'.$patient->getFullName().".hl7");

        echo $hl7Data['data'];
        die();

    }

    /**
     * @Route(
     *      "/export-hl7-form/{patient_id}",
     *      name = "patient_export_hl7_form"
     * )
     */
    public function patient_export_hl7_formAction($patient_id) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Export HL7'))) return $authService->redirectToHome();

        $hl7Service = $this->get('rx_connexion.hl7Service');
        $hl7MessageTypes = $hl7Service->messageTypes;

        $title = 'Export Patient Details to HL7 File';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/export_hl7_v2x.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'patient_id' => $patient_id,
            'hl7MessageTypes' => $hl7MessageTypes
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*				           	PATIENT ENCOUNTER TRANSFER          		    						      */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @Route(
     *      "/patient_chart_transfer",
     *      name = "patient_chart_transfer"
     * )
     */
    public function patient_chart_transferAction() {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Chart Transfer'))) return $authService->redirectToHome();

        $title = 'Patient Chart Transfer';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_chart_transfer_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_chart_transfer_save_action",
     *      name = "patient_chart_transfer_save"
     * )
     */
    public function patient_chart_transfer_saveAction(Request $request) {

        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Chart Transfer'))) return $authService->redirectToHome();

        $patient_id =  $request->get('patient_id');
        $params =  $request->get('ids');

        if(!empty($params) || $params != null) {

            $patient = $em->getRepository(PatientEntity::class)->find($patient_id);

            if($patient) {
                foreach ($params as $param) {
                    $oldPatientChart = $em->getRepository(PatientChartEntity::class)->find($param);
                    $oldPatientChart->setPatient($patient);
                    $em->flush();
                }


            }

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

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

        return new JsonResponse($result);
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*				           	PATIENT FILE TRANSFER          		    						              */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
 * @Route(
 *      "/patient_file_transfer",
 *      name = "patient_file_transfer"
 * )
 */
    public function patient_file_transferAction() {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient File Transfer'))) return $authService->redirectToHome();

        $title = 'Patient Chart Transfer';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_file_transfer_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_file_transfer_save_action",
     *      name = "patient_file_transfer_save"
     * )
     */
    public function patient_file_transfer_saveAction(Request $request) {

        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient File Transfer'))) return $authService->redirectToHome();

        $patient_id =  $request->get('patient_id');
        $params =  $request->get('ids');

        if(!empty($params) || $params != null) {

            $patient = $em->getRepository(PatientEntity::class)->find($patient_id);

            if($patient) {
                foreach ($params as $param) {
                    $oldPatientFile = $em->getRepository(PatientFileEntity::class)->find($param);
                    $oldPatientFile->setPatient($patient);
                    $em->flush();
                }


            }

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

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

        return new JsonResponse($result);
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*				           	PATIENT TRANSFER          		    						                  */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @Route(
     *      "/patient_transfer",
     *      name = "patient_transfer"
     * )
     */
    public function patient_transferAction(Request $request) {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Chart Transfer', 'Admin Patient File Transfer', 'Admin Patient Letter Transfer', 'Admin Patient Billing Transfer', 'Admin Patient Red Flag Transfer', 'Admin Patient Endorsement Transfer', 'Admin Patient Reminder Transfer'))) return $authService->redirectToHome();

        $title = 'Patient Transfer';

        $result['html'] =  $this->renderView('@RxConnexion/Patient/patient_transfer_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
        ));
        $result['success'] = true;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/patient_transfer_save_action",
     *      name = "patient_transfer_save"
     * )
     */
    public function patient_transfer_saveAction(Request $request) {

        $em = $this->getDoctrine()->getManager();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Patient Chart Transfer', 'Admin Patient File Transfer', 'Admin Patient Letter Transfer', 'Admin Patient Billing Transfer', 'Admin Patient Red Flag Transfer', 'Admin Patient Endorsement Transfer', 'Admin Patient Reminder Transfer'))) return $authService->redirectToHome();

        $patient_id =  $request->get('patient_id');
        $type =  $request->get('type');
        $params =  $request->get('ids');
        $patient = $em->getRepository(PatientEntity::class)->find($patient_id);

        if ($patient) {
            if (!empty($params) || $params != null) {
                switch ($type) {
                    case 'Encounter' :
                        foreach ($params as $param) {
                            $patientChart = $em->getRepository(PatientChartEntity::class)->find($param);
                            $patientChart->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'File' :
                        foreach ($params as $param) {
                            $patientFile = $em->getRepository(PatientFileEntity::class)->find($param);
                            $patientFile->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'Letters' :
                        foreach ($params as $param) {
                            $patientLetter = $em->getRepository(PatientLetterEntity::class)->find($param);
                            $patientLetter->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'Billing' :
                        foreach ($params as $param) {
                            $patientBilling = $em->getRepository(PatientBillingEntity::class)->find($param);
                            $patientBilling->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'Red Flag' :
                        foreach ($params as $param) {
                            $patientRedFlag = $em->getRepository(PatientRedFlagEntity::class)->find($param);
                            $patientRedFlag->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'Endorsement' :
                        foreach ($params as $param) {
                            $patientTicket = $em->getRepository(PatientTicketEntity::class)->find($param);
                            $patientTicket->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'Reminder' :
                        foreach ($params as $param) {
                            $accountUserReminderRef = $em->getRepository(AccountUserReminderRefPatientEntity::class)->find($param);
                            $accountUserReminderRef->setPatient($patient);
                            $em->flush();
                        }

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

                        break;
                    case 'Note' :
                        foreach ($params as $param) {
                            $patientNote = $em->getRepository(PatientNoteEntity::class)->find($param);
                            $patientNote->setPatient($patient);
                            $em->flush();
                        }

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/fax_status_receipt",
     *      name = "fax_status_receipt"
     * )
     */
    public function fax_status_receiptAction(Request $request) {
        $result['success'] = false;
        $result['msg'] = 'No matching remote id.';
        $filName = $request->get('FileName');
        $sentStatus = $request->get('SentStatus');
        $dateQueued = $request->get('DateQueued');
        $dateSent = $request->get('DateSent');
        $toFaxNumber = $request->get('ToFaxNumber');
        $noPage = $request->get('Pages');
        //$duration = $request->get('Duration');
        $fileNameDetails = explode('|', $filName);
        $remoteId = $fileNameDetails[1];
        $faxDetails = array(
            'fileName' => $filName,
            'sentStatus' => $sentStatus,
            'dateQueued' => $dateQueued,
            'dateSent' => $dateSent,
            'toFaxNumber' => $toFaxNumber,
            'pages' => $noPage
        );

        $em = $this->getDoctrine()->getManager();
        $faxTranOutBound = $em->getRepository('RxConnexionBundle:FaxTranOutboundEntity')->findOneBy(array(
            'faxId' => $remoteId
        ));

        $fileType = $em->getRepository('RxConnexionBundle:FileTypeEntity')->findOneBy(array(
            'description' => 'Fax Confirmation'
        ));

        if($faxTranOutBound){
            if($faxTranOutBound->getPatientLetter()){
                $patient = $faxTranOutBound->getPatientLetter()->getPatient();
                $content = $this->renderView('@RxConnexion/Referral/FaxTemplate/FaxReceipt.wkpdf.twig', array(
                    'response' => $faxDetails
                ));
                $fileName = $remoteId . ' - Fax Confirmation';
                $patientFile = new PatientFileEntity();
                $patientFile->setNote('Fax Receipt');
                $patientFile->setFileType($fileType);
                $patientFile->setPatient($patient);
                $em->persist($patientFile);
                $em->flush();
                $baseName = $patientFile->getId() . '-' . time() . '.pdf';
                $uploadFile = $patientFile->getUploadRootDir() . '/' . $baseName;
                $this->get('knp_snappy.pdf')->generateFromHtml($content, $uploadFile);
                $patientFile->removeFile();
                $patientFile->setDescription($fileName.'.pdf');
                $patientFile->setParsedDescription($baseName);
                $em->flush();

                $this->faxEmail(array(
                    'patient' => $patient,
                    'letter_type' => $faxTranOutBound->getPatientLetter()->getLetterType(),
                    'uploadedFile' => $uploadFile
                ));


                $result['success'] = true;
                $result['msg'] = 'Confirmation received.';
            }
        }

        $logData = '[' . date('Y-m-d H:i:s') . ']';
        $logData .= ' Post Data: ' . json_encode($faxDetails);
        $logData .= '[' . date('Y-m-d H:i:s') . ']';

        $logFileName = $this->getParameter('fax_api_log_dir') . '/notify/fax_notify.log';
        if(file_exists($logFileName)){
            $logFile = fopen($logFileName, "a+");
            fwrite($logFile, PHP_EOL . $logData);
        }else{
            $logFile = fopen($logFileName, "w");
            fwrite($logFile, $logData);
        }
        fclose($logFile);
        $logSize = $this->getParameter('api_log_max_size');
        if($logSize >= $this->getParameter('api_log_max_size')) {
            rename($logFileName, $this->getParameter('fax_api_log_dir') . '/notify/fax_notify' . '-' . date('Y-m-d-H-i-s') . '.log');
        }

        return new JsonResponse($result);

    }

    public function faxEmail($params) {

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

        $patient = $params['patient'];
        $emails = $em->getRepository(LetterTemplateEntity::class)->findOneBy(array(
            'letterType' => $params['letter_type']
        ));

        $sysParam = $em->getRepository(SystemParameterEntity::class)->findOneBy(array(
            'description' => 'Email Sender'
        ));

        $recipients = array();
        foreach ($emails->getLetterTemplateEmails() as $email) {
            $recipients[] = $email->getEmail();
        }

        $mailer = $this->get('mailer');
        $message = $mailer->createMessage()
            ->setSubject($patient->getFullName().' - '.$params['letter_type'])
            ->setFrom($sysParam->getValue())
            ->setTo($recipients)
            ->attach(\Swift_Attachment::fromPath($params['uploadedFile']))
            ->setBody(
                $this->renderView('@RxConnexion/Patient/email.html.twig', array(
                    'patient' => $patient,
                    'letterTemplate' => $emails
                )),
                'text/html'
            );
        $mailer->send($message);
    }

    /**
     * @Route(
     *      "/patient_email/send/{patientEmail_id}",
     *      name = "patient_email_send"
     * )
     */
    public function sendPatientEmail(Request $request, $patientEmail_id) {

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

        $emailRecipient = array();

        //GET EMAIL
        $patientEmail = $em->getRepository(PatientEmailEntity::class)->findOneBy(array(
            'id' => base64_decode($patientEmail_id)
        ));

        $emailRecipient[] = $patientEmail->getEmail();

        if($patientEmail->getPatientEmailCcs()) {
            foreach ($patientEmail->getPatientEmailCcs() as $emailCc) {
                $emailRecipient[] = $emailCc->getEmail();
            }
        }

        $mailer = $this->get('mailer');
        $message = $mailer->createMessage()
            ->setSubject($patientEmail->getPatient()->getFullName())
            ->setFrom($patientEmail->getEmailFrom())
            ->setTo($emailRecipient)
            ->setBody(
                $this->renderView('@RxConnexion/Patient/patient_email_body.html.twig', array(
                    'patient' => $patientEmail->getPatient(),
                    'patientEmail' => $patientEmail
                )),
                'text/html'
            );

        if(count($patientEmail->getPatientEmailFiles()) > 0) {
            foreach ($patientEmail->getPatientEmailFiles() as $patientEmailFile) {
                $message->attach(\Swift_Attachment::fromPath($patientEmailFile->getUploadRootDir() . '/' .$patientEmailFile->getParsedFileDesc())->setFilename($patientEmailFile->getFileDesc()));
            }
        }

        $mailer->send($message);
        $patientEmail->setStatus(PatientEmailEntity::PATIENT_EMAIL_STATUS_SENT);
        $em->flush();
        $this->get('session')->getFlashBag()->set('success_messages', 'Email Successfully Sent.');

        return $this->redirect($this->generateUrl('patient_detail',array(
            'patient_id' => base64_encode($patientEmail->getPatient()->getId()),
        )), 302);
    }


    /*============================================================*/
    /*=============== PRIVATE FUNCTIONS ==========================*/
    /*============================================================*/

    private function check_financing_billing_today($patient){
        $em = $this->getDoctrine()->getManager();
        $dateToday = new \DateTime();
        $today = $dateToday->format('m/d/Y');
        $dayToday = $dateToday->format('d');
        $patientBillingFinancingPaymentDetails = array();
        $ctr = 0;

        $patientBillings = $patient->getPatientBillings();
        foreach($patientBillings as $patientBilling){
            if($patientBilling->getPayerType() === PatientBillingEntity::PAYER_TYPE_FINANCING && $patientBilling->getBillingStatus() === PatientBillingEntity::BILLING_STATUS_PENDING_PAYMENT){
                if($patientBilling->getPatientBillingFinancingPaymentDetail()){
                    $patientBillingFinancingPaymentDetails[] = $patientBilling->getPatientBillingFinancingPaymentDetail();
                }
            }
        }

        foreach($patientBillingFinancingPaymentDetails as $patientBillingFinancingPaymentDetail){
            $patientPayments = $em->getRepository('RxConnexionBundle:PatientPaymentEntity')->findFinancingPaymentForThisMonth($patient->getId(), $patientBillingFinancingPaymentDetail->getPatientBilling()->getId() );
            if(count($patientPayments) <= 0){

                if($patientBillingFinancingPaymentDetail->getPaymentDay() == $dayToday){
                    $startDate = $patientBillingFinancingPaymentDetail->getStartDate();
                    $endDate = $patientBillingFinancingPaymentDetail->getEndDate();

                    if (($today >= $startDate->format('m/d/Y')) && ($today <= $endDate->format('m/d/Y'))){
                        $patientBillingEntity = $patientBillingFinancingPaymentDetail->getPatientBilling();
                        $patientPayment = new PatientPaymentEntity();
                        $patientPayment->setPatient($patient);
                        $patientPayment->setPatientBilling($patientBillingEntity);
                        $patientPayment->setPayType('Cash');
                        $patientPayment->setPayDate($today);
                        $patientPayment->setAmount($patientBillingFinancingPaymentDetail->getAmount());
                        $patientPayment->setBillDueAmount($patientBillingEntity->getAmountDue());
                        $patientPayment->setBillPaidAmount($patientBillingEntity->getAmountPaid());
                        $patientPayment->setBillBalAmount($patientBillingEntity->getAmountBalance());
                        $patientPayment->setNote(PatientPaymentEntity::PAYMENT_AUTO_GENERATED_NOTE_FOR_FINANCING);
                        $patientPayment->setPaymentStatus(PatientPaymentEntity::PAYMENT_STATUS_PENDING);
                        $em->persist($patientPayment);
                        $ctr++;
                    }
                }
            }
        }
        $em->flush();

        return $ctr;

    }


}
