<?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\BankEntity;
use RxConnexionBundle\Form\BankForm;

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

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

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

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

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

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

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

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

            $bank_form = $request->get($form->getName());
            $result = $this->processForm($bank_form, $bank, $form, $request);

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

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

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

    private function processForm($bank_form, $bank, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:BankEntity')->validate($bank_form);

        if(!count($errors)) {

            switch($bank_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

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

//                        $this->get('rx_connexion.glAccountService')->processCmsSlByLink('Bank', $bank);

                        $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

                    $bank_obj = $em->getRepository('RxConnexionBundle:BankEntity')->find($bank_form['id']);

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

                    $bank_obj->setCode($bank_form['code']);
                    $bank_obj->setDescription($bank_form['description']);
                    $bank_obj->setInitCheckNo($bank_form['init_check_no']);

//                    $newAT->parseInformation('Update');
//                    $em->persist($newAT);

                    $em->flush();

//                    $this->get('rx_connexion.glAccountService')->processCmsSlByLink('Bank', $bank_obj);

                    $this->get('session')->getFlashBag()->set('success_messages', 'Record Successfully Updated.');
                    $result['redirect'] = 'index';

                    break;

                case 'd': // delete

                    $bank = $em->getRepository('RxConnexionBundle:BankEntity')->find($bank_form['id']);
                    $em->remove($bank);

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

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

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

        return new JsonResponse($result);
    }
}
