<?php

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\Cotisation;
use App\Entity\Faq;
use App\Entity\Geoloc;
use App\Entity\Page;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\MoyenEnum;
use App\Form\Type\AdhererFormType;
use App\Form\Type\ContactFormType;
use App\Form\Type\TransactionAdherentPrestataireFormType;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Geocoder\Provider\Nominatim\Nominatim;
use Geocoder\Query\GeocodeQuery;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
use Swagger\Annotations as SWG;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class IndexController extends AbstractController
{
    private $em;
    private $um;

    public function __construct(EntityManagerInterface $em, UserManagerInterface $um)
    {
        $this->em = $em;
        $this->um = $um;
    }

    /**
     * @Route("/", name="index")
     */
    // public function index(TranslatorInterface $translator)
    public function index(Request $request)
    {
        // Exemple pour la traduction :
        // $translated = $translator->trans('Symfony is great');
        // $translator->transChoice(
        //     'Hurry up %name%! There is one apple left.|There are %count% apples left.',
        //     10,
        //     // no need to include %count% here; Symfony does that for you
        //     array('%name%' => $user->getName())
        // );

        return $this->render('index.html.twig', [
            'news' => array(),
        ]);
    }

    /**
     * @Route("/adherer", name="adherer")
     */
    public function adhererAction(Request $request)
    {
        // @TODO : formulaire d'adhésion sans cotisation ? à valider après ?

        $adherent = new Adherent();
        $user = $this->um->createUser();
        $groupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
        $user->setEnabled(true);
        $user->addGroup($groupe);
        $user->addRole('ROLE_ADHERENT');
        $adherent->setEcompte('0');
        $user->setAdherent($adherent);
        $adherent->setUser($user);
        if (count($adherent->getUser()->getCotisations()) <= 0) {
            $cotisation = new Cotisation();
            $cotisation->setMontant($this->getParameter('cotisation_montant'));
            $cotisation->setOperateur($adherent->getUser());
            $cotisation->setExpediteur($adherent);
            $cotisation->setMoyen(MoyenEnum::MOYEN_AUTRE);
            $cotisation->setDebut(new \DateTime());
            $cotisation->setFin(new \DateTime('+ 1 year'));
            $adherent->getUser()->addCotisation($cotisation);
        }
        if ($adherent->getGeoloc() == null) {
            $adherent->setGeoloc(new Geoloc());
        }
        $form = $this->createForm(AdhererFormType::class, $adherent);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $this->em->persist($adherent);
                $this->em->persist($user);
                $this->em->flush();
                $this->addFlash(
                    'success',
                    'Adhésion bien pris en compte, vous recevrez un email très bientôt !'
                );
                return $this->redirectToRoute('index');
            } else {
                $this->addFlash(
                    'error',
                    'Problème avec l\'adhésion !'
                );
            }
        }

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

    /**
     * @Route("/group/choice/{id}", name="group_choice")
     */
    public function groupChoiceAction(Usergroup $group, Request $request)
    {
        $request->getSession()->remove('_choixGroup');
        // On enregistre le rôle choisit en session
        $request->getSession()->set('_groupId', $group);

        // @TODO : On redirige sur l'index (ou en fonction du rôle?)
        return $this->redirectToRoute('index');
    }

    /**
     * @Route("/page/{slug}", name="show_page")
     */
    public function pageAction(Page $page)
    {
        $template = 'page.html.twig';
        if (!empty($page->getTemplate()) && $this->get('templating')->exists($page->getTemplate())) {
            $template = $page->getTemplate();
        }
        return $this->render($template, array(
            'page' => $page
        ));
    }

    /**
     * @Route("/faq", name="faq")
     */
    public function faqAction()
    {
        return $this->render('faq/liste.html.twig', array(
            'faqs' => $this->em->getRepository(Faq::class)->findBy(array('enabled' => true), array('createdAt' => 'DESC'))
        ));
    }


    /**
     * @Route("/faq/{slug}", name="show_faq")
     */
    public function showFaqAction(Faq $faq)
    {
        return $this->render('faq/show.html.twig', array(
            'faq' => $faq
        ));
    }

    /**
     * @Route("/contact", name="contact")
     */
    public function contactAction(Request $request)
    {
        $form = $this->createForm(ContactFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $nom = $form['nom']->getData();
            $emailFrom = $form['email']->getData();
            $message = $form['message']->getData();
            // TODO : send mail
            $this->addFlash(
                'success',
                'Merci ! Le message a bien été envoyé !'
            );
            $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->render('contact.html.twig', array(
            'form' => $form->createView()
        ));
    }
}
