<?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\ItemSizeEntity;
use RxConnexionBundle\Form\ItemSizeForm;

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

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

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

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

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

        $itemSize_obj = $em->getRepository('RxConnexionBundle:ItemSizeEntity')->find(base64_decode($id));
        $itemSize = new ItemSizeEntity($itemSize_obj);

        $formOptions = array('action' => $action);
        $form = $this->createForm(new ItemSizeForm($itemSize_obj), $itemSize, $formOptions);

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

            $itemSize_form = $request->get($form->getName());
            $result = $this->processForm($itemSize_form, $itemSize, $form, $request);

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

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

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

    private function processForm($itemSize_form, $itemSize, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:ItemSizeEntity')->validate($itemSize_form);

        if(!count($errors)) {

            switch($itemSize_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

                    $itemSize_obj = $em->getRepository('RxConnexionBundle:ItemSizeEntity')->find($itemSize_form['id']);

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

                    $itemSize_obj->setCode($itemSize_form['code']);
                    $itemSize_obj->setDescription($itemSize_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

                    $itemSize = $em->getRepository('RxConnexionBundle:ItemSizeEntity')->find($itemSize_form['id']);
                    $em->remove($itemSize);

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

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

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

        return new JsonResponse($result);
    }
}
