<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\AccountUserEntity;
use RxConnexionBundle\Entity\ChartStatusEntity;
use RxConnexionBundle\Entity\HealthFacilityEntity;
use RxConnexionBundle\Entity\PatientChartEntity;
use RxConnexionBundle\Entity\PatientChartNoteEntity;
use RxConnexionBundle\Entity\PatientChartTypeMethodEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\ProviderEntity;
use RxConnexionBundle\Entity\ScheduleStatusEntity;
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\ScheduleEntity;
use RxConnexionBundle\Form\ScheduleForm;
use RxConnexionBundle\Entity\AuditTrailEntity;

use RxConnexionBundle\Form\ScheduleForCalendarForm;


/**
 * @Route("/main/appointment")
 */
class ScheduleController extends Controller
{
    /**
     * @Route("", name="schedule")
     */
    public function indexAction() {

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

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

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

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ScheduleEntity')->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 = "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 Schedule New', 'Admin Schedule Update'))) return $authService->redirectToHome();

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

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

        $formOptions = array('action' => $action);
        $form = $this->createForm(ScheduleForm::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') . ' Appointment';

        return $this->render('@RxConnexion/Schedule/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
        ));
    }

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

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

                        $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());
                        $patientChart->setChartDate($schedule->getScheduleDateAsString());
                        $em->persist($patientChart);
                        $em->flush();

                        $newAT = new AuditTrailEntity(
                            'Appointment',
                            $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'] = '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(ScheduleEntity::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(ScheduleEntity::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="calendar_appointment")
     */
    public function calendarAction() {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin 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/Schedule/calendar.html.twig', array(
            'title' => 'Appointment Calendar',
            'page_title' => '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/schedule/calendar.js?v=1.1.0'),
            'healthFacilities' => $healthFacilities,
            'hfLatLongs' => $hfLatLngDetails,
            'userData' => $userData,
            'hasBackToTop' => true,
            'noteTemplateAccess' => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
            'defaultHealthFacility' => (($userData['type'] === 'Clinician' && $user->getProvider()) ? $user->getProvider()->getDefaultProviderHealthFacilityId() : '')
        ));
    }

    /**
     * @Route("/calendar/view", name="calendar_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']);
        $schedules = $em->getRepository('RxConnexionBundle:ScheduleEntity')-> 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 ($providers as $key => $provider){
                            if($provider['id'] != $schedule['providerId']){
                                continue;
                            }
                            if(isset($providers[$key]['schedules'])){
                                $found = false;
                                foreach($providers[$key]['schedules'] as $key2 => $providerSchedule){
                                    if($providerSchedule['id'] == $schedule['id']){
                                        $providers[$key]['schedules'][$key2]['rowSpan']++;
                                        $providers[$key]['schedules'][$key2]['rowSpanTimes'][] = $text;
                                        $found = true;
                                        break;
                                    }
                                }

                                if(!$found){
                                    $schedule['timeText'] = $text;
                                    $schedule['rowSpan'] = 1;
                                    $schedule['rowSpanTimes'] = array();
                                    $providers[$key]['schedules'][] = $schedule;
                                }
                            }else{
                                $schedule['timeText'] = $text;
                                $schedule['rowSpan'] = 1;
                                $schedule['rowSpanTimes'] = array();
                                $providers[$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 ($providers as $key => $provider){
                            if($provider['id'] != $schedule['providerId']){
                                continue;
                            }
                            if(isset($providers[$key]['schedulesNSC'])){
                                $found = false;
                                foreach($providers[$key]['schedulesNSC'] as $key2 => $providerSchedule){
                                    if($providerSchedule['id'] == $schedule['id']){
                                        $providers[$key]['schedulesNSC'][$key2]['rowSpan']++;
                                        $providers[$key]['schedulesNSC'][$key2]['rowSpanTimes'][] = $text;
                                        $found = true;
                                        break;
                                    }
                                }
                                if(!$found){
                                    $schedule['timeText'] = $text;
                                    $schedule['rowSpan'] = 1;
                                    $schedule['rowSpanTimes'] = array();
                                    $providers[$key]['schedulesNSC'][] = $schedule;
                                }
                            }else{
                                $schedule['timeText'] = $text;
                                $schedule['rowSpan'] = 1;
                                $schedule['rowSpanTimes'] = array();
                                $providers[$key]['schedulesNSC'] = array($schedule);
                            }
                        }
                    }
                }
                foreach ($providers as $key => $provider) {
                    $workSchedules = array(
                        'regular' => array(),
                        'irregular' => array(),
                        'out' => array()
                    );
                    if(!isset($providers[$key]['workSchedules'])){
                        $providers[$key]['workSchedules'] = $workSchedules;
                    }
                    $providerWorkSchedules = explode('@', $provider['providerWorkSchedules']);
                    foreach ($providerWorkSchedules as $providerWorkSchedule) {
                        $workSchedule = explode('|', $providerWorkSchedule);
                        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){
                            $providers[$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){
                            $providers[$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){
                            $providers[$key]['workSchedules']['regular'][] = $text;
                        }
                    }
                }
                $times[] = array(
                    'text' => $text
                    //'schedules' => $scheds
                );
            }
        }


//        var_dump($provider);
//        die();
        $result['success'] = true;
        $result['html'] = $this->renderView(
            '@RxConnexion/Schedule/calendar_view.html.twig', array(
                'providers' => $providers,
                'times' => $times,
                'healthFacility_id' => $get['healthFacility_id']
            )
        );

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/calendar/form",
     *      name = "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 Schedule New', 'Admin Schedule Update'))) return $authService->redirectToHome();

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

        $schedule = $em->getRepository('RxConnexionBundle:ScheduleEntity')->find($get['id']);
        $provider = $em->getRepository('RxConnexionBundle:ProviderEntity')->find($get['provider_id']);
        $healthFacility = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($get['healthFacility_id']);
        $providerFullName = $provider->getFullName();
        $healthFacilityName = $healthFacility->getDescription();
        $latestChartDetails = array();

        if($schedule){
            $latestChartDetails = $em->getRepository('RxConnexionBundle:PatientChartEntity')->getPatientLatestChart($schedule->getPatient()->getId(), $schedule->getPatientChart()->getId());
            $result['latestPatientChartDetails'] = $latestChartDetails;

        }
        if(!$schedule) {
            $schedule = new ScheduleEntity();
        }
        $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(),
            'provider_id' => $get['provider_id'],
            'schedDate' => $get['date'],
            'startTime' => $get['start_time'],
            'providerFullName' => $providerFullName,
            'healthFacilityName' => $healthFacilityName,
            'startTimeHour' => intval($time[3]),
            'startTimeMin' => $time[0],
            'startTimePeriod' => $time[1],
            'action' => $get['action']
        );
        $form = $this->createForm(ScheduleForCalendarForm::class, $schedule, $formOptions);


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

        $result['html'] =  $this->renderView('@RxConnexion/Schedule/schedule_calendar_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'startTime' => $get['start_time'],
            'providerFullName' => $providerFullName,
            'healthFacilityName' => $healthFacilityName,
            'schedDate' => $get['date'],
            'form' => $form->createView(),
            'action' => $get['action'],
            'id' => $get['id'],
            'schedule' => $schedule,
            'latestChartDetails' => $latestChartDetails,
            'healthFacility' => $healthFacility
        ));
        if($schedule->getPatient()){
            $patient = $schedule->getPatient();
            $patientFullName = $patient->getFullName();
            $url = $this->generateUrl('patient_detail', array(
                'patient_id' => base64_encode($patient->getId())
            ));
            $patientDetails = array(
                'patientName' => "<a href='$url' target='_blank'>$patientFullName</a>",
                'birthDate' => $patient->getBirthDateAsString(),
                'personalHealthNo' => $patient->getPersonalHealthNo(),
                'address' => $patient->getAddress(),
                'mobileNos' => $patient->getConcatenatedMobileNo(),
                'phoneNos' => $patient->getConcatenatedPhoneNo(),
                'insurances' => $patient->getConcatenatedInsurance(),
        );
            $result['patientDetails'] = $patientDetails;
        }
        $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 = "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 Schedule New', 'Admin Schedule Update'))) return $authService->redirectToHome();
        $schedule_form = $request->get('schedule');
        $em = $this->getDoctrine()->getManager();
        $schedule = $em->getRepository('RxConnexionBundle:ScheduleEntity')->find($schedule_form['id']);
        if(!$schedule){
            $schedule = new ScheduleEntity();
        };
        $formOptions = array(
            'healthFacility_id' => $schedule_form['health_facility'],
            'provider_id' => $schedule_form['provider'],
            'schedDate' => $schedule_form['schedule_date'],
            'startTime' => $schedule_form['start_time'],
            'action' => $schedule_form['action']
        );
        $form = $this->createForm(ScheduleForCalendarForm::class, $schedule, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ScheduleEntity')->validate($schedule_form, $schedule);
        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->getScheduleStatus()->getDescription(),
                            'chartType' => $schedule->getChartType()->getId()
                        ));
                        $em->persist($schedule);
                        $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->setSchedule($schedule);
                        $patientChart->setHealthFacility($schedule->getHealthFacility());
                        $patientChart->setProvider($schedule->getProvider());
                        $patientChart->setPatient($schedule->getPatient());
                        $patientChart->setChartType($schedule->getChartType());
                        $patientChart->setIsRepeat(isset($schedule_form['isRepeat']) ? true : false);
                        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(
                            'Appointment',
                            $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['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(ScheduleEntity::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()
                        ));

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $schedule = $em->getRepository('RxConnexionBundle:ScheduleEntity')->find($schedule_form['id']);
                        $schedule->setIsDeleted(true);
                        $patientChart = $schedule->getPatientChart();
                        $patientChart->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 = "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 Schedule Update'))) return $authService->redirectToHome();

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

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

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

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

            if($action === 'u'){
                $newAT = new AuditTrailEntity(
                    'Appointment',
                    $em->getClassMetadata(ScheduleEntity::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/Schedule/dashboard_form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/schedule/schedule_form.js?v=1.0.2'),
            '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);
    }

	/**
	 * @Route("/calendar/week", name="calendar_appointment_week")
	 */
	public function calendar_weekAction(Request $request) {

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

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


		$filter = $request->get('filter');
		$date = new \DateTime($filter ? $filter['date'] : 'now');

		$dateFrom = (clone $date)->modify('sunday last week')->format('m/d/Y');
		$dateTo = (clone $date)->modify('saturday this week')->format('m/d/Y');

		/**@var $user AccountUserEntity */
		$user = $em->getRepository(AccountUserEntity::class)->find($userData['id']);
		$healthFacilities = $em->getRepository(HealthFacilityEntity::class)->findAllNotDeletedAndHasPatient($userData);

		$provider = [
			'id'            => NULL,
			'workSchedules' => NULL,
		];
		$schedules = [];
		$times = [];
		$minutesIncrement = 15; // IMPORTANT!!! INCLUDED IN CONDITIONS INSIDE TABLE VIEW

		$provider_id = isset($filter['provider']) ? $filter['provider'] : ($user->getProvider() ? $user->getProvider()->getId() : 0);

		/**@var ProviderEntity $provider_obj */
		if ($provider_obj = $em->getRepository(ProviderEntity::class)->find($provider_id)) {

			$filter['provider'] = $provider_obj->getId();
			$filter['provider_name'] = $provider_obj->getFullName();

			$filter['date'] = $date->format('m/d/Y');

			$filter['branch'] = isset($filter['branch']) ? $filter['branch'] : $provider_obj->getDefaultProviderHealthFacilityId();

			$schedules = $em->getRepository(ScheduleEntity::class)->schedule_calendar_week_view_schedules($dateFrom, $dateTo, $filter['branch'], $filter['provider']);

			$provider = [
				'id'            => $provider_obj->getId(),
				'workSchedules' => $provider_obj->getWorkSchedulesToArray([
					'branch_id'   => $filter['branch'],
					'groupByType' => TRUE,
				]),
			];

			for ($i = 6; $i <= 20; $i++) {
				for ($ii = 0; $ii < 60; $ii += $minutesIncrement) {
					$hm = sprintf('%002d', $i) . ':' . sprintf('%002d', $ii);
					$dt = strtotime($date->format('m/d/Y') . ' ' . $hm);
					$text = date('h:i A', $dt);
					$int = intval(sprintf('%002d', $i) . sprintf('%002d', $ii)); // military time as integer: used inside table view display ex. 09:30 = 930
					$inc = $int + $minutesIncrement; // incremented minutes:  used to not allow overlapping ex. 6:00-6:30, dapat ung highlight sa table hangang 6:15 lang
					$times[] = [
						'text' => $text,
						'int'  => $int,
						'inc'  => $inc + (($inc % 100) == 60 ? 40 : 0),
						// modulus: para sa mga military time na may 60, dapat auto next hour un. ex. 660, dapat 700 na yan kase walang time na 660. kaya may add 40 para pag 60 ung minutes, add 40 na para mag next hr
					];
				}
			}
		}


		return $this->render('@RxConnexion/Schedule/calendar_week.html.twig', [
			'title'                 => 'Appointment Calendar: Week View',
			'page_title'            => 'Appointment Calendar: Week View',
			'stylesheets'           => ['rxconnexion/admin/css/schedule/calendar_week.css?v=1.0.0'],
			'javascripts'           => ['rxconnexion/admin/js/schedule/calendar_week.js?v=1.0.0'],
			'healthFacilities'      => $healthFacilities,
			'hasBackToTop'          => TRUE,
			'filter'                => $filter,
			'dateFrom'              => $dateFrom,
			'dateTo'                => $dateTo,
			'times'                 => $times,
			'minutesIncrement'      => $minutesIncrement,
			'schedules'             => $schedules,
			'provider'              => $provider,
			'defaultHealthFacility' => (($userData['type'] === 'Clinician' && $user->getProvider()) ? $user->getProvider()->getDefaultProviderHealthFacilityId() : ''),
			'googleMapApiKey'       => $this->container->getParameter('google_map_api_key'),
			'noteTemplateAccess'    => $authService->isUserHasAccessNoteTemplate(array('Admin Note Template', 'Admin Note Template')),
		]);
	}

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

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

		$schedule = $em->getRepository('RxConnexionBundle:ScheduleEntity')->find($get['id']);
		$provider = $em->getRepository('RxConnexionBundle:ProviderEntity')->find($get['provider_id']);
		$healthFacility = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->find($get['healthFacility_id']);
		$providerFullName = $provider->getFullName();
		$healthFacilityName = $healthFacility->getDescription();
		$latestChartDetails = array();
		$patient = null;

		if($schedule){
			$patient = $schedule->getPatient();
			$latestChartDetails = $em->getRepository('RxConnexionBundle:PatientChartEntity')->getPatientLatestChart($schedule->getPatient()->getId(), $schedule->getPatientChart()->getId());
			$result['latestPatientChartDetails'] = $latestChartDetails;

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


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

		$result['html'] = $this->renderView('@RxConnexion/Schedule/schedule_calendar_week_form.html.twig', [
			'title'              => $title,
			'page_title'         => $title,
			'startTime'          => $get['start_time'],
			'providerFullName'   => $providerFullName,
			'healthFacilityName' => $healthFacilityName,
			'schedDate'          => $get['date'],
			'form'               => $form->createView(),
			'action'             => $get['action'],
			'id'                 => $get['id'],
			'schedule'           => $schedule,
			'latestChartDetails' => $latestChartDetails,
			'healthFacility'     => $healthFacility,
			'patient'            => $patient,
		]);
		if ($schedule->getPatient()) {
			$patient = $schedule->getPatient();
			$patientFullName = $patient->getFullName();
			$url = $this->generateUrl('patient_detail', [
				'patient_id' => base64_encode($patient->getId()),
			]);
			$patientDetails = [
				'patientName'      => "<a href='$url' target='_blank'>$patientFullName</a>",
				'birthDate'        => $patient->getBirthDateAsString(),
				'personalHealthNo' => $patient->getPersonalHealthNo(),
				'address'          => $patient->getAddress(),
				'mobileNos'        => $patient->getConcatenatedMobileNo(),
				'phoneNos'         => $patient->getConcatenatedPhoneNo(),
				'insurances'       => $patient->getConcatenatedInsurance(),
			];
			$result['patientDetails'] = $patientDetails;
		}
		$branchDetails = [
			'address'   => $healthFacility->getAddress(),
			'mobileNos' => $healthFacility->getConcatenatedMobileNo(),
			'phoneNos'  => $healthFacility->getConcatenatedPhoneNo(),
		];
		$result['success'] = TRUE;
		$result['action'] = $get['action'];
		$result['branchDetails'] = $branchDetails;
		return new JsonResponse($result);
	}
}