<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use App\Entity\User;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\HttpFoundation\Session\Session;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="app_login")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        // if ($this->getUser()) {
        //     return $this->redirectToRoute('target_path');
        // }
    
        $session = new Session();    
        
        if($session->get('currentOtp') === null)
            return $this->redirectToRoute('app_otpInput');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
    }

    /**
     * @Route("/otpInput", name="app_otpInput")
     */
    public function otpInput(Request $request, MailerInterface $mailer, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $form = $this->createFormBuilder(null)       
            ->add('username',TextType::class, [       
                'attr' => ['class' => 'form-control'],
                'label' => false,
            ])    
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
           
           $data = $form->getData();                        
           $username =  $form->get('username')->getData();

            ////
            $entityManager = $this->getDoctrine()->getManager(); 
            $userObj = $entityManager
                            ->getRepository(User::class)
                            ->findOneBy(array('username' => $username));
           
            if($userObj === null)
            {
                $this->addFlash('warning', 'PIN could not be found.');

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

            $otp = random_int(100000, 999999);

            $hashedPassword = $passwordEncoder->encodePassword($userObj, $otp);
            $userObj->setPassword($hashedPassword);

            $entityManager->persist($userObj);
            $entityManager->flush();
            
            $email = (new Email())
                ->from('hr@cross-world.com')                
                ->to($userObj->getOfficeEmail())           
                ->bcc('malayaroy99@gmail.com')             
                //->replyTo('fabien@example.com')
                //->priority(Email::PRIORITY_HIGH)
                ->subject('Your Login OTP')
                ->text('Sending emails is fun again!')
                ->html('<p> Welcome to Cross World Leave Application System.  </p> <p> Your OTP is: '.$otp.'</p><p>**The Email is a system-generated email.</p>');
        
            try {
            
                $mailer->send($email);

                $session = new Session();
                $session->set('userNames', $username);
                $session->set('currentOtp', $otp);
                $session->set('userEmail', $userObj->getOfficeEmail());

                return $this->redirectToRoute('app_login');

            } catch (TransportExceptionInterface $e) {
                        
                return $this->redirectToRoute('app_login');

            }
          ////
           
        }

        return $this->render('security/otpInput.html.twig', [
            'otpInputForm' => $form->createView(),
        ]);
    }


    /**
     * @Route("/logout", name="app_logout")
     */
    public function logout()
    {
        throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
    }
}
