<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ChartStatusEntity;
use RxConnexionBundle\Entity\PatientChartEntity;
use RxConnexionBundle\Entity\PatientChartNoteEntity;
use RxConnexionBundle\Entity\PatientChartTypeMethodEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityChartEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityChartNoteEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityNoteEntity;
use RxConnexionBundle\Entity\ReferringProviderChartEntity;
use RxConnexionBundle\Entity\ReferringProviderChartNoteEntity;
use RxConnexionBundle\Entity\ReferringProviderNoteEntity;
use RxConnexionBundle\Entity\ScheduleStatusEntity;
use RxConnexionBundle\Form\MarketingStaffScheduleForCalendarForm;
use RxConnexionBundle\Form\MarketingStaffScheduleForm;
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\MarketingStaffScheduleEntity;
use RxConnexionBundle\Form\ScheduleForm;
use RxConnexionBundle\Entity\AuditTrailEntity;

use RxConnexionBundle\Form\ScheduleForCalendarForm;


/**
 * @Route("/main/marketing_staff_appointment")
 */
class MarketingStaffScheduleController extends Controller
{
    /**
     * @Route("", name="marketing_staff_schedule")
     */
    public function indexAction() {

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

        return $this->render('@RxConnexion/MarketingStaffSchedule/index.html.twig', array(
            'title' => 'Manage Marketing Staff Appointment',
            'page_title' => 'Manage Marketing Staff Appointment',
            'javascripts' => array('rxconnexion/admin/js/marketingStaffSchedule/marketingStaffSchedule.js?v=1.0.3')
        ));
    }

    /**
     * @Route("/ajax_list", name="marketing_staff_schedule_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 Marketing Staff Schedule Update'), false);

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

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

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

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

                $values = array(
                    $row['account_desc'],
                    $row['id'],
                    $row['health_facility_desc'],
                    $row['patient_fullName'],
                    $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);
    }

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

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

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

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

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

            $schedule_form = $request->get($form->getName());
            $result = $this->processForm($schedule_form, $schedule, $form, $request);

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

        $title = ($action === 'n' ? 'New' : 'Update') . ' Marketing Staff Appointment';

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

    private function processForm($schedule_form, $schedule, $form, Request $request) {

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

        if(!count($errors)) {

            switch($schedule_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $em->persist($schedule);
                        $patientChart = new PatientChartEntity();
                        $patientChart->setMarketingStaffSchedule($schedule);
                        $patientChart->setHealthFacility($schedule->getHealthFacility());
                        $patientChart->setMarketingStaff($schedule->getMarketingStaff());
                        $patientChart->setPatient($schedule->getPatient());
                        $patientChart->setChartType($schedule->getChartType());
                        $patientChart->setChartDate($schedule->getScheduleDateAsString());
                        $em->persist($patientChart);
                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Appointment',
                            $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $schedule;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();

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

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

                    } else {

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

                    break;

                case 'u': // update

                    $newAT = new AuditTrailEntity(
                        'Appointment',
                        $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $schedule;
                    $newAT->parseOriginalDetails();

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

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

                    } else {

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

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Appointment',
                        $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_NEW
                    );
                    $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("/calendar", name="marketing_staff_calendar_appointment")
     */
    public function calendarAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Marketing Staff Calendar'))) return $authService->redirectToHome();
        $userData = $this->get('session')->get('userData');

        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('RxConnexionBundle:AccountUserEntity')->find($userData['id']);
        $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findBy(array(
            'isActive' => true,
            'isDeleted' => false,
        ));
        $hfLatLngDetails = array();
        foreach($healthFacilities as $healthFacility){
            if($healthFacility->getGeoLatitude() != '' && $healthFacility->getGeoLatitude() != null && $healthFacility->getGeoLongitude() != '' && $healthFacility->getGeoLongitude() != null)
                $hfLatLngDetails[] = array(
                    'description' => $healthFacility->getDescription(),
                    'latLng' => $healthFacility->getGeoLatitude() . ', ' . $healthFacility->getGeoLongitude()
                );
        }

        /*$healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->findAllNotDeletedAndHasPatient($userData);
        $hfLatLngDetails = array();
        foreach($healthFacilities as $healthFacility){
            if($healthFacility['geo_latitude'] != '' && $healthFacility['geo_latitude'] != null && $healthFacility['geo_longitude'] != '' && $healthFacility['geo_longitude'] != null)
                $hfLatLngDetails[] = array(
                    'description' => $healthFacility['description'],
                    'latLng' => $healthFacility['geo_latitude'] . ', ' . $healthFacility['geo_longitude']
                );
        }*/


        return $this->render('@RxConnexion/MarketingStaffSchedule/calendar.html.twig', array(
            'title' => 'Marketing Staff Appointment Calendar',
            'page_title' => 'Marketing Staff Appointment Calendar',
            'googleMapApiKey' => $this->container->getParameter('google_map_api_key'),
            'stylesheets' => array('rxconnexion/admin/css/schedule/calendar.css?v=1.0.3'),
            'javascripts' => array('rxconnexion/admin/js/marketingStaffSchedule/calendar.js?v=1.1.1'),
            'healthFacilities' => $healthFacilities,
            'hfLatLongs' => $hfLatLngDetails,
            'userData' => $userData,
            'hasBackToTop' => true,
            'noteTemplateAccess' => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
            'defaultHealthFacility' => (($userData['type'] === 'Marketing Staff' && $user->getMarketingStaff()) ? $user->getMarketingStaff()->getDefaultMarketingStaffHealthFacilityId() : '')
        ));
    }

    /**
     * @Route("/calendar/view", name="marketing_staff_schedule_view")
     */
    public function calendar_viewAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) {
            return new JsonResponse(array('result' => false));
        }

        $get = $request->query->all();
        $em = $this->getDoctrine()->getManager();
//        $providers = $em->getRepository('RxConnexionBundle:ProviderEntity')-> scheduleCalendarViewProviders($get['healthFacility_id'], $get['date']);
        $marketingStaffs = $em->getRepository('RxConnexionBundle:MarketingStaffEntity')-> scheduleCalendarViewMarketingStaffs($get['healthFacility_id'], $get['date']);
        $schedules = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleEntity')-> scheduleCalendarViewSchedules($get['healthFacility_id'], $get['date']);

        $dayName = date('l', strtotime($get['date']));
        $times = array();
        $patient_id = null;

        for($i=6; $i<=20; $i++) {
            for($ii=0; $ii<60; $ii+=15) {
                //$scheds = array();
                $hm = sprintf('%002d', $i) . ':' . sprintf('%002d', $ii);
                $dt = strtotime($get['date'] . ' ' . $hm);
                $text = date('h:i A', $dt);
                $dtEnd = strtotime('+14 minute', $dt);
                foreach($schedules as $schedule){
                    if(in_array(strtoupper($schedule['scheduleStatus']), array('NO SHOW', 'CANCELLED', 'RESCHEDULED'))) {
                        continue;
                    }
                    $sDT = strtotime($schedule['scheduleDT']);
                    $sDTEnd = strtotime($schedule['scheduleDTEnd']);

                    if(($sDT >= $dt && $sDT <= $dtEnd) || ($sDTEnd > $dt && $sDT <= $dt)){

                        foreach ($marketingStaffs as $key => $marketingStaff){
                            if($marketingStaff['id'] != $schedule['marketingStaffId']){
                                continue;
                            }
                            if(isset($marketingStaffs[$key]['schedules'])){
                                $found = false;
                                foreach($marketingStaffs[$key]['schedules'] as $key2 => $marketingStaffSchedule){
                                    if($marketingStaffSchedule['id'] == $schedule['id']){
                                        $marketingStaffs[$key]['schedules'][$key2]['rowSpan']++;
                                        $marketingStaffs[$key]['schedules'][$key2]['rowSpanTimes'][] = $text;
                                        $found = true;
                                        break;
                                    }
                                }

                                if(!$found){
                                    $schedule['timeText'] = $text;
                                    $schedule['rowSpan'] = 1;
                                    $schedule['rowSpanTimes'] = array();
                                    $marketingStaffs[$key]['schedules'][] = $schedule;
                                }
                            }else{
                                $schedule['timeText'] = $text;
                                $schedule['rowSpan'] = 1;
                                $schedule['rowSpanTimes'] = array();
                                $marketingStaffs[$key]['schedules'] = array($schedule);
                            }
                        }
                        //$scheds[] = $schedule;
                    }

                }
                // Schedules no show and cancelled
                foreach($schedules as $schedule){
                    if(!in_array(strtoupper($schedule['scheduleStatus']), array('NO SHOW', 'CANCELLED', 'RESCHEDULED'))) {
                        continue;
                    }
                    $sDT = strtotime($schedule['scheduleDT']);
                    $sDTEnd = strtotime($schedule['scheduleDTEnd']);
                    if(($sDT >= $dt && $sDT <= $dtEnd) || ($sDTEnd > $dt && $sDT <= $dt)){
                        foreach ($marketingStaffs as $key => $marketingStaff){
                            if($marketingStaff['id'] != $schedule['marketingStaffId']){
                                continue;
                            }
                            if(isset($marketingStaffs[$key]['schedulesNSC'])){
                                $found = false;
                                foreach($marketingStaffs[$key]['schedulesNSC'] as $key2 => $marketingStaffSchedule){
                                    if($marketingStaffSchedule['id'] == $schedule['id']){
                                        $marketingStaffs[$key]['schedulesNSC'][$key2]['rowSpan']++;
                                        $marketingStaffs[$key]['schedulesNSC'][$key2]['rowSpanTimes'][] = $text;
                                        $found = true;
                                        break;
                                    }
                                }
                                if(!$found){
                                    $schedule['timeText'] = $text;
                                    $schedule['rowSpan'] = 1;
                                    $schedule['rowSpanTimes'] = array();
                                    $marketingStaffs[$key]['schedulesNSC'][] = $schedule;
                                }
                            }else{
                                $schedule['timeText'] = $text;
                                $schedule['rowSpan'] = 1;
                                $schedule['rowSpanTimes'] = array();
                                $marketingStaffs[$key]['schedulesNSC'] = array($schedule);
                            }
                        }
                    }
                }
                foreach ($marketingStaffs as $key => $marketingStaff) {
                    $workSchedules = array(
                        'regular' => array(),
                        'irregular' => array(),
                        'out' => array()
                    );
                    if(!isset($marketingStaffs[$key]['workSchedules'])){
                        $marketingStaffs[$key]['workSchedules'] = $workSchedules;
                    }
                    $marketingStaffWorkSchedules = explode('@', $marketingStaff['marketingStaffWorkSchedules']);
                    foreach ($marketingStaffWorkSchedules as $marketingStaffWorkSchedule) {
                        $workSchedule = explode('|', $marketingStaffWorkSchedule);
                        switch ($workSchedule[0]) {
                            case 'Regular' :
                                $workSchedules['regular'][] = array(
                                    'type' => $workSchedule[0],
                                    'dayName' => $workSchedule[1],
                                    'timeFrom' => $workSchedule[2],
                                    'timeTo' => $workSchedule[3],
                                    'healthFacility' => $workSchedule[4],
                                );
                                break;

                            case 'Irregular':
                                $workSchedules['irregular'][] = array(
                                    'type' => $workSchedule[0],
                                    'fromDate' => $workSchedule[1],
                                    'toDate' => $workSchedule[2],
                                    'timeFrom' => $workSchedule[3],
                                    'timeTo' => $workSchedule[4],
                                    'healthFacility' => $workSchedule[5],
                                );

                                break;

                            case 'Out':
                                $workSchedules['out'][] = array(
                                    'type' => $workSchedule[0],
                                    'fromDate' => $workSchedule[1],
                                    'toDate' => $workSchedule[2],
                                    'timeFrom' => $workSchedule[3],
                                    'timeTo' => $workSchedule[4],
                                );

                                break;

                        }
                    }
                    foreach ($workSchedules['out'] as  $wsOut){
                        $outTimeFromDT = strtotime($get['date'] . ' ' . $wsOut['timeFrom']);
                        $outTimeToDT = strtotime($get['date'] . ' ' . $wsOut['timeTo']);
                        if($dt >= $outTimeFromDT && $dt < $outTimeToDT){
                            $marketingStaffs[$key]['workSchedules']['out'][] = $text;
                        }
                    }

                    foreach ($workSchedules['irregular'] as  $wsIrregular){
                        $regularTimeFromDT = strtotime($get['date'] . ' ' . $wsIrregular['timeFrom']);
                        $regularTimeToDT = strtotime($get['date'] . ' ' . $wsIrregular['timeTo']);
                        if($dt >= $regularTimeFromDT && $dt <= $regularTimeToDT){
                            $marketingStaffs[$key]['workSchedules']['irregular'][] = array(
                                'hfId' => $wsIrregular['healthFacility'],
                                'time' => $text
                            );
                        }
                    }

                    foreach ($workSchedules['regular'] as  $wsRegular){
                        $regularTimeFromDT = strtotime($get['date'] . ' ' . $wsRegular['timeFrom']);
                        $regularTimeToDT = strtotime($get['date'] . ' ' . $wsRegular['timeTo']);
                        if($dayName == $wsRegular['dayName'] && $dt >= $regularTimeFromDT && $dt <= $regularTimeToDT){
                            $marketingStaffs[$key]['workSchedules']['regular'][] = $text;
                        }
                    }
                }


                $times[] = array(
                    'text' => $text
                    //'schedules' => $scheds
                );
            }
        }

        $result['success'] = true;
        $result['html'] = $this->renderView(
            '@RxConnexion/MarketingStaffSchedule/calendar_view.html.twig', array(
                'marketingStaffs' => $marketingStaffs,
                'times' => $times,
                'healthFacility_id' => $get['healthFacility_id']
            )
        );

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/calendar/form",
     *      name = "marketing_staff_schedule_calendar_form"
     * )
     */
    public function schedule_calendar_formAction(Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Marketing Staff Schedule New', 'Admin Marketing Staff Schedule Update'))) return $authService->redirectToHome();

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

        $schedule = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleEntity')->find($get['id']);
        $marketingStaff = $em->getRepository('RxConnexionBundle:MarketingStaffEntity')->find($get['marketing_staff_id']);
        $healthFacility = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($get['healthFacility_id']);
        $marketingStaffFullName = $marketingStaff->getFullName();
        $healthFacilityName = $healthFacility->getDescription();
        $latestChartDetails = array();

        if($schedule){
            if ($schedule->getReferringHealthFacility()) {
                $latestChartDetails = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartEntity')->getReferringHealthFacilityLatestChart($schedule->getReferringHealthFacility()->getId(), $schedule->getReferringHealthFacilityChart()->getId());
                $result['latestPatientChartDetails'] = $latestChartDetails;
            } else {
                $latestChartDetails = $em->getRepository('RxConnexionBundle:ReferringProviderChartEntity')->getReferringProviderLatestChart($schedule->getReferringProvider()->getId(), $schedule->getReferringProviderChart()->getId());
                $result['latestPatientChartDetails'] = $latestChartDetails;
            }


        }
        if(!$schedule) {
            $schedule = new MarketingStaffScheduleEntity();
        }
        $times = explode(':', $get['start_time']);
        $time = explode(' ', $times[1]);
        $time[3] = $times[0];
        $formOptions = array(
            'healthFacility_id' => $get['healthFacility_id'],
            'healthFacility_city_id' => $healthFacility->getCity()->getId(),
            'healthFacility_geoLat' => $healthFacility->getGeoLatitude(),
            'healthFacility_geoLong' => $healthFacility->getGeoLongitude(),
            'marketingStaff_id' => $get['marketing_staff_id'],
            'schedDate' => $get['date'],
            'startTime' => $get['start_time'],
            'marketingStaffFullName' => $marketingStaffFullName,
            'healthFacilityName' => $healthFacilityName,
            'startTimeHour' => intval($time[3]),
            'startTimeMin' => $time[0],
            'startTimePeriod' => $time[1],
            'action' => $get['action']
        );
        $form = $this->createForm(MarketingStaffScheduleForCalendarForm::class, $schedule, $formOptions);


        $title = $get['action'] === 'n' ? 'New Appointment' : 'Update Appointment';

        $result['html'] =  $this->renderView('@RxConnexion/MarketingStaffSchedule/schedule_calendar_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'startTime' => $get['start_time'],
            'marketingStaffFullName' => $marketingStaffFullName,
            'healthFacilityName' => $healthFacilityName,
            'schedDate' => $get['date'],
            'form' => $form->createView(),
            'action' => $get['action'],
            'id' => $get['id'],
            'schedule' => $schedule,
            'latestChartDetails' => $latestChartDetails,
            'healthFacility' => $healthFacility
        ));
        if($schedule->getReferringHealthFacility()){
            $referringHealthFacility = $schedule->getReferringHealthFacility();
            $referringHealthFacilityDescription = $referringHealthFacility->getDescription();
            $url = $this->generateUrl('referring_health_facility_detail', array(
                'referringHealthFacility_id' => base64_encode($referringHealthFacility->getId())
            ));
            $referringHealthFacilityDetails = array(
                'patientName' => "<a href='$url' target='_blank'>$referringHealthFacilityDescription</a>",
                'address' => $referringHealthFacility->getAddress(),
                'mobileNos' => $referringHealthFacility->getMobileNo(),
                'phoneNos' => $referringHealthFacility->getPhoneNo(),
            );
            $result['patientDetails'] = $referringHealthFacilityDetails;
        } else if ($schedule->getReferringProvider()) {
            $referringProvider = $schedule->getReferringProvider();
            $referringProviderFullName = $referringProvider->getFullName();
            $url = $this->generateUrl('referring_provider_detail', array(
                'referringProvider_id' => base64_encode($referringProvider->getId())
            ));
            $referringHealthFacilityDetails = array(
                'patientName' => "<a href='$url' target='_blank'>$referringProviderFullName</a>",
                'address' => $referringProvider->getAddress(),
                'mobileNos' => $referringProvider->getMobileNo(),
                'phoneNos' => $referringProvider->getPhoneNo(),
            );
            $result['patientDetails'] = $referringHealthFacilityDetails;
        }
        $branchDetails = array(
            'address' => $healthFacility->getAddress(),
            'mobileNos' => $healthFacility->getConcatenatedMobileNo(),
            'phoneNos' => $healthFacility->getConcatenatedPhoneNo()
        );
        $result['success'] = true;
        $result['action'] = $get['action'];
        $result['branchDetails'] = $branchDetails;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/calendar_form/save_action",
     *      name = "marketing_staff_calendar_form_save"
     * )
     */
    public function calendar_form_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 Marketing Staff Schedule New', 'Admin Marketing Staff Schedule Update'))) return $authService->redirectToHome();
        $schedule_form = $request->get('marketingStaffScheduleForCalendar');
        $em = $this->getDoctrine()->getManager();
        $schedule = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleEntity')->find($schedule_form['id']);
        if(!$schedule){
            $schedule = new MarketingStaffScheduleEntity();
        };
        $formOptions = array(
            'healthFacility_id' => $schedule_form['health_facility'],
            'marketingStaff_id' => $schedule_form['marketingStaff'],
            'schedDate' => $schedule_form['schedule_date'],
            'startTime' => $schedule_form['start_time'],
            'action' => $schedule_form['action']
        );
        $form = $this->createForm(MarketingStaffScheduleForCalendarForm::class, $schedule, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleEntity')->validate($schedule_form);
        if(!count($errors)) {
            $oldNotes = $schedule->getNote();
            $oldChartType = $schedule->getChartType() ? $schedule->getChartType()->getId() : 0;
            switch($schedule_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {
                        $chartStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findOneBy(array(
                            'description' => $schedule->getMarketingStaffScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));
                        $em->persist($schedule);

                        if (isset($schedule_form['patient'])) {
                            $patient = $schedule->getPatient();

                            if(($patient->getGeoLat() == '' && $patient->getGeoLat() == null) || ($patient->getGeoLong() == '' && $patient->getGeoLong() == null)){
                                $patient->setGeoLat($schedule_form['patient_geoLat']);
                                $patient->setGeoLong($schedule_form['patient_geoLong']);
                            }
                            $patientChart = new PatientChartEntity();
                            $patientChart->setMarketingStaffSchedule($schedule);
                            $patientChart->setHealthFacility($schedule->getHealthFacility());
                            $patientChart->setMarketingStaff($schedule->getMarketingStaff());
                            $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();
                        }

                        if ($schedule_form['referringHealthFacility'] != '' || $schedule_form['referringHealthFacility'] != null) {
                            $referringHealthFacility = $schedule->getReferringHealthFacility();

//                            if(($referringHealthFacility->getGeoLat() == '' && $referringHealthFacility->getGeoLat() == null) || ($referringHealthFacility->getGeoLong() == '' && $patient->getGeoLong() == null)){
//                                $referringHealthFacility->setGeoLat($schedule_form['patient_geoLat']);
//                                $referringHealthFacility->setGeoLong($schedule_form['patient_geoLong']);
//                            }
                            $referringHealthFacilityChart = new ReferringHealthFacilityChartEntity();
                            $referringHealthFacilityChart->setMarketingStaffSchedule($schedule);
                            $referringHealthFacilityChart->setHealthFacility($schedule->getHealthFacility());
                            $referringHealthFacilityChart->setMarketingStaff($schedule->getMarketingStaff());
                            $referringHealthFacilityChart->setReferringHealthFacility($schedule->getReferringHealthFacility());
                            $referringHealthFacilityChart->setChartType($schedule->getChartType());
                            if($chartStatus){
                                $referringHealthFacilityChart->setChartStatus($chartStatus);
                            }
                            $referringHealthFacilityChart->setChartDate($schedule->getScheduleDateAsString());
                            $em->persist($referringHealthFacilityChart);
                            $referringHealthFacilityChartNote = new ReferringHealthFacilityChartNoteEntity();
                            $referringHealthFacilityChartNote->setReferringHealthFacilityChart($referringHealthFacilityChart);
                            $referringHealthFacilityChartNote->setNote($schedule->getNote());
                            $em->persist($referringHealthFacilityChartNote);
                            $referringHealthFacilityNote = new ReferringHealthFacilityNoteEntity();
                            $referringHealthFacilityNote->setReferringHealthFacility($schedule->getReferringHealthFacility());
                            $referringHealthFacilityNote->setType($schedule_form['note_type']);
                            $referringHealthFacilityNote->setNote($schedule->getNote());
                            $em->persist($referringHealthFacilityNote);
                        }

                        if ($schedule_form['referringProvider'] != '' || $schedule_form['referringProvider'] != null) {
                            $referringProvider = $schedule->getReferringProvider();

//                            if(($referringProvider->getGeoLat() == '' && $referringProvider->getGeoLat() == null) || ($referringHealthFacility->getGeoLong() == '' && $patient->getGeoLong() == null)){
//                                $referringProvider->setGeoLat($schedule_form['patient_geoLat']);
//                                $referringProvider->setGeoLong($schedule_form['patient_geoLong']);
//                            }
                            $referringProviderChart = new ReferringProviderChartEntity();
                            $referringProviderChart->setMarketingStaffSchedule($schedule);
                            $referringProviderChart->setHealthFacility($schedule->getHealthFacility());
                            $referringProviderChart->setMarketingStaff($schedule->getMarketingStaff());
                            $referringProviderChart->setReferringProvider($schedule->getReferringProvider());
                            $referringProviderChart->setChartType($schedule->getChartType());
                            if($chartStatus){
                                $referringProviderChart->setChartStatus($chartStatus);
                            }
                            $referringProviderChart->setChartDate($schedule->getScheduleDateAsString());
                            $em->persist($referringProviderChart);
                            $referringProviderChartNote = new ReferringProviderChartNoteEntity();
                            $referringProviderChartNote->setReferringProviderChart($referringProviderChart);
                            $referringProviderChartNote->setNote($schedule->getNote());
                            $em->persist($referringProviderChartNote);
                            $referringProviderNote = new ReferringProviderNoteEntity();
                            $referringProviderNote->setReferringProvider($schedule->getReferringProvider());
                            $referringProviderNote->setType($schedule_form['note_type']);
                            $referringProviderNote->setNote($schedule->getNote());
                            $em->persist($referringProviderNote);
                        }

                        $em->flush();
//                        $newAT = new AuditTrailEntity(
//                            'Appointment',
//                            $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $schedule;
//                        $newAT->parseDetails();
//                        $em->persist($newAT);
//                        $em->flush();

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

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

                    break;

                case 'u': // update

//                    $newAT = new AuditTrailEntity(
//                        'Appointment',
//                        $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_UPDATE
//                    );
//                    $newAT->entity = $schedule;
//                    $newAT->parseOriginalDetails();

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

                        if ($schedule_form['patient']) {
                            $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->findOneBy(array(
                                'schedule' => $schedule->getId()
                            ));

                            $patientChart->setHealthFacility($schedule->getHealthFacility());
                            $patientChart->setMarketingStaff($schedule->getMarketingStaff());
                            $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->getMarketingStaffScheduleStatus()->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(PatientNoteEntity::TYPE_APPOINTMENT);
                                $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();
                                    }
                                }
                            }
                            $schedule->updateStartEndTime();
                        }

                        if ($schedule_form['referringHealthFacility'] != '' || $schedule_form['referringHealthFacility'] != null) {
                            $referringHealthFacilityChart = $em->getRepository('RxConnexionBundle:ReferringHealthFacilityChartEntity')->findOneBy(array(
                                'marketingStaffSchedule' => $schedule->getId()
                            ));

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

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

                        if ($schedule_form['referringProvider'] != '' || $schedule_form['referringProvider'] != null) {
                            $referringProviderChart = $em->getRepository('RxConnexionBundle:ReferringProviderChartEntity')->findOneBy(array(
                                'marketingStaffSchedule' => $schedule->getId()
                            ));

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

                            $chartStatus = $em->getRepository('RxConnexionBundle:ChartStatusEntity')->findOneBy(array(
                                'description' => $schedule->getMarketingStaffScheduleStatus()->getDescription(),
                                'chartType' => $schedule->getChartType()->getId()
                            ));
                            if($chartStatus && $scheduleStatus){
                                $referringProviderChart->setChartStatus($chartStatus);
                            }
                            if($schedule->getNote() != $oldNotes){
                                $referringProviderChartNote = new ReferringProviderChartNoteEntity();
                                $referringProviderChartNote->setReferringProviderChart($referringProviderChart);
                                $referringProviderChartNote->setNote($schedule->getNote());
                                $em->persist($referringProviderChartNote);
                                $referringProviderNote = new ReferringProviderNoteEntity();
                                $referringProviderNote->setReferringProvider($schedule->getReferringProvider());
                                $referringProviderNote->setType(ReferringProviderNoteEntity::TYPE_APPOINTMENT);
                                $referringProviderNote->setNote($schedule->getNote());
                                $em->persist($referringProviderNote);
                            }
                            $schedule->updateStartEndTime();
                        }

//                        $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(
//                        'Appointment',
//                        $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_DELETE
//                    );
//                    $newAT->entity = $schedule;
//                    $newAT->parseDetails();
//                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $schedule = $em->getRepository('RxConnexionBundle:MarketingStaffScheduleEntity')->find($schedule_form['id']);
                        $schedule->setIsDeleted(true);

                        if ($schedule_form['patient']) {
                            $patientChart = $schedule->getPatientChart();
                            $patientChart->setIsDeleted(true);
                        }

                        if ($schedule_form['referringHealthFacility']) {
                            $referringHealthFacility = $schedule->getReferringHealthFacility();
                            $referringHealthFacility->setIsDeleted(true);
                        }

                        if ($schedule_form['referringProvider']) {
                            $referringProvider = $schedule->getReferringProvider();
                            $referringProvider->setIsDeleted(true);
                        }

                        //$em->remove($schedule);

                        $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(
     *      "/dashboard/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "marketing_staff_schedule_dashboard_form"
     * )
     */
    public function dashboard_formAction($action, $id, Request $request) {
        $get = $request->query->all();
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Marketing Staff Schedule Update'))) return $authService->redirectToHome();

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

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

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

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

            if($action === 'u'){
                $newAT = new AuditTrailEntity(
                    'Appointment',
                    $em->getClassMetadata(MarketingStaffScheduleEntity::class)->getTableName(),
                    AuditTrailEntity::AXN_UPDATE
                );
                $newAT->entity = $schedule;
                $newAT->parseOriginalDetails();

                $form->handleRequest($request);

                if ($form->isValid()) {

                    $patientChart = $em->getRepository('RxConnexionBundle:PatientChartEntity')->findOneBy(array(
                        'schedule' => $schedule->getId()
                    ));

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

                    $patientChartNote = new PatientChartNoteEntity();
                    $patientChartNote->setPatientChart($patientChart);
                    $patientChartNote->setNote($schedule->getNote());
                    $em->persist($patientChartNote);
                    $patientNote = new PatientNoteEntity();
                    $patientNote->setPatient($schedule->getPatient());
                    $patientNote->setType(PatientNoteEntity::TYPE_APPOINTMENT);
                    $patientNote->setNote($schedule->getNote());
                    $em->persist($patientNote);

                    $em->flush();
                    $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                    return $this->redirect($this->generateUrl('dashboard_clinician_preview'), 302);
                } else {
                    $this->get('session')->getFlashBag()->set('error_messages', 'No record updated.');
                    return $this->redirect($this->generateUrl('main'), 302);
                }
            }

        }

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

        $result['html'] =  $this->renderView('@RxConnexion/MarketingStaffSchedule/dashboard_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/schedule/schedule_form.js?v=1.0.3'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id,
            'schedule' => $schedule,
        ));
        $result['success'] = true;
        $result['action'] = $action;
        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/calendar/check",
     *      name = "patient_chart_health_facility_check"
     * )
     */
    public function patientChartHealthFacility_check(Request $request) {

        $patient_id = $request->request->get('patient');

        $em = $this->getDoctrine()->getManager();
        $result = $em->getRepository('RxConnexionBundle:PatientChartEntity')->check_patientChart_healthFacility($patient_id);

        return new JsonResponse($result);
    }
}