<?php

namespace RxConnexionBundle\Controller;

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\ReferringProviderEntity;
use RxConnexionBundle\Entity\ReferringProviderHealthFacilityEntity;

use RxConnexionBundle\Form\ReferringProviderHealthFacilityForm;
use RxConnexionBundle\Form\ReferringProviderForm;

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

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

        return $this->render('@RxConnexion/ReferringProvider/index.html.twig', array(
            'title' => 'Manage Referring Physician',
            'page_title' => 'Manage Referring Physician',
            'javascripts' => array('rxconnexion/admin/js/referringProvider/referringProvider.js?v=1.0.0')
        ));
    }

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

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

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

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

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['phoneNos'],
                    $row['mobileNos'],
                    $row['emails'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route("/ajax_list_for_referral_form", name="referring_provider_ajax_list_for_referral_form")
     */
    public function ajax_list_for_referral_form(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:ReferringProviderEntity')->ajax_list_for_referral_form($get, $this->get('session')->get('userData'));

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

                $values = array(
                    $row['full_name'],
                    $row['address'],
                    $row['phoneNos'],
                    $row['mobileNos'],
                    $row['emails'],
                    'DT_DATA' => array(
                        'firstName' =>$row['first_name'],
                        'middleName' =>$row['middle_name'],
                        'lastName' =>$row['last_name'],
                        'gender' =>$row['gender'],
                        'street' => $row['street'],
                        'cityId' => $row['city_id'],
                        'cityDesc' => $row['city_desc'],
                        'id' => $row['id']
                    )
                );

                $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 = "referring_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 Referring Provider New', 'Admin Referring Provider Update'))) return $authService->redirectToHome();

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

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

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

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

            $referringReferringProvider_form = $request->get($form->getName());
            $result = $this->processForm($referringReferringProvider_form, $referringReferringProvider, $form, $request);

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

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

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

    private function processForm($referringReferringProvider_form, $referringReferringProvider, $form, Request $request) {

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

        if(!count($errors)) {

            switch($referringReferringProvider_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Provider',
                            $em->getClassMetadata(ReferringProviderEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringReferringProvider;
                        $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(
                        'Referring Provider',
                        $em->getClassMetadata(ReferringProviderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringReferringProvider;
                    $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(
                        'Referring Provider',
                        $em->getClassMetadata(ReferringProviderEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringReferringProvider;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

        $em = $this->getDoctrine()->getManager();
        $referringProvider = $em->getRepository('RxConnexionBundle:ReferringProviderEntity')->find(base64_decode($referringProvider_id));

        $title = 'Manage Referring Physician - ' . $referringProvider->getFullName();
        return $this->render('@RxConnexion/ReferringProvider/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/referringProvider/referringProvider_detail.js?v=1.0.0'
            ),
            'referringProvider_id' => $referringProvider_id,
            'referringProvider' => $referringProvider,
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/referring_provider_health_facilities_ajax_list", name="referring_provider_health_facilities_ajax_list")
     */
    public function referring_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 Referring Provider Referring Health Facilities Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ReferringProviderHealthFacilityEntity')->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-referring-medical-facility-form' data-action='u' data-id='$id'>Update</a>";
                }

                $values = array(
                    $row['company_description'],
                    $row['branch_description'],
                    $row['description'],
                    $row['address'],
                    $row['phoneNos'],
                    $row['mobileNos'],
                    $row['emails'],
                    $row['startDate'],
                    $row['endDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/referring_health_facility/form/{referringProvider_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "referring_provider_health_facilities_form"
     * )
     */
    public function referring_provider_health_facilities_formAction($referringProvider_id, $action, $id) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'referringProvider_id' => $referringProvider_id
        );
        $form = $this->createForm(ReferringProviderHealthFacilityForm::class, $referringProviderHealthFacility, $formOptions);


        $title = $action === 'n' ? 'Add Referring Medical Facility' : 'Update ' . $referringProviderHealthFacility->getReferringHealthFacility()->getDescription()    ;

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

    /**
     * @Route(
     *      "/referring_provider_health_facilities/save_action",
     *      name = "referring_provider_health_facilities_save"
     * )
     */
    public function referring_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 Referring Provider Referring Health Facility New', 'Admin Referring Provider Referring Health Facility Update'))) return $authService->redirectToHome();

        $referringProviderHealthFacility_form = $request->get('referringProviderHealthFacility');
        $em = $this->getDoctrine()->getManager();
        $referringProviderHealthFacility = $em->getRepository('RxConnexionBundle:ReferringProviderHealthFacilityEntity')->find($referringProviderHealthFacility_form['id'] );
        if(!$referringProviderHealthFacility) {
            $referringProviderHealthFacility = new ReferringProviderHealthFacilityEntity();
        }
        $formOptions = array(
            'action' => $referringProviderHealthFacility_form['action'],
            'referringProvider_id' => $referringProviderHealthFacility_form['referringProvider']
        );
        $form = $this->createForm(ReferringProviderHealthFacilityForm::class, $referringProviderHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ReferringProviderHealthFacilityEntity')->validate($referringProviderHealthFacility_form);

        if(!count($errors)) {

            switch($referringProviderHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Referring Provider Health Facility',
                            $em->getClassMetadata(ReferringProviderHealthFacilityEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $referringProviderHealthFacility;
                        $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(
                        'Referring Provider Health Facility',
                        $em->getClassMetadata(ReferringProviderHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $referringProviderHealthFacility;
                    $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(
                        'Referring Provider Health Facility',
                        $em->getClassMetadata(ReferringProviderHealthFacilityEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $referringProviderHealthFacility;
                    $newAT->parseDetails();
                    $em->persist($newAT);


                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($referringProviderHealthFacility);
                        $referringProviderHealthFacility->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("/referring_provider_health_facility_autocomplete", name="referring_provider_health_facility_autocomplete")
     */
    public function referring_provider_health_facility_autocompleteAction(Request $request) {

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

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

        return new JsonResponse($result);
    }



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

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

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

        return new JsonResponse($result);
    }
}