<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ProviderWorkScheduleEntity;
use RxConnexionBundle\Form\ProviderWorkScheduleForm;
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\AuditTrailEntity;
use RxConnexionBundle\Entity\ProviderEntity;
use RxConnexionBundle\Entity\ProviderHealthFacilityEntity;

use RxConnexionBundle\Form\ProviderHealthFacilityForm;
use RxConnexionBundle\Form\ProviderForm;

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

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

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

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

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

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

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

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

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

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

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

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

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['gender'],
                    $row['birthDate'],
                    $row['startDate'],
                    $row['endDate'],
                    $row['emergencyContactName'],
                    $row['emergencyContactNo'],
                    $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 = "provider_form"
     * )
     */
    public function formAction($action, $id, Request $request) {

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

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

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

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

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

            $provider_form = $request->get($form->getName());
            $result = $this->processForm($provider_form, $provider, $form, $request);

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

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

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

    private function processForm($provider_form, $provider, $form, Request $request) {

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

        if(!count($errors)) {

            switch($provider_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

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

                            }
                        }

                        $newAT = new AuditTrailEntity(
                            'Physician',
                            $em->getClassMetadata(ProviderEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $provider;
                        $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(
                        'Physician',
                        $em->getClassMetadata(ProviderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $provider;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $provider_obj = $em->getRepository('RxConnexionBundle:ProviderEntity')->find($provider_form['id']);

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

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

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

                            if (move_uploaded_file($_FILES['form']['tmp_name']['photo'], $uploadFile)) {
                                $provider_obj->removePhoto();
                                $provider_obj->setPhotoDescription($_FILES['form']['name']['photo']);
                                $provider_obj->setParsedPhotoDescription($baseName);
                                $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(
                        'Physician',
                        $em->getClassMetadata(ProviderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $provider;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

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

                    } else {

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

                    break;
            }

            $result['success'] = true;

        } else {

            foreach($errors as $error) {
                $this->get('session')->getFlashBag()->add('error_messages', $error);
            }

            $result['success'] = false;
        }

        return $result;
    }

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

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

        $em = $this->getDoctrine()->getManager();
        $provider = $em->getRepository('RxConnexionBundle:ProviderEntity')->find(base64_decode($provider_id));

        $title = 'Manage Clinician - ' . $provider->getFullName();
        return $this->render('@RxConnexion/Provider/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/provider/provider_detail.js?v=1.0.4'
            ),
            'provider_id' => $provider_id,
            'provider' => $provider,
            'tab' => $request->query->get('tab')
        ));
    }

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

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

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

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

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

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

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

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

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

                $values = array(
                    $row['health_facility_id'],
                    $row['company_description'],
                    $row['branch_description'],
                    $row['description'],
                    $row['mobile_no'],
                    $row['phone_no'],
                    $row['email'],
                    $row['startDate'],
                    $row['endDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/health_facility/form/{provider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "provider_health_facilities_form"
     * )
     */
    public function provider_health_facilities_formAction($provider_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'provider_id' => $provider_id
        );
        $form = $this->createForm(ProviderHealthFacilityForm::class, $providerHealthFacility, $formOptions);


        $title = $action === 'n' ? 'Add Branch' : 'Update ' . $providerHealthFacility->getHealthFacility()->getDescription()    ;

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

    /**
     * @Route(
     *      "/provider_health_facilities/save_action",
     *      name = "provider_health_facilities_save"
     * )
     */
    public function provider_health_facilities_saveAction(Request $request) {

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

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

        $providerHealthFacility_form = $request->get('provider_health_facility');
        $em = $this->getDoctrine()->getManager();
        $providerHealthFacility = $em->getRepository('RxConnexionBundle:ProviderHealthFacilityEntity')->find($providerHealthFacility_form['id'] );
        if(!$providerHealthFacility) {
            $providerHealthFacility = new ProviderHealthFacilityEntity();
        }
        $formOptions = array(
            'action' => $providerHealthFacility_form['action'],
            'provider_id' => $providerHealthFacility_form['provider']
        );
        $form = $this->createForm(ProviderHealthFacilityForm::class, $providerHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ProviderHealthFacilityEntity')->validate($providerHealthFacility_form);

        if(!count($errors)) {

            switch($providerHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {
                        if(isset($providerHealthFacility_form['is_schedule_default'])){
                            $em->getRepository('RxConnexionBundle:ProviderHealthFacilityEntity')->removeCurrentScheduleDefault(base64_decode($providerHealthFacility_form['provider']));
                            $providerHealthFacility->setIsScheduleDefault(true);
                        }

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

                        $newAT = new AuditTrailEntity(
                            'Physician Branch',
                            $em->getClassMetadata(ProviderHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $providerHealthFacility;
                        $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
                    if(isset($providerHealthFacility_form['is_schedule_default'])){
                        $em->getRepository('RxConnexionBundle:ProviderHealthFacilityEntity')->removeCurrentScheduleDefault(base64_decode($providerHealthFacility_form['provider']));
                        $providerHealthFacility->setIsScheduleDefault(true);
                    }

                    //$em->persist($providerHealthFacility);
                    $em->flush();

                    $newAT = new AuditTrailEntity(
                        'Physician Branch',
                        $em->getClassMetadata(ProviderHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $providerHealthFacility;
                    $newAT->parseOriginalDetails();

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

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

                        $em->flush();
                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Physician Branch',
                        $em->getClassMetadata(ProviderHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $providerHealthFacility;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Deleted.';

                    } else {

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

                    break;
            }
        } else {

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

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

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

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

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

            $hasUpdate = $authService->isUserHasAccesses(array('Admin Physician Work Schedule Update'), false);

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

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

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

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

                $values = array(
                    $row['type'],
                    $row['healthFacility'],
                    $row['fromDate'],
                    $row['fromTime'],
                    $row['toDate'],
                    $row['toTime'],
                    $row['day_name'],
                    $row['note'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/work_schedule/form/{provider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "provider_work_schedule_form"
     * )
     */
    public function provider_work_schedule_formAction($provider_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'provider_id' => $provider_id
        );
        $form = $this->createForm(ProviderWorkScheduleForm::class, $providerWorkSchedule, $formOptions);


        $title = $action === 'n' ? 'New Work Schedule' : 'Update Work Schedule' ;

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

    /**
     * @Route(
     *      "/provider_work_schedule/save_action",
     *      name = "provider_work_schedule_save"
     * )
     */
    public function provider_work_schedule_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 Physician Work Schedule New', 'Admin Physician Work Schedule Update'))) return $authService->redirectToHome();

        $providerWorkSchedule_form = $request->get('providerWorkSchedule');
        $em = $this->getDoctrine()->getManager();
        $providerWorkSchedule = $em->getRepository('RxConnexionBundle:ProviderWorkScheduleEntity')->find($providerWorkSchedule_form['id'] );
        if(!$providerWorkSchedule) {
            $providerWorkSchedule = new ProviderWorkScheduleEntity();
        }
        $formOptions = array(
            'action' => $providerWorkSchedule_form['action'],
            'provider_id' => $providerWorkSchedule_form['provider']
        );
        $form = $this->createForm(ProviderWorkScheduleForm::class, $providerWorkSchedule, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ProviderWorkScheduleEntity')->validate($providerWorkSchedule_form);

        if(!count($errors)) {

            switch($providerWorkSchedule_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Physician Work Schedule',
                            $em->getClassMetadata(ProviderWorkScheduleEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $providerWorkSchedule;
                        $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(
                        'Physician Work Schedule',
                        $em->getClassMetadata(ProviderWorkScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $providerWorkSchedule;
                    $newAT->parseOriginalDetails();

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

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

                        $em->flush();
                        $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Updated.';
                    }else{
                        $result['errorMessages'][] = 'Something went wrong. Please try again.';
                    }

                    break;

                case 'd': // delete

                    $newAT = new AuditTrailEntity(
                        'Physician Work Schedule',
                        $em->getClassMetadata(ProviderWorkScheduleEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $providerWorkSchedule;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $em->flush();

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

                        $result['success'] = true;
                        $result['successMessages'][] = 'Record Successfully Deleted.';

                    } else {

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

                    break;
            }
        } else {

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

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

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

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

        return new JsonResponse($result);
    }

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

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

        $result = array(
            'query' => 'providers',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ProviderEntity')->for_patient_schedule_providerAutocomplete_suggestions($q)
        );

        return new JsonResponse($result);
    }

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

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

        $result = array(
            'query' => 'cities',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ProviderEntity')->schedule_provider_autocomplete_suggestions($q, $healthFacility_id)
        );

        return new JsonResponse($result);
    }

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

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

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

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

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:AuditTrailEntity')->provider_work_schedule_history_ajax_list($get);

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

                $history = json_decode($row['historyData'], true);
                $labels = array(
                    'id' => 'ID',
                    //'type' => 'Type',
                    //'branch' => 'Branch',
                    'from_date' => 'From Date',
                    'from_time' => 'From Time',
                    'to_date' => 'To Date',
                    'to_time' => 'To Time',
                    //'day_name' => 'Day',
                );
                $historyData = '';

                if($row['axn'] == 'New' || $row['axn'] == 'Delete') {
                    foreach($labels as $columnName => $label){
                        $historyData .= (empty($historyData) ? '' : ' | ');
                        $historyData .= ' '.$label.': ';
                        if(isset($history['Details'][$columnName])) {
                            if($columnName == 'from_date' || $columnName == 'to_date'){
                                $historyData .= date('m/d/Y', strtotime(substr($history['Details'][$columnName],0,10)));
                            } else {
                                $historyData .= $history['Details'][$columnName];
                            }
                        } elseif($columnName === 'from_time') {
                            $historyData .= (str_pad($history['Details']['from_hr'], 2, "0", STR_PAD_LEFT) . ':' . str_pad($history['Details']['from_min'], 2, '0', STR_PAD_LEFT) . ' ' . $history['Details']['from_am']);
                        } elseif($columnName === 'to_time') {
                            $historyData .= (str_pad($history['Details']['to_hr'], 2, "0", STR_PAD_LEFT) . ':' . str_pad($history['Details']['to_min'], 2, '0', STR_PAD_LEFT) . ' ' . $history['Details']['to_am']);
                        }
                    }
                } else {
                    foreach($labels as $columnName => $label){
                        if(isset($history['Details'][$columnName]) && isset($history['Original Details'][$columnName])) {
                            if($columnName === 'from_date' || $columnName == 'to_date') {
                                $origValue = date('m/d/Y', strtotime(isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName] : null));
                                $newValue =  date('m/d/Y', strtotime(isset($history['Details'][$columnName]) ? $history['Details'][$columnName] : null));
                            } else {
                                $origValue = isset($history['Original Details'][$columnName]) ? $history['Original Details'][$columnName] : null;
                                $newValue =  isset($history['Details'][$columnName]) ? $history['Details'][$columnName] : null;
                            }
                            if($origValue != $newValue) {
                                $historyData .= (empty($historyData) ? '' : ' | ');

                                $historyData .= (is_array($label) ? $label[0] : $label).': ';
                                $historyData .= $origValue;

                                $historyData .= ' &rarr; ';
                                $historyData .= $newValue;
                            }
                        } elseif($columnName === 'from_time') {
                            $origValue = null;
                            $newValue = null;
                            if(isset($history['Original Details']['from_hr']) && isset($history['Original Details']['from_min']) && isset($history['Original Details']['from_am'])) $origValue = (str_pad($history['Original Details']['from_hr'], 2, "0", STR_PAD_LEFT) . ':' . str_pad($history['Original Details']['from_min'], 2, '0', STR_PAD_LEFT) . ' ' . $history['Original Details']['from_am']);
                            if(isset($history['Details']['from_hr'])          && isset($history['Details']['from_min'])          && isset($history['Details']['from_am']))          $newValue = (str_pad($history['Details']['from_hr'], 2, "0", STR_PAD_LEFT) . ':' . str_pad($history['Details']['from_min'], 2, '0', STR_PAD_LEFT) . ' ' . $history['Details']['from_am']);

                            if($origValue != $newValue) {
                                $historyData .= (empty($historyData) ? '' : ' | ');

                                $historyData .= (is_array($label) ? $label[0] : $label).': ';
                                $historyData .= $origValue;

                                $historyData .= ' &rarr; ';
                                $historyData .= $newValue;
                            }
                        } elseif($columnName === 'to_time') {
                            $origValue = null;
                            $newValue = null;
                            if(isset($history['Original Details']['to_hr']) && isset($history['Original Details']['to_min']) && isset($history['Original Details']['to_am'])) $origValue = (str_pad($history['Original Details']['to_hr'], 2, "0", STR_PAD_LEFT) . ':' . str_pad($history['Original Details']['to_min'], 2, '0', STR_PAD_LEFT) . ' ' . $history['Original Details']['to_am']);
                            if(isset($history['Details']['to_hr'])          && isset($history['Details']['to_min'])          && isset($history['Details']['to_am']))          $newValue = (str_pad($history['Details']['to_hr'], 2, "0", STR_PAD_LEFT) . ':' . str_pad($history['Details']['to_min'], 2, '0', STR_PAD_LEFT) . ' ' . $history['Details']['to_am']);

                            if($origValue != $newValue) {
                                $historyData .= (empty($historyData) ? '' : ' | ');

                                $historyData .= (is_array($label) ? $label[0] : $label).': ';
                                $historyData .= $origValue;

                                $historyData .= ' &rarr; ';
                                $historyData .= $newValue;
                            }
                        }

                    }
                }


                $values = array(
                    $row['axn'],
                    $row['date'],
                    $row['user'],
                    //$row['label'],
                    $historyData,
                );

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

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

        return new JsonResponse($result);
    }
}