<?php

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\Payment;
use App\Form\Type\AdhererFormType;
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\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class AdhesionController extends AbstractController
{
    /**
     * @Route("/adherer", name="adherer")
     */
    public function adhererAction(Request $request)
    {
        $adherent = new Adherent();

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

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $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\FluxController::preparePaymentAction', [
                    'form' => $form,
                    'type' => Payment::TYPE_ADHESION,
                    'extra_data' => $jsondata,
                ]);
            } else {
                $this->addFlash(
                    'error',
                    'Problème avec l\'adhésion, veuillez vérifier les informations du formulaire !'
                );
            }
        }

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