<?php

namespace App\Controller;

use App\Entity\AchatMonnaiePrestataire;
use App\Entity\AchatMonnaieAConfirmerPrestataire;
use App\Entity\Payment;
use App\Entity\Prestataire;
use App\Entity\Reconversion;
use App\Entity\TransactionPrestataireAdherent;
use App\Form\Type\AchatMonnaiePrestataireFormType;
use App\Form\Type\AchatMonnaieAConfirmerPrestataireFormType;
use App\Form\Type\GroupePrestataireInscriptionFormType;
use App\Form\Type\PrestataireInfosFormType;
use App\Form\Type\ReconversionFormType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class UserPrestataireController extends FluxController
{
    /**
     * @Route("/prestataireinfos", name="prestataire_infos")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function prestataireInfosAction(Request $request)
    {
        $presta = $this->session->get('_prestagere');
        $presta = $this->em->merge($presta);
        $originalAdresses = $presta->getGeolocs();

        $form = $this->createForm(PrestataireInfosFormType::class, $presta);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            foreach ($originalAdresses as $adresse) {
                if (false === $presta->getGeolocs()->contains($adresse)) {
                    $adresse->getPrestataires()->removeElement($presta);
                }
                $this->em->persist($adresse);
            }
            $this->em->persist($form->getData());
            $this->em->flush();
            $this->addFlash(
                'success',
                $this->translator->trans('Infos du prestataire modifiées !')
            );
            $referer = $request->headers->get('referer');
            if ($referer && !$request->isXmlHttpRequest()) {
                return $this->redirect($referer);
            } elseif (!$request->isXmlHttpRequest()) {
                return new Response('', Response::HTTP_BAD_REQUEST);
            }
        }

        return $this->redirectToRoute('index');
    }

    /**
     * @Route("/prestatairegroupes/inscription", name="groupeprestataire_inscription")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function groupePrestataireInscriptionAction(Request $request)
    {
        //#180: at this point, the Prestataire entity is detached from the EntityManager (because we get it from the session)
        $presta = $this->session->get('_prestagere');
        //#180: $presta now refers to the fully managed copy returned by the merge operation.
        $presta = $this->em->merge($presta);
        $originalGroupes = clone $presta->getGroupeprestataires();

        $form = $this->createForm(GroupePrestataireInscriptionFormType::class, $presta);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $prestataire = $form->getData();

            // Add flash messages if add/remove amap/marche
            foreach ($originalGroupes as $grp) {
                if (false === $presta->getGroupeprestataires()->contains($grp)) {
                    $this->addFlash(
                        'success',
                        $this->translator->trans('Vous êtes bien désinscrit de : {name} !', ['{name}' => $grp->getName()])
                    );
                    $grp->getPrestataires()->removeElement($presta);
                    $this->em->persist($grp);
                }
            }
            foreach ($prestataire->getGroupeprestataires() as $key => $groupePresta) {
                if (false === $originalGroupes->contains($groupePresta)) {
                    $this->addFlash(
                        'success',
                        $this->translator->trans('Vous êtes bien inscrit à : {name} !', ['{name}' => $groupePresta->getName()])
                    );
                }
            }

            $this->em->persist($prestataire);
            $this->em->flush();

            if ($request->isXmlHttpRequest()) {
                return new JsonResponse(['status' => 'success']);
            } else {
                $referer = $request->headers->get('referer');
                if ($referer && !$request->isXmlHttpRequest()) {
                    return $this->redirect($referer);
                } elseif (!$request->isXmlHttpRequest()) {
                    return new Response('', Response::HTTP_BAD_REQUEST);
                }
            }
        }

        return $this->redirectToRoute('index');
    }

    /**
     * @Route("/prestataire/transaction/{type}/", name="transactionPrestataireAdherent", defaults={"type": "adherent"})
     * @Route("/prestataire/transaction/{type}/", name="transactionPrestatairePrestataire", defaults={"type": "prestataire"})
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function transactionPrestataireAction($type, Request $request)
    {
        $entityName = 'App\Entity\TransactionPrestataire' . ucwords($type);
        $entity = new $entityName();
        $entity->setOperateur($this->getUser());
        $entity->setExpediteur($this->session->get('_prestagere'));
        $form = $this->createForm('App\Form\Type\TransactionPrestataire' . ucwords($type) . 'FormType', $entity);

        return $this->manageFluxForm(
            $request,
            $form
        );
    }

    /**
     * @Route("/prestataire/reconversion/", name="transactionReconversion")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function reconversionAction(Request $request)
    {
        $entity = new Reconversion();
        $entity->setOperateur($this->getUser());
        $entity->setExpediteur($this->session->get('_prestagere'));
        $form = $this->createForm(ReconversionFormType::class, $entity);

        return $this->manageFluxForm(
            $request,
            $form
        );
    }

    /**
     * @Route("/prestataire/achat-monnaie/", name="achatMonnaiePrestataire")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function achatMonnaiePrestataireAction(Request $request)
    {
        if (empty($this->getUser()) || empty($this->session->get('_prestagere'))) {
            return $this->redirectToRoute('index');
        }

        $entity = new AchatMonnaiePrestataire();
        $entity->setReconverti(true);
        $form = $this->createForm(AchatMonnaiePrestataireFormType::class, $entity);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($form->get('payOther')->isClicked()) {
                return $this->redirectToRoute('achatMonnaieAConfirmerPrestataire');
            } else {
                return $this->preparePaymentAction(
                    $form,
                    Payment::TYPE_ACHAT_MONNAIE_PRESTA
                );
            }
        }

        return $this->render('@kohinos/flux/transaction.html.twig', [
            'form' => $form->createView(),
            'title' => $this->translator->trans('Achat de monnaie locale'),
        ]);
    }

    /**
     * @Route("/prestataire/demande/achat-monnaie/", name="achatMonnaieAConfirmerPrestataire")
     * @IsGranted("ROLE_PRESTATAIRE")
     */
    public function achatMonnaieAConfirmerPrestataireAction(Request $request)
    {
        if (empty($this->getUser()) || empty($this->session->get('_prestagere'))) {
            return $this->redirectToRoute('index');
        }

        $entity = new AchatMonnaieAConfirmerPrestataire();
        $entity->setReconverti(true);
        $form = $this->createForm(AchatMonnaieAConfirmerPrestataireFormType::class, $entity);

        return $this->manageFluxForm(
            $request,
            $form,
            '@kohinos/flux/demande_achat_monnaie.html.twig',
            ['title' => $this->translator->trans("Demande d'achat de monnaie locale numérique")]
        );
    }
}
