<?php

namespace App\Controller\Frontend;


use App\Controller\AbstractController;
use App\Form\SubscribeNewsletterForm;
use Symfony\Component\HttpFoundation\Request;
use Welp\MailchimpBundle\Exception\MailchimpException;
use Welp\MailchimpBundle\Event\SubscriberEvent;
use Welp\MailchimpBundle\Subscriber\Subscriber;

class NewsletterController extends AbstractController
{
    public function subscribeNewsletter(Request $request)
    {
        $form = $this->createForm(SubscribeNewsletterForm::class) ;
        $form->handleRequest($request) ;

        if($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData() ;
            $email = $data['email'] ;

            try {
                // api mailchimp
                $subscriber = new Subscriber($email);
                $this->container->get('event_dispatcher')->dispatch(
                    SubscriberEvent::EVENT_SUBSCRIBE,
                    new SubscriberEvent('91a235f34c', $subscriber)
                );
                $this->addFlash('success', 'Votre inscription à notre newsletter a bien été prise en compte.');
            }
            catch(MailchimpException $exception) {
                $this->addFlash('error', $exception->getMessage());
            }
        }

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