<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\UserGroupAccountUserEntity;
use RxConnexionBundle\Entity\UserGroupEntity;
use RxConnexionBundle\Form\UserGroupForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use RxConnexionBundle\Entity\AuditTrailEntity;
use RxConnexionBundle\Form\UserGroupAccountUserForm;

/**
 * @Route("/main/user-group")
 */
class UserGroupController extends Controller
{
    /**
     * @Route("/", name="user_group")
     */
    public function indexAction(Request $request)
    {
        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin User Group'))) return $authService->redirectToHome();

        return $this->render('@RxConnexion/UserGroup/index.html.twig', array(
            'title' => 'User Group',
            'page_title' => 'User Group',
            'javascripts' => array('rxconnexion/admin/js/userGroup/userGroup.js?v=1.0.1'),
        ));
    }

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

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

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

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

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

                if($hasDetail){
                    $detailsUrl = $this->generateUrl('user_group_detail', array(
                        'user_group_id' => base64_encode($row['id'])

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

                $values = array(
                    $row['id'],
                    $row['code'],
                    $row['description'],
//                    0,
                    $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 = "user_group_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 User Group New', 'Admin User Group Update'))) return $authService->redirectToHome();

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

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

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

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

            $userGroup_form = $request->get($form->getName());
            $result = $this->processForm($userGroup_form, $userGroup, $form, $request);

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

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

        return $this->render('@RxConnexion/UserGroup/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id
        ));
    }

    private function processForm($userGroup_form, UserGroupEntity $userGroup, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:UserGroupEntity')->validate($userGroup_form);

        if(!count($errors)) {

            switch($userGroup_form['action']) {

                case 'n': // new

                    //$form->handleRequest($request);
                    $form->submit($userGroup_form, false);

                    if($form->isValid()) {

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

                        /*$newAT = new AuditTrailEntity(
                            'Account',
                            $em->getClassMetadata(AccountEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $UserGroup;
                        $newAT->parseDetails();
                        $em->persist($newAT);
                        $em->flush();*/

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

                    } else {

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

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

                    break;

                case 'u': // update

                    /*$newAT = new AuditTrailEntity(
                        'Account',
                        $em->getClassMetadata(AccountEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $UserGroup;
                    $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

                    $form->submit($userGroup_form, false);

                    /*$newAT = new AuditTrailEntity(
                        'Account',
                        $em->getClassMetadata(AccountEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $UserGroup;
                    $newAT->parseDetails();
                    $em->persist($newAT);*/

                    if($form->isValid()) {

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

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

        $em = $this->getDoctrine()->getManager();
        $userGroup = $em->getRepository('RxConnexionBundle:UserGroupEntity')->find(base64_decode($user_group_id));

        $title = 'Manage User Group - ' . $userGroup->getDescription();
        return $this->render('@RxConnexion/UserGroup/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/userGroup/userGroup_detail.js?v=1.0.0'
            ),
            'user_group_id' => $user_group_id,
            'userGroup' => $userGroup,
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/user_group_account_user_ajax_list", name="user_group_account_user_ajax_list")
     */
    public function user_group_account_user_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()) {

            $userData = $this->get('session')->get('userData');

            $hasUpdate = $authService->isUserHasAccesses(array('Admin User Group Account User Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:UserGroupAccountUserEntity')->account_user_ajax_list($get, $userData);

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

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

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

                $values = array(
                    $row['fullName'],
                    $row['startDate'],
                    $row['endDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }


    /**
     * @Route(
     *      "/account_user/form/{user_group_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "user_group_account_user_form"
     * )
     */
    public function user_group_account_user_formAction($user_group_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'user_group_id' => $user_group_id
        );
        $form = $this->createForm(UserGroupAccountUserForm::class, $userGroupAccountUser, $formOptions);

        $title = $action === 'n' ? 'Add User' : 'Update ' . $userGroupAccountUser->getAccountUser()->getFullName();

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

    /**
     * @Route(
     *      "/account_user/save_action",
     *      name = "user_group_account_user_save"
     * )
     */
    public function user_group_account_user_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 Group User Account User New', 'Admin Group User Account User Update'))) return $authService->redirectToHome();

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

        $formOptions = array(
            'action' => $userGroupAccountUser_form['action'],
            'user_group_id' => $userGroupAccountUser_form['user_group']
        );
        $form = $this->createForm(UserGroupAccountUserForm::class, $userGroupAccountUser, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:UserGroupAccountUserEntity')->validate($userGroupAccountUser_form);

        if(!count($errors)) {

            switch($userGroupAccountUser_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'User Group Account User',
                            $em->getClassMetadata(UserGroupAccountUserEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $userGroupAccountUser;
                        $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

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

                    $newAT = new AuditTrailEntity(
                        'User Group Account User',
                        $em->getClassMetadata(UserGroupAccountUserEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $userGroupAccountUser;
                    $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(
                        'User Group Account User',
                        $em->getClassMetadata(UserGroupAccountUserEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $userGroupAccountUser;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

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

        return new JsonResponse($result);
    }

}