<?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\CreditHistoryInterface;
use Lc\ShopBundle\Context\MerchantUtilsInterface;
use Lc\ShopBundle\Context\OrderUtilsInterface;
use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Form\Backend\UserMerchant\CreditHistoryType;
use Lc\ShopBundle\Services\CreditUtils;
use Lc\ShopBundle\Services\Utils;
use Lc\ShopBundle\Services\UtilsManager;
use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;

class UserMerchantController extends AdminController
{
        protected $creditUtils;

        public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em, MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator)
        {
                parent::__construct($security, $userManager, $em, $mailjetTransport, $utilsManager, $translator);
                $this->creditUtils = $utilsManager->getCreditUtils();
        }

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

                $creditHistoryClass = $this->em->getClassMetadata(CreditHistoryInterface::class);
                $creditHistory = new $creditHistoryClass->name;

                $addCreditHistoryForm = $this->createForm(CreditHistoryType::class, $creditHistory);
                $addCreditHistoryForm->handleRequest($this->request);
                if ($addCreditHistoryForm->isSubmitted() && $addCreditHistoryForm->isValid()) {
                        $creditHistory->setUserMerchant($userMerchant);
                        if($this->creditUtils->saveCreditHistory($creditHistory)){

                                //TODo envoyer un email à l'utilisateur
                                $this->utils->addFlash('success', 'success.credit.added');
                        }else{
                                $this->utils->addFlash('error', 'error.credit.notAdded');
                        }

                } else {
                        $this->utils->addFlash('error', $addCreditHistoryForm->getErrors());
                }
                return $this->redirectToRoute('easyadmin', [
                        'action' => 'show',
                        'entity' => $this->request->query->get('entity'),
                        'id' => $userMerchant->getId()
                ]);
        }
        protected 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]);

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

                //ETAPE 1 Choix de l'utilisateur
                $user = $newForm->get('user')->getData();

                if ($user == null) {
                        $user = $this->getUserViaFirstStepForm($entity);
                }

                if (!$user instanceof UserInterface) return $user;
                else {

                        $userMerchant = $this->creditUtils->activeCredit($user);

                        return $this->redirectToRoute('easyadmin', [
                                'action' => 'edit',
                                'entity' => $this->entity['name'],
                                'id' => $userMerchant->getId()
                        ]);
                }
        }

        public function getUserViaFirstStepForm($entity)
        {
                $userClass = $this->em->getClassMetadata(UserInterface::class);

                $userChoiceForm = $this->createFormBuilder($entity)
                        ->add('user', EntityType::class, array(
                                'class' => $userClass->name
                        ))
                        ->add('nextStep', SubmitType::class)
                        ->getForm();
                $userChoiceForm->handleRequest($this->request);
                if ($userChoiceForm->isSubmitted() && $userChoiceForm->isValid()) {
                        return $userChoiceForm->get('user')->getData();
                }

                $parameters = [
                        'form' => $userChoiceForm->createView(),
                        'formView' => 'default',
                        'entity' => $entity,
                ];

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

        /**
         * The method that is executed when the user performs a 'show' action on an entity.
         *
         * @return Response
         */
        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'];


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

                $parameters = [
                        'entity' => $entity,
                        'fields' => $fields
                ];

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

        public function renderUserMerchantTemplate($actionName, $templatePath, array $parameters = []){
                if ($actionName == 'show') {
                        $parameters['add_credit_history_form'] = $this->createCustomForm(CreditHistoryType::class, 'addCreditHistory', $parameters, false)->createView();
                }

                return parent::renderTemplate($actionName, $templatePath, $parameters);

        }

        /**
         * Réécriture de edit action pr rediriger vers le show */
        public function editAction()
        {
                $id = $this->request->query->get('id');
                $entity = $this->request->query->get('entity');

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

}
