<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\MarketingStaffWorkScheduleEntity;
use RxConnexionBundle\Form\MarketingStaffWorkScheduleForm;
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\MarketingStaffEntity;
use RxConnexionBundle\Entity\MarketingStaffHealthFacilityEntity;

use RxConnexionBundle\Form\MarketingStaffHealthFacilityForm;
use RxConnexionBundle\Form\MarketingStaffForm;

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

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

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

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

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

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

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

                if($hasUpdate) {
                    $url = $this->generateUrl('marketing_staff_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }
                if($hasDetail){
                    $detailsUrl = $this->generateUrl('marketing_staff_detail', array(
                        'marketing_staff_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 = "marketing_staff_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 New', 'Admin Marketing Staff Update'))) return $authService->redirectToHome();

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

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

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

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

            $marketingStaff_form = $request->get($form->getName());
            $result = $this->processForm($marketingStaff_form, $marketingStaff, $form, $request);

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

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

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

    private function processForm($marketingStaff_form, $marketingStaff, $form, Request $request) {

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

        if(!count($errors)) {

            switch($marketingStaff_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

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

                            }
                        }

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {
                        $marketingStaff_obj = $em->getRepository('RxConnexionBundle:MarketingStaffEntity')->find($marketingStaff_form['id']);

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

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

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

                            if (move_uploaded_file($_FILES['form']['tmp_name']['photo'], $uploadFile)) {
                                $marketingStaff_obj->removePhoto();
                                $marketingStaff_obj->setPhotoDescription($_FILES['form']['name']['photo']);
                                $marketingStaff_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(MarketingStaffEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $marketingStaff;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($marketingStaff);
                        $marketingStaff->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/{marketing_staff_id}",
     *      name = "marketing_staff_detail"
     * )
     */
    public function detailAction($marketing_staff_id, Request $request) {

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

        $em = $this->getDoctrine()->getManager();
        $marketingStaff = $em->getRepository('RxConnexionBundle:MarketingStaffEntity')->find(base64_decode($marketing_staff_id));

        $title = 'Manage Marketing Staff - ' . $marketingStaff->getFullName();
        return $this->render('@RxConnexion/MarketingStaff/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/marketingStaff/marketingStaff_detail.js?v=1.0.3'
            ),
            'marketingStaff_id' => $marketing_staff_id,
            'marketingStaff' => $marketingStaff,
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/marketing_staff_health_facilities_ajax_list", name="marketing_staff_health_facilities_ajax_list")
     */
    public function marketingStaff_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 Marketing Staff Health Facility Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:MarketingStaffHealthFacilityEntity')->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/{marketingStaff_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "marketing_staff_health_facilities_form"
     * )
     */
    public function marketingStaff_health_facilities_formAction($marketingStaff_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'marketingStaff_id' => $marketingStaff_id
        );
        $form = $this->createForm(MarketingStaffHealthFacilityForm::class, $marketingStaffHealthFacility, $formOptions);


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

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

    /**
     * @Route(
     *      "/marketing_staff_health_facilities/save_action",
     *      name = "marketing_staff_health_facilities_save"
     * )
     */
    public function marketingStaff_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 Marketing Staff Health Facility New', 'Admin Marketing Staff Health Facility Update'))) return $authService->redirectToHome();

        $marketingStaffHealthFacility_form = $request->get('marketingStaff_health_facility');
        $em = $this->getDoctrine()->getManager();
        $marketingStaffHealthFacility = $em->getRepository('RxConnexionBundle:MarketingStaffHealthFacilityEntity')->find($marketingStaffHealthFacility_form['id'] );
        if(!$marketingStaffHealthFacility) {
            $marketingStaffHealthFacility = new MarketingStaffHealthFacilityEntity();
        }
        $formOptions = array(
            'action' => $marketingStaffHealthFacility_form['action'],
            'marketingStaff_id' => $marketingStaffHealthFacility_form['marketingStaff']
        );
        $form = $this->createForm(MarketingStaffHealthFacilityForm::class, $marketingStaffHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:MarketingStaffHealthFacilityEntity')->validate($marketingStaffHealthFacility_form);

        if(!count($errors)) {

            switch($marketingStaffHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {
                        if(isset($marketingStaffHealthFacility_form['is_schedule_default'])){
                            $em->getRepository('RxConnexionBundle:MarketingStaffHealthFacilityEntity')->removeCurrentScheduleDefault(base64_decode($marketingStaffHealthFacility_form['marketingStaff']));
                            $marketingStaffHealthFacility->setIsScheduleDefault(true);
                        }

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

                        $newAT = new AuditTrailEntity(
                            'Marketing Staff Branch',
                            $em->getClassMetadata(MarketingStaffHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $marketingStaffHealthFacility;
                        $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($marketingStaffHealthFacility_form['is_schedule_default'])){
                        $em->getRepository('RxConnexionBundle:MarketingStaffHealthFacilityEntity')->removeCurrentScheduleDefault(base64_decode($marketingStaffHealthFacility_form['marketingStaff']));
                        $marketingStaffHealthFacility->setIsScheduleDefault(true);
                    }

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

                    $newAT = new AuditTrailEntity(
                        'Marketing Staff Branch',
                        $em->getClassMetadata(MarketingStaffHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $marketingStaffHealthFacility;
                    $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(
                        'Marketing Staff Branch',
                        $em->getClassMetadata(MarketingStaffHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $marketingStaffHealthFacility;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($marketingStaffHealthFacility);
                        $marketingStaffHealthFacility->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("/marketing_staff_work_schedule_ajax_list", name="marketing_staff_work_schedule_ajax_list")
     */
    public function marketingStaff_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 Marketing Staff Work Schedule Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:MarketingStaffWorkScheduleEntity')->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/{marketing_staff_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "marketing_staff_work_schedule_form"
     * )
     */
    public function marketing_staff_work_schedule_formAction($marketing_staff_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();

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

        $formOptions = array(
            'action' => $action,
            'marketingStaff_id' => $marketing_staff_id
        );
        $form = $this->createForm(MarketingStaffWorkScheduleForm::class, $marketingStaffWorkSchedule, $formOptions);


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

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

    /**
     * @Route(
     *      "/marketing_staff_work_schedule/save_action",
     *      name = "marketing_staff_work_schedule_save"
     * )
     */
    public function marketing_staff_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 Marketing Staff Work Schedule New', 'Admin Marketing Staff Work Schedule Update'))) return $authService->redirectToHome();

        $marketingStaffWorkSchedule_form = $request->get('marketingStaffWorkSchedule');
        $em = $this->getDoctrine()->getManager();
        $marketingStaffWorkSchedule = $em->getRepository('RxConnexionBundle:MarketingStaffWorkScheduleEntity')->find($marketingStaffWorkSchedule_form['id'] );
        if(!$marketingStaffWorkSchedule) {
            $marketingStaffWorkSchedule = new MarketingStaffWorkScheduleEntity();
        }
        $formOptions = array(
            'action' => $marketingStaffWorkSchedule_form['action'],
            'marketingStaff_id' => $marketingStaffWorkSchedule_form['marketingStaff']
        );
        $form = $this->createForm(MarketingStaffWorkScheduleForm::class, $marketingStaffWorkSchedule, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:MarketingStaffWorkScheduleEntity')->validate($marketingStaffWorkSchedule_form);

        if(!count($errors)) {

            switch($marketingStaffWorkSchedule_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($marketingStaffWorkSchedule);
                        $marketingStaffWorkSchedule->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="marketing_staff_autocomplete")
     */
    public function autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }

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

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

        $result = array(
            'query' => 'marketing_staffs',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:MarketingStaffEntity')->for_patient_schedule_marketing_staffAutocomplete_suggestions($q)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/autocomplete_for_schedule", name="marketing_staff_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:MarketingStaffEntity')->schedule_marketing_staff_autocomplete_suggestions($q, $healthFacility_id)
        );

        return new JsonResponse($result);
    }

    /**
     * @Route("/work_schedule_history_ajax_list", name="marketing_staff_work_schedule_history_ajax_list")
     */
    public function marketing_staff_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')->markeringStaff_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);
    }
}