<?php

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\Payment;
use App\Entity\Usergroup;
use App\Form\Type\AdhererFormType;
use App\Security\LoginAuthenticator;
use Doctrine\ORM\EntityManagerInterface;
use Gamez\Symfony\Component\Serializer\Normalizer\UuidNormalizer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class AdhesionController extends AbstractController
{
    private $em;
    private $authenticator;
    private $guardHandler;

    public function __construct(
        EntityManagerInterface $em,
        RouterInterface $router,
        LoginAuthenticator $authenticator,
        GuardAuthenticatorHandler $guardHandler)
    {
        $this->em = $em;
        $this->router = $router;
        $this->authenticator = $authenticator;
        $this->guardHandler = $guardHandler;
    }

    /**
     * @Route("/adherer", name="adherer")
     */
    public function adhererAction(Request $request)
    {
        if ($this->getParameter('tav_env') == true) {
            return $this->redirect($this->router->generate('index'));
        }

        $adherent = new Adherent();

        $form = $this->createForm(AdhererFormType::class, $adherent);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                // CB PAIEMENT USE PAYZEN
                if ($form->has('save') && $form->get('save')->isClicked()) {
                    $adherentNew = $form->getData();

                    // Serialize form data in json to store with payment object and persist when payment is valid
                    $encoders = [new JsonEncoder()];
                    $normalizers = [new UuidNormalizer(), new ObjectNormalizer()];
                    $serializer = new Serializer($normalizers, $encoders);

                    $data = $serializer->normalize(
                        $adherentNew,
                        null,
                        [AbstractNormalizer::ATTRIBUTES => ['user' => ['username', 'email', 'firstname', 'lastname', 'plainPassword'],
                            'groupe' => ['id' => 'uuid'],
                            'geoloc' => ['adresse',
                                'cpostal',
                                'ville', ], ]]
                    );
                    $jsondata = $serializer->serialize($data, 'json');

                    // Redirect to payment page
                    return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
                        'form' => $form,
                        'type' => Payment::TYPE_ADHESION,
                        'extra_data' => $jsondata,
                    ]);
                // HELLOASSO PAIEMENT
                } elseif ($form->has('saveHelloAsso') && $form->get('saveHelloAsso')->isClicked()) {
                    $adherentNew = $form->getData();
                    $usergroup = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
                    $adherentNew->getUser()->addPossiblegroup($usergroup);
                    $adherentNew->getUser()->addGroup($usergroup);
                    $adherentNew->getUser()->setAdherent($adherentNew);
                    $adherentNew->getUser()->setEnabled(true);

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

                    // Connect new user
                    $this->guardHandler->authenticateUserAndHandleSuccess(
                        $adherentNew->getUser(),
                        $request,
                        $this->authenticator,
                        'main'
                    );

                    return $this->redirect($this->router->generate('index') . '?showmlcadhesionmodal=1');
                }
            } else {
                $this->addFlash(
                    'error',
                    'Veuillez vérifier les informations du formulaire !'
                );
            }
        }

        return $this->render('@kohinos/adherent/adherer.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}
