<?php

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\Payment;
use App\Form\Type\AdhererFormType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

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
                $serializer = $this->container->get('serializer');
                $data = $serializer->normalize(
                    $adherentNew,
                    null,
                    [AbstractNormalizer::ATTRIBUTES => ['user' => ['username', 'email', 'firstname', 'lastname', 'plainPassword'],
                                                      'groupe' => ['id'],
                    '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(),
        ]);
    }
}
