<?php

namespace App\Controller;

use App\Entity\MetaData;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Utils\Utils;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;

class RegistrationController extends AbstractController
{
    #[Route('/register', name: 'app_register')]
    public function register(
        Request $request,
        UserPasswordHasherInterface $userPasswordHasher,
        EntityManagerInterface $entityManager,
        MailerInterface $mailer
    ): Response {
        $user = new User();

        $form = $this->createForm(RegistrationFormType::class, $user);
        $form->handleRequest($request);
        $role = ['ROLE_USER'];

        if ($entityManager->getRepository(User::class)->getUserCount() == 0) {
            $role = ['ROLE_ADMIN'];
        }

        if ($form->isSubmitted() && $form->isValid()) {
            // encode the plain password
            $user->setPassword(
                $userPasswordHasher->hashPassword(
                    $user,
                    $form->get('plainPassword')->getData()
                )
            );
            $user->setRoles($role);
            $user->setMetaData([
                'saveInterval' => 30,
                'saveReferences' => true,
                'noteTextSize' => 14,
                'trackSaveSize' => false,
                'saveTimeout' => 10,
                'saveFailureCount' => 3,
            ]);

            $entityManager->persist($user);
            $entityManager->flush();

            $this->sendEmail($user, $mailer);

            return $this->redirectToRoute('app_home');
        }
        else {
            //dd($form);
        }

        return $this->render('registration/register.html.twig', [
            'registrationForm' => $form,
        ]);
    }

    private function sendEmail(User $user, MailerInterface $mailer): void
    {
        $util = new Utils();
        $util->sendEmail(
            $mailer,
            new Address('ryan@rkprather.com'),
            new Address('ryan@rkprather.com'),
            'New Account',
            $this->renderView('emails/registration.html.twig', [
                'user' => $user
            ])
        );
    }
}
