<?php

namespace RxConnexionBundle\Controller;

use RxConnexionBundle\Entity\ItemPackageItemEntity;
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\ItemPackageEntity;

use RxConnexionBundle\Form\ItemPackageForm;

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

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

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

    /**
     * @Route("/ajax_list", name="item_package_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 Item Package Update'), false);

            $data = $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:ItemPackageEntity')->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_package_form', array(
                        'action' => 'u',
                        'id' => $id
                    ));
                    $action = "<a class='action-button-style' href='$url'>Update</a>";
                }

                $values = array(
                    $row['code'],
                    $row['description'],
                    $row['items'],
                    $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_package_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 Package New', 'Admin Item Package Update'))) return $authService->redirectToHome();

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

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

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

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

            $item_package_form = $request->get($form->getName());
            $result = $this->processForm($item_package_form, $item_package, $form, $request);

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

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

        return $this->render('@RxConnexion/ItemPackage/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/itemPackage/itemPackage_form.js?v=1.0.2'),
            'form' => $form->createView(),
            'action' => $action,
            'itemPackage' => $item_package,
            'id' => $id
        ));
    }

    private function processForm($item_package_form, $item_package, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:ItemPackageEntity')->validate($item_package_form);

        if(!count($errors)) {

            switch($item_package_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

                    $form->handleRequest($request);

                    if ($form->isValid()) {

                        //$em->remove($item_package);
                        $item_package->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("/item/remove", name="item_package_remove_detail")
     */
    public function remove_detailAction(Request $request) {

        $authService = $this->get('rx_connexion.authService');
        if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
        if(!$authService->isUserHasAccesses(array('Admin Item Package New', 'Admin Item Package Update'))) return $authService->redirectToHome();
        $em = $this->getDoctrine()->getManager();

        $id = $request->get('id');

        $result = array(
            'success' => false,
            'msg' => '',
        );

        $itemPackageItem = $em->getRepository(ItemPackageItemEntity::class)->find(base64_decode($id));
        if($itemPackageItem){
            $itemPackageItem->isDeleted(true);
            $em->flush();
            $result['success'] = true;
        } else {
            $result['msg'] = 'Item not found. Please contact administrator.';
        }

        return new JsonResponse($result);
    }


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

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

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

        return new JsonResponse($result);
    }

}
