<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ItemEntity;
use RxConnexionBundle\Entity\ItemPriceEntity;
use RxConnexionBundle\Form\ItemPriceForm;
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\Form\ItemForm;

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

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

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

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

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

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

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

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

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

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

                $values = array(
                    $row['itemCat'],
                    $row['itemSubCat'],
                    $row['itemCompany'],
                    $row['code'],
                    $row['type'],
                    $row['description'],
                    $row['startDate'],
                    $row['endDate'],
                    $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 = "item_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 Items New', 'Admin Items Update'))) return $authService->redirectToHome();

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

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

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

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

            $item_form = $request->get($form->getName());
            $result = $this->processForm($item_form, $item, $form, $request);

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

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

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

    private function processForm($item_form, $item, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:ItemEntity')->validate($item_form);

        if(!count($errors)) {

            switch($item_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

        $em = $this->getDoctrine()->getManager();
        $item = $em->getRepository('RxConnexionBundle:ItemEntity')->find(base64_decode($item_id));

        $title = 'Manage Item - ' . $item->getDescription();
        return $this->render('@RxConnexion/Item/detail.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array(
                'rxconnexion/admin/js/item/item_detail.js?v=1.0.0'
            ),
            'item_id' => $item_id,
            'item' => $item,
            'tab' => $request->query->get('tab')
        ));
    }

    /**
     * @Route("/item_price_ajax_list", name="item_price_ajax_list")
     */
    public function item_price_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 Items Price Update'), false);

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

                $values = array(
                    number_format($row['price'], 2),
                    $row['startDate'],
                    $row['endDate'],
                    $action
                );

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

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

        return new JsonResponse($result);
    }

    /**
     * @Route(
     *      "/item_price/form/{item_id}/{action}/{id}",
     *      defaults = {
     *          "action":  "n",
     *          "id": 0
     *      },
     *      requirements = {
     *          "action": "n|u"
     *      },
     *      name = "item_price_form"
     * )
     */
    public function item_price_formAction($item_id, $action, $id, Request $request) {

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

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

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

        $formOptions = array(
            'action' => $action,
            'item_id' => $item_id
        );
        $form = $this->createForm(ItemPriceForm::class, $itemPrice, $formOptions);


        $title = $action === 'n' ? 'Add Branch' : 'Update ' . $itemPrice->getPrice()    ;

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

    /**
     * @Route(
     *      "/item_price/save_action",
     *      name = "item_price_save"
     * )
     */
    public function item_price_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 Items Price New', 'Admin Items Price Update'))) return $authService->redirectToHome();

        $itemPrice_form = $request->get('item_price');
        $em = $this->getDoctrine()->getManager();
        $itemPrice = $em->getRepository('RxConnexionBundle:ItemPriceEntity')->find($itemPrice_form['id'] );
        if(!$itemPrice) {
            $itemPrice = new ItemPriceEntity();
        }
        $formOptions = array(
            'action' => $itemPrice_form['action'],
            'item_id' => $itemPrice_form['item']
        );
        $form = $this->createForm(ItemPriceForm::class, $itemPrice, $formOptions);
        $errors = $em->getRepository('RxConnexionBundle:ItemPriceEntity')->validate($itemPrice_form);

        if(!count($errors)) {

            switch($itemPrice_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if($form->isValid()) {

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

                        $newAT = new AuditTrailEntity(
                            'Item Price',
                            $em->getClassMetadata(ItemPriceEntity::class)->getTableName(),
                            AuditTrailEntity::AXN_NEW
                        );
                        $newAT->entity = $itemPrice;
                        $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($itemPrice);
                    $em->flush();

                    $newAT = new AuditTrailEntity(
                        'Item Price',
                        $em->getClassMetadata(ItemPriceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_UPDATE
                    );
                    $newAT->entity = $itemPrice;
                    $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(
                        'Item Price',
                        $em->getClassMetadata(ItemPriceEntity::class)->getTableName(),
                        AuditTrailEntity::AXN_DELETE
                    );
                    $newAT->entity = $itemPrice;
                    $newAT->parseDetails();
                    $em->persist($newAT);

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($itemPrice);
                        $itemPrice->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("/ajax_list_transfer_inventory", name="item_ajax_list_transfer_inventory")
     */
    public function ajax_list_transfer_inventory(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:ItemEntity')->ajax_list_transfer_inventory($get, $this->get('session')->get('userData'));
        }

        return new JsonResponse($result);
    }

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

        $result = array(
            'query' => 'items',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ItemEntity')->autocomplete_suggestions($request)
        );

        return new JsonResponse($result);
    }

}
