<?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\PurposeEntity;
use RxConnexionBundle\Form\PurposeForm;

/**
 * @Route("/admin/purpose")
 */
class PurposeController extends Controller
{
    /**
     * @Route("", name="purpose")
     */
    public function indexAction() {

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

        return $this->render('@RxConnexion/Purpose/index.html.twig', array(
            'title' => 'Manage Purpose',
            'page_title' => 'Manage Purpose',
            'javascripts' => array('rxconnexion/admin/js/purpose/purpose.js')
        ));
    }

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

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

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

        if($this->get('rx_connexion.authService')->isLoggedIn()) {
            $result = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:PurposeEntity')->ajax_list($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/form/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "purpose_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 Purpose New', 'Admin Purpose Update'))) return $authService->redirectToHome();

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

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

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

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

            $purpose_form = $request->get($form->getName());
            $result = $this->processForm($purpose_form, $purpose, $form, $request);

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

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

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

    private function processForm($purpose_form, $purpose, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:PurposeEntity')->validate($purpose_form);

        if(!count($errors)) {

            switch($purpose_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        $em->persist($purpose);
                        $em->flush();
//
//                        $newAT = new AuditTrailEntity();
//                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                        $newAT->entity = $purpose;
//                        $newAT->setRefTable('purpose');
//                        $newAT->parseInformation('New');
//                        $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

//                    $purpose_obj = $em->getRepository('RxConnexionBundle:PurposeEntity')->find($purpose_form['id']);

//                    $newAT = new AuditTrailEntity();
//                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                    $newAT->entity = $purpose_obj;
//                    $newAT->setRefTable('purpose');
//                    $newAT->parseOriginalDetails();

//                    $purpose_obj->setCode($purpose_form['code']);
//                    $purpose_obj->setDescription($purpose_form['description']);
//
//                    $newAT->parseInformation('Update');
//                    $em->persist($newAT);

                    $em->flush();

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

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

                    break;

                case 'd': // delete

                    $purpose = $em->getRepository('RxConnexionBundle:PurposeEntity')->find($purpose_form['id']);
                    $purpose->isDeleted(true);
//                    $em->remove($purpose);

//                    $newAT = new AuditTrailEntity();
//                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
//                    $newAT->entity = $purpose;
//                    $newAT->setRefTable('purpose');
//                    $newAT->parseInformation('Delete');
//                    $em->persist($newAT);

                    $em->flush();

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

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

                    break;
            }

            $result['success'] = true;

        } else {

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

            $result['success'] = false;
        }

        return $result;
    }

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

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

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

        return new JsonResponse($result);
    }
}
