<?php

namespace App\Controller;

use App\Document\User;
use App\Form\Type\UserType;
use App\Form\Type\LoginType;
use App\Form\Type\DeleteType;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Redirect;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Routing\Annotation\Route;

#[Route(path: '/users', name: 'users_')]
class UserController extends AbstractController
{
    #[Route('/create', name: 'create')]
    public function createAction(DocumentManager $dm, Request $request, UserPasswordHasherInterface $passwordHasher, Security $security)
    {
        $user = new User();
        $form = $this->createForm(UserType::class, $user);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();

            if ($dm->getRepository(User::class)->findOneBy(['email'=> $user->getEmail()])) {
                if ($this->getUser() !== null)
                    throw $this->createAccessDeniedException('Účet patří jinému uživateli!');
                return $this->redirectToRoute('users_login');
            }

            $hashedPassword = $passwordHasher->hashPassword($user, $user->getPassword());
            $user->setPassword($hashedPassword);

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

            $security->login($user);

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

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

    #[Route('/login', name: 'login')]
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        return $this->render('user/login.html.twig', [
            'last_email' => $authenticationUtils->getLastUsername(),
            'error' => $authenticationUtils->getLastAuthenticationError(),
        ]);
    }

    #[Route('/logout', name: 'logout')]
    public function logout(Security $security): Response
    {
        $response = $security->logout();
        return $response;
    }

    #[Route('/{id}/edit', name: 'edit')]
    public function editAction(DocumentManager $dm, Request $request, UserPasswordHasherInterface $passwordHasher, User $user)
    {
        if ($user !== $this->getUser()) {
            if ($this->getUser() !== null)
                throw $this->createAccessDeniedException('Účet patří jinému uživateli!');
            return $this->redirectToRoute('users_login');
        }

        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();

            $hashedPassword = $passwordHasher->hashPassword($user, $user->getPassword());
            $user->setPassword($hashedPassword);

            $dm->persist($user);
            $dm->flush();
        }

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

    #[Route('/{id}/remove', name: 'remove')]
    public function removeAction(DocumentManager $dm, Request $request, User $user) : Response
    {
        if ($user !== $this->getUser())
            throw $this->createAccessDeniedException('Účet patří jinému uživateli!');

        $form = $this->createForm(DeleteType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->getCharts()->clear();
            $dm->remove($user);
            $dm->flush();

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

        return $this->render('user/remove.html.twig', [
            'form' =>$form->createView(),
            'entity' => $user
        ]);
    }
}
