<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\SalesAgentReferringHealthFacilityEntity;
use RxConnexionBundle\Form\SalesAgentReferringHealthFacilityForm;
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\SalesAgentEntity;

use RxConnexionBundle\Form\SalesAgentForm;

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

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

        return $this->render('@RxConnexion/SalesAgent/index.html.twig', array(
            'title' => 'Manage Sales Agent',
            'page_title' => 'Manage Sales Agent',
            'javascripts' => array('rxconnexion/admin/js/salesAgent/salesAgent.js?v=1.0.0')
        ));
    }

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

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

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

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

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

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

                $values = array(
                    $row['full_name'],
                    $row['rate'],
                    $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 = "sales_agent_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 Sales Agent New', 'Admin Sales Agent Update'))) return $authService->redirectToHome();

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

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

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

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

            $salesAgent_form = $request->get($form->getName());
            $result = $this->processForm($salesAgent_form, $salesAgent, $form, $request);

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

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

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

    private function processForm($salesAgent_form, $salesAgent, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:SalesAgentEntity')->validate($salesAgent_form);

        if(!count($errors)) {

            switch($salesAgent_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Sales Agent',
                            $em->getClassMetadata(SalesAgentEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $salesAgent;
                        $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(
                        'Sales Agent',
                        $em->getClassMetadata(SalesAgentEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $salesAgent;
                    $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(
                        'Sales Agent',
                        $em->getClassMetadata(SalesAgentEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $salesAgent;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

        $em = $this->getDoctrine()->getManager();
        $salesAgent = $em->getRepository('RxConnexionBundle:SalesAgentEntity')->find(base64_decode($salesAgent_id));

        $title = 'Manage Sales Agent - ' . $salesAgent->getFullName();
        return $this->render('@RxConnexion/SalesAgent/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/salesAgent/salesAgent_detail.js?v=1.0.0'
            ),
            'salesAgent_id' => $salesAgent_id,
            'salesAgent' => $salesAgent,
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/sales_agent_referring_health_facility_ajax_list", name="sales_agent_referring_health_facility_ajax_list")
     */
    public function sales_agent_referring_health_facility_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 Sales Agent Detail Referring Health Facility Update'), false);

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

                $values = array(
                    $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_affiliate/form/{salesAgent_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "sales_agent_health_referring_facility_form"
     * )
     */
    public function sales_agent_health_referring_facility_formAction($salesAgent_id, $action, $id) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'salesAgent_id' => $salesAgent_id
        );
        $form = $this->createForm(SalesAgentReferringHealthFacilityForm::class, $salesAgentReferringHealthFacility, $formOptions);


        $title = $action === 'n' ? 'Add Affiliate' : 'Update ' . $salesAgentReferringHealthFacility->getReferringHealthFacility()->getDescription();

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

    /**
     * @Route(
     *      "/sales_agent_referring_affiliate/save_action",
     *      name = "sales_agent_referring_affiliate_save"
     * )
     */
    public function sales_agent_referring_affiliate_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 Sales Agent Detail Referring Health Facility New', 'Admin Sales Agent Detail Referring Health Facility Update'))) return $authService->redirectToHome();

        $salesAgentReferringHealthFacility_form = $request->get('salesAgentReferringHealthFacility');
        $em = $this->getDoctrine()->getManager();
        $salesAgentReferringHealthFacility = $em->getRepository('RxConnexionBundle:SalesAgentReferringHealthFacilityEntity')->find($salesAgentReferringHealthFacility_form['id']);
        if(!$salesAgentReferringHealthFacility) {
            $salesAgentReferringHealthFacility = new SalesAgentReferringHealthFacilityEntity();
        }

        $formOptions = array(
            'action' => $salesAgentReferringHealthFacility_form['action'],
            'salesAgent_id' => $salesAgentReferringHealthFacility_form['salesAgent']
        );
        $form = $this->createForm(SalesAgentReferringHealthFacilityForm::class, $salesAgentReferringHealthFacility, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:SalesAgentReferringHealthFacilityEntity')->validate($salesAgentReferringHealthFacility_form);

        if(!count($errors)) {

            switch($salesAgentReferringHealthFacility_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

        return new JsonResponse($result);
    }
}
