<?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\LocationEntity;
use RxConnexionBundle\Form\LocationForm;

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

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

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

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

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


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

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

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

            $location_form = $request->get($form->getName());
            $result = $this->processForm($location_form, $location, $form, $request);

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

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

        return $this->render('@RxConnexion/Location/form.html.twig', array(
            'title' => $title,
            'page_title' => $title,
            'javascripts' => array('rxconnexion/admin/js/location/location_form.js'),
            'form' => $form->createView(),
            'action' => $action,
            'id' => $id
        ));
    }

    private function processForm($location_form, $location, $form, Request $request) {

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

        $errors = $em->getRepository('RxConnexionBundle:LocationEntity')->validate($location_form);

        if(!count($errors)) {

            switch($location_form['action']) {

                case 'n': // new

                    $form->handleRequest($request);

                    if ($form->isValid()) {

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

//                        $newAT = new AuditTrailEntity(
//                            'Device',
//                            $em->getClassMetadata(DeviceEntity::class)->getTableName(),
//                            AuditTrailEntity::AXN_NEW
//                        );
//                        $newAT->entity = $device;
//                        $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(
//                        'Device',
//                        $em->getClassMetadata(DeviceEntity::class)->getTableName(),
//                        AuditTrailEntity::AXN_UPDATE
//                    );
//                    $newAT->entity = $device;
//                    $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

                    $location = $em->getRepository('RxConnexionBundle:LocationEntity')->find($location_form['id']);
                    $em->remove($location);

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

        $q = $request->query->all();

        $result = array(
            'query' => 'locations',
            'suggestions' => $this->getDoctrine()->getManager()->getRepository('RxConnexionBundle:LocationEntity')->autoCompleteSuggestions($q, $this->get('session')->get('userData'))
        );

        return new JsonResponse($result);
    }
}
