<?php

namespace App\Controller;

use App\Core\Controller\Site\PageController;
use App\Core\Notification\MailNotifier;
use App\Form\ContactType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Core\Setting\SettingManager;

class ContactController extends PageController
{
    public function contact(MailNotifier $notifier, Request $request, SettingManager $settingManager): Response
    {
        $form = $this->createForm(ContactType::class);
        $showForm = true;

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);

            if ($form->isValid()) {
                $showForm = false;
                $data = $form->getData();

                $notifier
                    ->setFrom($settingManager->get('email_sender')->getValue())
                    ->addRecipient($settingManager->get('email_contact')->getValue())
                    ->setSubject('[Deblan] Nouveau message')
                    ->setReplyTo($data['email'])
                    ->notify('mail/contact.html.twig', [
                        'message' => $data,
                    ], 'text/plain')
                ;

                $this->addFlash(
                    'success',
                    'Votre message a bien été envoyé.'
                );
            } else {
                $this->addFlash('error', 'Le formulaire n\'est pas valide.');
            }
        }

        return $this->defaultRender($this->siteRequest->getPage()->getTemplate(), [
            'form' => $form->createView(),
            'showForm' => $showForm,
        ]);
    }
}
