<?php

namespace App\Controller\Frontend;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use Doctrine\ORM\EntityManagerInterface;

use App\Form\Frontend\UserAdresseType;
use App\Form\Frontend\UserInfoCnxType;
use App\Form\Frontend\UserInfoPersoType;
use App\Form\Frontend\UserUpdatePasswordType;


use App\Entity\User;

/**
 * @Security("is_granted('ROLE_USER')")
 */
class UserController extends AbstractController
{

    /**
     * @var EntityManagerInterface $em
     */
    private $em;


    /**
     * @param EntityManagerInterface $em
     * @return $this
     */
    public function __construct(
        EntityManagerInterface $em
    ){
        $this->em = $em;
    }

    #[Route('/frontend/user/edit', name: 'frontend_user_profile')]
    public function profile(Request $request): Response
    {

        $user = $this->getUser(); 

        $formInfoPerso = $this->createForm(UserInfoPersoType::class, $user);
        $formInfoPerso->handleRequest($request);

        $formInfoAdress = $this->createForm(UserAdresseType::class, $user);
        $formInfoAdress->handleRequest($request);

        $formInfoCnx = $this->createForm(UserInfoCnxType::class, $user);
        $formInfoCnx->handleRequest($request);

        if( ($formInfoPerso->isSubmitted() && $formInfoPerso->isValid()) or
            ($formInfoAdress->isSubmitted() && $formInfoAdress->isValid()) or
            ($formInfoCnx->isSubmitted() && $formInfoCnx->isValid())
        )
        {
            $this->em->persist($user);
            $this->em->flush();
        }

        return $this->render('frontend/user/edit.html.twig', [

            'user' => $user,

            'formInfoPerso' => $formInfoPerso->createView(),
            'errorsInfoPerso' => $formInfoPerso->getErrors(),

            'formInfoAdress' => $formInfoAdress->createView(),
            'errorsInfoAdress' => $formInfoAdress->getErrors(),

            'formInfoCnx' => $formInfoCnx->createView(),
            'errorsInfoCnx' => $formInfoCnx->getErrors(),

        ]);
    }


    #[Route('/frontend/user/update_password', name: 'frontend_user_update_password')]
    public function update_password(Request $request, UserPasswordHasherInterface $passwordHasher): Response
    {
        $user = $this->getUser(); 

        $form = $this->createForm(UserUpdatePasswordType::class);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid() ) {

            $plaintextPassword = $form->get('new_password')->getData();
            
            $hashedPassword = $passwordHasher->hashPassword($user, $plaintextPassword);

            $user->setPassword($hashedPassword);
            $user->setLastChangePassword(new \DateTime());
            
            $this->em->persist($user);
            $this->em->flush();
            $this->addFlash('success', '');

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

        return $this->render('frontend/user/update_password.html.twig', [
            "form"=>$form,
            'errors' => $form->getErrors(),
        ]);
    }

    #[Route('/frontend/user/delete', name: 'frontend_user_delete')]
    public function delete(): Response
    {
        $user = $this->getUser();
        $user->setIsDeleted(true);
        $this->em->persist($user);
        $this->em->flush();
        
        return $this->redirectToRoute('frontend_security_logout'); 
    }


    #[Route('/frontend/user/parrainage', name: 'frontend_user_parrainage')]
    public function parrainage(Request $request): Response
    {
        $user = $this->getUser();
        
        $form = $this->createFormBuilder()
                    ->add('email', \Symfony\Component\Form\Extension\Core\Type\EmailType::class)
                    ->add('save', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, ['attr'=>['class'=>'envoyer']])
                    ->getForm();

        $hash = openssl_encrypt(json_encode($user->getId()), "AES-128-ECB", $_ENV['APP_SECRET']);
        $urlParinage = $request->getScheme().'://'.$request->getHttpHost().$request->getBasePath().'/frontend/user_parrai?use='.$hash;
        
        return $this->render('frontend/user/parrainage.html.twig', [
            "form"=>$form,
            "parrainages"=>$user->getParrainages(),
            "urlParinage"=>$urlParinage
        ]);
    }

    #[Route('/frontend/user_parrai', name: 'frontend_user_parrai')]
    public function user_parrai(Request $request, Session $session): Response
    {
        $hash = $request->get('use');
        
        $plain = openssl_decrypt($hash, "AES-128-ECB", $_ENV['APP_SECRET']);
        if(is_numeric($plain)){
            $session->set("user_parrai", $plain);
        }
        

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