<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\FaxTranEntity;
use RxConnexionBundle\Entity\FileTypeEntity;
use RxConnexionBundle\Entity\PatientFileEntity;
use RxConnexionBundle\Entity\PatientHealthFacilityEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\PatientReferringHealthFacilityEntity;
use RxConnexionBundle\Entity\PatientReferringProviderEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityProviderEntity;
use RxConnexionBundle\Entity\ReferredByPatientEntity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

use RxConnexionBundle\Entity\ReferralEntity;
use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Entity\PatientServiceEntity;
use RxConnexionBundle\Entity\PatientEntity;
use RxConnexionBundle\Entity\ReferralServiceEntity;
use RxConnexionBundle\Form\ReferralForm;

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

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

        $monthNow = date('n');
        $yearNow = date('Y');
        $yr=$yearNow;
        $monthFilter = array();
        $i = 0;
        for ($m=$monthNow; $m > $monthNow-12; $m--) {
            if($m < 1){
                $yr = $yearNow-1;
            }
            $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
            $monthFilter[$i]['display'] = $yr.' - '.$month;
            $monthFilter[$i]['value'] = $yr.'|'.abs($m);
            $i++;
        }

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

    /**
     * @Route("/ajax_list", name="referral_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 Referral Update'), false);

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

            foreach($data['results'] as $row) {
                $id = base64_encode($row['id']);
                $action = '';

                if($hasUpdate) {
                    $url = $this->generateUrl('referral_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }
                $values = array(
                    $row['referral_date'],
                    $row['full_name'],
                    $row['branch'],
                    $row['gender'],
                    $row['birthDate'],
                    $row['address'],
                    $row['referring_provider'],
                    $row['referring_health_facility'],
//                    $hasPendingApproval ? "<a href='javascript:void(0)' class='action-button-style href-referral-patient-approval-form' data-id='$id'>Approve</a>" : ($row['is_approved'] === '1' ? 'Approved' : 'Denied'),
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}/{faxTranId}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0,
     *          "faxTranId": "0"
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referral_form"
     * )
     */
    public function formAction($action, $id, $faxTranId, Request $request) {

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

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

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

        $service = $em->getRepository('RxConnexionBundle:ServiceEntity')->findAll();
        if(count($service)){
            foreach ($service as $services){
                $referralService = $referral->getReferralServiceByServiceId($services->getId());
                if(!$referralService){
                    $referralService = new ReferralServiceEntity();
                    $referralService->setService($services);
                    $referral->addReferralService($referralService);
                }
            }
        }

        if($faxTranId != '0') {
            $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($faxTranId);
            $referral->setHealthFacility($faxTran->getHealthFacility());
        }

        /*$faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($faxTranId);
        $remote_id = $faxTran->getRemoteId();*/
        $formOptions = array('action' => $action, 'faxTranId' => $faxTranId);
        $form = $this->createForm(ReferralForm::class, $referral, $formOptions);

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

            $referral_form = $request->get($form->getName());
            $result = $this->processForm($referral_form, $referral, $form, $request);
            if($result['success']) {
                if($result['redirect'] === 'index') {
                    return $this->redirect($this->generateUrl('referral'), 302);
                } else if($result['redirect'] === 'form') {
                    return $this->redirect($this->generateUrl('referral_form', array(
                        'action' => 'u',
                        'id' => base64_encode($result['id'])
                    )), 302);
                } else if($result['redirect'] === 'form with error') {
                    return $this->redirect($this->generateUrl('referral_form'), 302);
                }
            } else {
                $form->submit($referral_form, false);
                return $this->redirect($this->generateUrl('referral_form'), 302);
            }
        }

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

        return $this->render('@RxConnexion/Referral/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/referral/referral_form.js?v=1.0.3'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'faxTranId' => $faxTranId
        ));
    }

    private function processForm($referral_form, $referral, $form, Request $request) {
        $oldNote = $referral->getNote() ? $referral->getNote() : '';
        $em = $this->getDoctrine()->getManager();
        $errors = $em->getRepository('RxConnexionBundle:ReferralEntity')->validate($referral_form);
        $srFax = $this->get('rx_connexion.SRFaxService');
//        var_dump($referral_form['patientServices']);
//        die();
        if(!count($errors)) {

            switch($referral_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);
                    if ($form->isValid()) {
                        $newNote = $referral->getNote();
                        $referringHealthProviderHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->findOneBy(array(
                            'referringHealthFacility' => $referral_form['referringHealthFacility_id'],
                            'referringProvider' => $referral_form['referringProvider_id']
                        ));
                        if(!$referringHealthProviderHealthFacility){
                            $referringHealthProviderHealthFacility = new ReferringHealthFacilityProviderEntity();
                            $referringHealthProviderHealthFacility->setReferringProvider($referral->getReferringProvider());
                            $referringHealthProviderHealthFacility->setReferringHealthFacility($referral->getReferringHealthFacility());
                            $referringHealthProviderHealthFacility->setStartDate(date('m/d/Y'));
                            $em->persist($referringHealthProviderHealthFacility);
                        }

                        if($referral_form['fax_tran'] == "0"){
                            $referral->setFaxTran(null);
                        }

                        $em->persist($referral);
                        $patient = new PatientEntity();
                        $patient->setFirstName($referral->getFirstName());
                        $patient->setMiddleName($referral->getMiddleName());
                        $patient->setLastName($referral->getLastName());
                        $patient->setGender($referral->getGender());
                        $patient->setBirthDate($referral->getBirthDateAsString());
                        $patient->setReferralDate($referral->getReferralDateAsString());
                        if($referral->getFaxTran()){
                            $patient->setReceivedDate($referral->getFaxTran()->getFaxDateAsString());
                        }
                        $patient->setCity($referral->getCity());
                        $patient->setStreet($referral->getStreet());
                        $patient->setPostalCode($referral->getPostalCode());
                        $patient->setMobileNo($referral->getMobileNo());
                        $patient->setMobileNoTwo($referral->getMobileNoTwo());
                        $patient->setMobileNoThree($referral->getMobileNoThree());
                        $patient->setPhoneNo($referral->getPhoneNo());
                        $patient->setPhoneNoTwo($referral->getPhoneNoTwo());
                        $patient->setPhoneNoThree($referral->getPhoneNoThree());
                        $patient->setEmail($referral->getEmail());
                        $patient->setEmailTwo($referral->getEmailTwo());
                        $patient->setEmailThree($referral->getEmailThree());
                        $patient->setPersonalHealthNo($referral->getPersonalHealthNo());
                        $patient->setIsActive(true);
                        $patient->setReferral($referral);
                        $patient->setHealthFacility($referral->getHealthFacility());
                        $patient->setSource($referral->getSource());

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

                        $patient->setIsDuplicate(false);
                        $patient->setIsSpecialist(false);
                        $patient->setIsTestPatient(false);

                        $em->persist($patient);

                        if(isset($referral_form['healthFacility'])) {
                            $patientHealthFacility = new PatientHealthFacilityEntity();
                            $patientHealthFacility->setPatient($patient);
                            $patientHealthFacility->setHealthFacility($em->getReference('RxConnexionBundle:HealthFacilityEntity', $referral_form['healthFacility']));
                            $patientHealthFacility->setStartDate(date('Y/m/d'));
                            $patientHealthFacility->setEndDate(null);
                            $em->persist($patientHealthFacility);
                        }

                        if(isset($referral_form['referralServices'])) {
                            foreach ($referral_form['referralServices'] as $rService) {
                                if(isset($rService['is_checked'])) {
                                    $patientServices = new PatientServiceEntity();
                                    $patientServices->setPatient($patient);
                                    $patientServices->setStartDate(date('Y/m/d'));
                                    $patientServices->setEndDate(null);
                                    $patientServices->setPatientServiceType('Others');
                                    $patientServices->setService($em->getReference('RxConnexionBundle:ServiceEntity', $rService['service']));
                                    $em->persist($patientServices);
                                }
                            }
                        }

                        /*
                        $patientFile = new PatientFileEntity();
                        $patientFile->setNote('Received Referral');
                        $patientFile->setPatient($patient);
                        $em->persist($patientFile);
                        $em->flush();


                        $faxNo = $this->getParameter('srfax_caller_id');
                        if($referral->getFaxTran()){
                            if ($referral->getFaxTran()->getRemoteId() != '' && $referral->getFaxTran()->getRemoteId() != null){
                                $faxNo = $referral->getFaxTran()->getRemoteId();
                            }
                        }

                        $content = $this->renderView('@RxConnexion/Referral/FaxTemplate/Acknowledgement.wkpdf.twig', array(
                            'referral' => $referral,
                            'dateToday' => date('F j, Y'),
                            'receiverFax' => $faxNo
                        ));
                        $receiver = preg_replace("/[^0-9]/", "", $faxNo );
                        $fileName = $referral->getReferringProvider()->getFullName() . uniqid() . ' - Acknowledgement';
                        $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content);
                        $srFax->Queue_Fax(array(
                            'sFaxType'         =>  $srFax::FAX_TYPE_SINGLE, // Single Fax
                            'sToFaxNumber'     =>  $receiver ,
                            'sFileName_1'      =>  $fileName,
                            'sFileContent_1'   =>  base64_encode($xml)
                        ));
                        if($srFax->getRequestStatus()){
                            $srFax->Get_FaxStatus(array(
                                'sFaxDetailsID' => $srFax->getRequestResponse()
                            ));
                            $response = $srFax->getRequestResponse();
                            $fileNameArr = explode('|',$response->FileName);
                            $fileName = $fileNameArr[0];
                            $faxDetails = array(
                                'fileName' => $response->FileName,
                                'sentStatus' => $response->SentStatus,
                                'dateQueued' => $response->DateQueued,
                                'dateSent' => $response->DateSent,
                                'toFaxNumber' => $response->ToFaxNumber,
                                'pages' => 1
                            );
                            $content = $this->renderView('@RxConnexion/Referral/FaxTemplate/FaxReceipt.wkpdf.twig', array(
                                'response   ' => $faxDetails
                            ));
                            $fileName = 'Referral Acknowledgement -' .uniqid() . ' - Fax Confirmation';
                            $xml = $this->get('knp_snappy.pdf')->getOutputFromHtml($content);
                            $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);
                            $receiver = $this->getParameter('srfax_caller_id');
                            $srFax->Queue_Fax(array(
                                'sFaxType'         =>  $srFax::FAX_TYPE_SINGLE, // Single Fax
                                'sToFaxNumber'     =>  $receiver ,
                                'sFileName_1'      =>  $fileName,
                                'sFileContent_1'   =>  base64_encode($xml)
                            ));
                        }
                        */

                        if($referral_form['note'] != '' || $referral_form['note'] != null){
                            if($oldNote != $newNote){
                                $patientNote = new PatientNoteEntity();
                                $patientNote->setType(PatientNoteEntity::TYPE_CLINICAL);
                                $patientNote->setNote($referral_form['note']);
                                $patientNote->setPatient($patient);
                                $em->persist($patientNote);
                            }
                        }

                        /** NOTE: THIS IS FOR ADDING THE FAXTRAN INSIDE THE PATIENTFILE */
                        if(isset($referral_form['fax_tran'])){
                            $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($referral_form['fax_tran']);
                            $fileType = $em->getRepository('RxConnexionBundle:FileTypeEntity')->findOneBy(array('description'=>'Referral Fax'));
                            /** NOTE: if there is no "Referral Fax" in file_type, add it so that we can use it in relationship */
                            if(!$fileType){
                                $fileType = new FileTypeEntity();
                                $fileType->setDescription('Referral Fax');
                                $fileType->setCode('Referral Fax');
                                $em->persist($fileType);
                            }
                            if($faxTran && $referral_form['fax_tran'] != "0"){
                                $patientFile = new PatientFileEntity();
                                $patientFile->setPatient($patient);
                                $patientFile->setFileType($fileType);
                                $patientFile->setDescription($faxTran->getFileName().'.pdf');
                                $patientFile->setParsedDescription($faxTran->getFileName().'.pdf');
                                $patientFile->setNote('File from fax received');
                                $em->persist($patientFile);

                                /** NOTE: Set Fax_Status of the fax to "Closed" */
                                if($faxTran){
                                    $faxTran->setFaxStatus(1);
                                    $em->persist($faxTran);
                                }
                            }
                        }

                        /** NOTE: UPLOAD FILE TO PATIENT_FILE IF THERE IS FILE UPLOAD */
                        if(isset($_FILES['form']) && !empty($_FILES['form']['tmp_name']['file'])) {
                            $fileType = $em->getRepository('RxConnexionBundle:FileTypeEntity')->findOneBy(array('description'=>'Referral Form'));
                            /** NOTE: if there is no "Referral Form" in file_type, add it so that we can use it in relationship */
                            if(!$fileType){
                                $fileType = new FileTypeEntity();
                                $fileType->setDescription('Referral Form');
                                $fileType->setCode('Referral Form');
                                $em->persist($fileType);
                            }
                            $patientFile = new PatientFileEntity();
                            $patientFile->setPatient($patient);
                            $patientFile->setFileType($fileType);
                            $patientFile->setNote('File from referral');
                            $em->persist($patientFile);

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

                        $patientReferringProvider = new PatientReferringProviderEntity();
                        $patientReferringProvider->setPatient($patient);
                        $patientReferringProvider->setReferringProvider($referral->getReferringProvider());
                        $patientReferringProvider->setStartDate(date('Y-m-d 00:00:00'));
                        $em->persist($patientReferringProvider);

                        $patientReferringHealthFacility = new PatientReferringHealthFacilityEntity();
                        $patientReferringHealthFacility->setPatient($patient);
                        $patientReferringHealthFacility->setReferringHealthFacility($referral->getReferringHealthFacility());
                        $patientReferringHealthFacility->setStartDate(date('Y-m-d 00:00:00'));
                        $em->persist($patientReferringHealthFacility);

                        $em->flush();
                        $newAT = new AuditTrailEntity(
                            'Referral',
                            $em->getClassMetadata(ReferralEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referral;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();
                        $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'] = 'index';

                    } else {

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

                    break;

                case 'u': // update
                    //TODO:Update record hindi nag-create ng bagong health facility at provider pag inaalis yung ID both

                    $newAT = new AuditTrailEntity(
                        'Referral',
                        $em->getClassMetadata(ReferralEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referral;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $newNote = $referral->getNote();
                        $referringHealthProviderHealthFacility = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityProviderEntity')->findOneBy(array(
                            'referringHealthFacility' => $referral_form['referringHealthFacility_id'],
                            'referringProvider' => $referral_form['referringProvider_id']
                        ));
                        if(!$referringHealthProviderHealthFacility){
                            $referringHealthProviderHealthFacility = new ReferringHealthFacilityProviderEntity();
                            $referringHealthProviderHealthFacility->setReferringProvider($referral->getReferringProvider());
                            $referringHealthProviderHealthFacility->setReferringHealthFacility($referral->getReferringHealthFacility());
                            $referringHealthProviderHealthFacility->setStartDate(date('m/d/Y'));
                            $em->persist($referringHealthProviderHealthFacility);
                        }

                        if($referral_form['fax_tran'] == "0"){
                            $referral->setFaxTran(null);
                        }

                        $newAT->parseDetails();
                        $em->persist($newAT);
                        if($referral->getPatient()){
                            if($referral_form['note'] != '' || $referral_form['note'] != null){
                                if($oldNote != $newNote){
                                    $patientNote = new PatientNoteEntity();
                                    $patientNote->setType(PatientNoteEntity::TYPE_CLINICAL);
                                    $patientNote->setNote($referral_form['note']);
                                    $patientNote->setPatient($referral->getPatient());
                                    $em->persist($patientNote);
                                }
                            }
                        }

                        $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(
                        'Referral',
                        $em->getClassMetadata(ReferralEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referral;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $faxTran = $em->getRepository('RxConnexionBundle:FaxTranEntity')->find($referral_form['fax_tran']);
                        /** NOTE: Set Fax_Status of the fax to "Active" */
                        if($faxTran){
                            $faxTran->setFaxStatus(0);
                            $em->persist($faxTran);
                        }


                        $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(
     *      "/approval/form/{id}",
     *      defaults = {
     *          "id": 0
     *      },
     *      name = "referral_approval_form"
     * )
     */
    public function referral_approval_formAction($id) {

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

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

        $referral = $em->getRepository('RxConnexionBundle:ReferralEntity')->find(base64_decode($id));

        $title = 'Approve ' . $referral->getFullName();

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

    /**
     * @Route(
     *      "/approval/form_action",
     *      name = "referral_approval_action"
     * )
     */
    public function referral_approval_form_actionAction(Request $request) {

        $result['success'] = false;
        $result['successMessages'] = array();
        $result['errorMessages'] = array();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        $form = $request->get('form');
        $em = $this->getDoctrine()->getManager();
        $referral = $em->getRepository('RxConnexionBundle:ReferralEntity')->find(base64_decode($form['id']));

        $referral->setIsApproved(true);

        $patient = new PatientEntity();
        $patient->setFirstName($referral->getFirstName());
        $patient->setMiddleName($referral->getMiddleName());
        $patient->setLastName($referral->getLastName());
        $patient->setGender($referral->getGender());
        $patient->setBirthDate($referral->getBirthDateAsString());
        $patient->setCity($referral->getCity());
        $patient->setStreet($referral->getStreet());
        $patient->setPostalCode($referral->getPostalCode());
        $patient->setMobileNo($referral->getMobileNo());
        $patient->setMobileNoTwo($referral->getMobileNoTwo());
        $patient->setMobileNoThree($referral->getMobileNoThree());
        $patient->setPhoneNo($referral->getPhoneNo());
        $patient->setPhoneNoTwo($referral->getPhoneNoTwo());
        $patient->setPhoneNoThree($referral->getPhoneNoThree());
        $patient->setEmail($referral->getEmail());
        $patient->setEmailTwo($referral->getEmailTwo());
        $patient->setEmailThree($referral->getEmailThree());
        $patient->setReferral($referral);
        $em->persist($patient);
        $em->flush();

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

        return new JsonResponse($result);
    }

    //TODO: referral_denied function




}
