<?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\ItemUnitEntity;
use RxConnexionBundle\Form\ItemUnitForm;

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

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

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

    /**
     * @Route("/ajax_list", name="item_unit_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:ItemUnitEntity')->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 = "item_unit_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 Item Unit New', 'Admin Item Unit Update'))) return $authService->redirectToHome();

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

        $itemUnit_obj = $em->getRepository('RxConnexionBundle:ItemUnitEntity')->find(base64_decode($id));
        $itemUnit = new ItemUnitEntity($itemUnit_obj);

        $formOptions = array('action' => $action);
        $form = $this->createForm(new ItemUnitForm($itemUnit_obj), $itemUnit, $formOptions);

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

            $itemUnit_form = $request->get($form->getName());
            $result = $this->processForm($itemUnit_form, $itemUnit, $form, $request);

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

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

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

    private function processForm($itemUnit_form, $itemUnit, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:ItemUnitEntity')->validate($itemUnit_form);

        if(!count($errors)) {

            switch($itemUnit_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

                        $newAT = new AuditTrailEntity();
                        $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                        $newAT->entity = $itemUnit;
                        $newAT->setRefTable('item_unit');
                        $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

                    $itemUnit_obj = $em->getRepository('RxConnexionBundle:ItemUnitEntity')->find($itemUnit_form['id']);

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

                    $itemUnit_obj->setCode($itemUnit_form['code']);
                    $itemUnit_obj->setDescription($itemUnit_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

                    $itemUnit = $em->getRepository('RxConnexionBundle:ItemUnitEntity')->find($itemUnit_form['id']);
                    $em->remove($itemUnit);

                    $newAT = new AuditTrailEntity();
                    $newAT->setUser($em->getReference('RxConnexionBundle:UserEntity', base64_decode($_COOKIE['userId'])));
                    $newAT->entity = $itemUnit;
                    $newAT->setRefTable('item_unit');
                    $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="item_unit_autocomplete")
     */
    public function autocompleteAction(Request $request) {

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

        $result = array(
            'query' => 'itemUnits',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ItemUnitEntity')->autoCompleteSuggestions($q)
        );

        return new JsonResponse($result);
    }
}
