<?php

namespace Lc\ShopBundle\Controller\Backend;

use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use FOS\UserBundle\Model\UserManagerInterface;
use Lc\ShopBundle\Context\OrderShopInterface;
use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Form\Backend\Ticket\TicketMessageType;
use Lc\ShopBundle\Form\Backend\Ticket\TicketStatusType;
use Lc\ShopBundle\Model\Ticket;
use Lc\ShopBundle\Services\UtilsManager;
use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;

class TicketController extends AdminController
{
        protected $ticketUtils;
        protected $userUtils;

        public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em, MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator, SessionInterface $session)
        {
                parent::__construct($security, $userManager, $em, $mailjetTransport, $utilsManager, $translator, $session);
                $this->ticketUtils = $utilsManager->getTicketUtils();
                $this->userUtils = $utilsManager->getUserUtils();
        }

        public function persistTicketEntity($entity, $form)
        {
                $entity->setStatus(Ticket::TICKET_STATUS_OPEN);

                $ticket = $this->ticketUtils->createTicket([
                        'user' => $entity->getUser(),
                        'type' => $entity->getType(),
                        'orderShop' => $entity->getOrderShop(),
                        'subject' => $entity->getSubject(),
                        'message' => $form->get('message')->getData(),
                        'createByAdmin' => true,
                ]);

        }

        protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
        {

                $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

                if ($this->filtersForm->get('status')->getData() === null) {
                        $queryBuilder->andWhere('entity.status LIKE :open OR entity.status LIKE :beingprocessed');
                        $queryBuilder->setParameter('open', Ticket::TICKET_STATUS_OPEN);
                        $queryBuilder->setParameter('beingprocessed', Ticket::TICKET_STATUS_BEING_PROCESSED);
                }

                return $queryBuilder;
        }

        public function showAction()
        {
                $this->dispatch(EasyAdminEvents::PRE_SHOW);

                $id = $this->request->query->get('id');
                $easyadmin = $this->request->attributes->get('easyadmin');
                $entity = $easyadmin['item'];

                $fields = $this->entity['show']['fields'];
                $deleteForm = $this->createDeleteForm($this->entity['name'], $id);

                $this->dispatch(EasyAdminEvents::POST_SHOW, [
                        'deleteForm' => $deleteForm,
                        'fields' => $fields,
                        'entity' => $entity,
                ]);

                $parameters = [
                        'entity' => $entity,
                        'fields' => $fields,
                        'delete_form' => $deleteForm->createView(),
                ];

                return $this->executeDynamicMethod('render<EntityName>Template', ['show', $this->entity['templates']['show'], $parameters]);
        }

        /**
         * The method that is executed when the user performs a 'show' action on an entity.
         *
         * @return Response
         */
        public function renderTicketTemplate($actionName, $templatePath, array $parameters = [])
        {
                if ($actionName == 'show') {
                        $parameters['form_add_ticket_message'] = $this->createCustomForm(TicketMessageType::class, 'newMessageTicket', $parameters, false)->createView();
                        $parameters['form_ticket_status'] = $this->createCustomForm(TicketStatusType::class, 'ticketStatus', $parameters)->createView();
                }
                return parent::renderTemplate($actionName, $templatePath, $parameters);

        }


        public function ticketStatusAction()
        {
                $easyadmin = $this->request->attributes->get('easyadmin');
                $ticket = $easyadmin['item'];

                $formTicketStatusForm = $this->createForm(TicketStatusType::class, $ticket);
                $formTicketStatusForm->handleRequest($this->request);

                if ($formTicketStatusForm->isSubmitted() && $formTicketStatusForm->isValid()) {
                        $this->em->persist($ticket);
                        $this->em->flush();

                        $this->utils->addFlash('success', 'success.ticket.statusChange');
                } else {
                        $this->utils->addFlash('error', $formTicketStatusForm->getErrors());
                }
                $response['flashMessages'] = $this->utils->getFlashMessages();

                return new Response(json_encode($response));
        }

        public function newMessageTicketAction()
        {
                $easyadmin = $this->request->attributes->get('easyadmin');
                $ticket = $easyadmin['item'];

                $formAddTicketMessage = $this->createForm(TicketMessageType::class);
                $formAddTicketMessage->handleRequest($this->request);

                if ($formAddTicketMessage->isSubmitted() && $formAddTicketMessage->isValid()) {
                        $this->ticketUtils->createTicketMessage(array(
                                'ticket' => $ticket,
                                'message' => $formAddTicketMessage->get('message')->getData(),
                                'answerByAdmin' => true
                        ));

                        $this->utils->addFlash('success', 'success.ticket.addMessage');
                } else {
                        $this->utils->addFlash('error', $formAddTicketMessage->getErrors());
                }

                return $this->redirectToRoute('easyadmin', [
                        'action' => 'show',
                        'entity' => 'Ticket',
                        'id' => $ticket->getId()
                ]);
        }

        public function newAction()
        {
                $this->dispatch(EasyAdminEvents::PRE_NEW);

                $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');

                $easyadmin = $this->request->attributes->get('easyadmin');
                $easyadmin['item'] = $entity;
                $this->request->attributes->set('easyadmin', $easyadmin);

                $fields = $this->entity['new']['fields'];

                $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);

                if ($this->request->request->get('user')) {
                        $userRepo = $this->em->getRepository(UserInterface::class);
                        $newForm->get('user')->setData($userRepo->find($this->request->request->get('user')));
                }

                if ($this->request->request->get('orderId')) {
                        $newForm->get('orderId')->setData($this->request->request->get('orderId'));
                }


                $newForm->handleRequest($this->request);

                if ($newForm->isSubmitted() && $newForm->isValid()) {

                        if ($newForm->get('orderId')->getData()) {
                                $orderShopRepo = $this->em->getRepository(OrderShopInterface::class);
                                $orderShop = $orderShopRepo->find($newForm->get('orderId')->getData());
                                if($orderShop)$entity->setOrderShop($orderShop);
                        }


                        $this->processUploadedFiles($newForm);

                        $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
                        $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
                        $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);

                        $this->utils->addFlash('success', 'success.ticket.addMessage');

                        if ($this->request->isXmlHttpRequest()) {
                                $response['type'] = 'success';
                                $response['flashMessages'] = $this->utils->getFlashMessages();
                                return new Response(json_encode($response));
                        } else {
                                return $this->redirectToReferrer();
                        }


                }
                $this->dispatch(EasyAdminEvents::POST_NEW, [
                        'entity_fields' => $fields,
                        'form' => $newForm,
                        'entity' => $entity,
                ]);

                $parameters = [
                        'form' => $newForm->createView(),
                        'entity_fields' => $fields,
                        'entity' => $entity,
                ];
                if ($this->request->isXmlHttpRequest()) {
                        $response['modal'] = $this->renderView('@LcShop/backend/ticket/modal/create.html.twig', $parameters);
                        return new Response(json_encode($response));
                } else {
                        return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
                }
        }
}
