<?php

namespace App\Controller;

use App\Form\MeType;
use App\Form\MePasswordType;
use Psr\Log\LoggerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

#[Route('/me', name: 'me_')]
class MeController extends AbstractController
{
    private Security $security;
    private LoggerInterface $logger;

    public function __construct(Security $security, LoggerInterface $logger)
    {
        $this->security = $security;
        $this->logger = $logger;
    }

    #[Route('/', name: 'index')]
    public function index(PaginatorInterface $paginator, Request $request): Response
    {
        /**
         * @var User $user
         */
        $user = $this->security->getUser();
        $form = $this->createForm(MeType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            try {
                $entityManager->flush();
            } catch (\Throwable $th) {
                if ($_ENV['APP_ENV'] === 'dev') {
                    throw $th; //DEBUG
                } else {
                    $this->logger->error($th);
                }

                $this->addFlash('danger', 'alert_error_editing_profile');
                return $this->redirectToRoute($request->getRequestUri());
            }

            $this->addFlash('success', 'alert_success_editing_profile');
            $request->getSession()->set('_locale', $user->getLocale());
            return $this->redirectToRoute('me_index');
        }


        return $this->render('me/index.html.twig', [
            'controller_name' => 'MeController',
            'form' => $form->createView(),
            'pagination' => $paginator->paginate(
                $user->getDocuments(),
                $request->query->getInt('page', 1)
            )
        ]);
    }

    #[Route('/password', name: 'password')]
    public function password(Request $request, UserPasswordHasherInterface $passwordEncoder): Response
    {
        /**
         * @var User $user
         */
        $user = $this->security->getUser();
        $form = $this->createForm(MePasswordType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // encode the plain password
            $user->setPassword(
                $passwordEncoder->hashPassword(
                    $user,
                    $form->get('plainPassword')->getData()
                )
            );

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            try {
                $entityManager->flush();
            } catch (\Throwable $th) {
                if ($_ENV['APP_ENV'] === 'dev') {
                    throw $th; //DEBUG
                } else {
                    $this->logger->error($th);
                }

                $this->addFlash('danger', 'alert_error_editing_password');
                return $this->redirectToRoute($request->getRequestUri());
            }

            $this->addFlash('success', 'alert_success_editing_password');
            $request->getSession()->set('_locale', $user->getLocale());
            return $this->redirectToRoute('me_index');
        }


        return $this->render('me/password.html.twig', [
            'controller_name' => 'MeController',
            'form' => $form->createView(),
        ]);
    }
}
