<?php

namespace AutoAdmin\Bundle\Admin\Controller\Resetting;

use AutoAdmin\Bundle\Admin\Entity\Administrator;
use AutoAdmin\Bundle\Admin\Form\ResettingType;
use AutoAdmin\Bundle\Admin\Service\AdministratorResettingService;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\OptimisticLockException;
use Exception as ExceptionAlias;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ResettingController extends AbstractController
{
    /**
     * @throws ExceptionAlias
     */
    #[Route('/password-reset', name: 'aa_admin_password_reset')]
    public function request(Request $request, AdministratorResettingService $service): Response
    {
        $options = [];
        if ($request->getMethod() === "POST") {
            $submittedToken = $request->request->get('token');
            if ($this->isCsrfTokenValid('password-reset', $submittedToken)) {
                try {
                    $service->request($request);
                } catch (ExceptionAlias $e) {
                    $options['error'] = $e->getMessage();
                }
            } else {
                $options['error'] = 'Une erreur est survenue, veuillez réessayer';
            }
        }

        return $this->render('@AutoAdminAdmin/resetting/request.html.twig', $options);
    }

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    #[Route('/password-reset/{passwordRequestToken}', name: 'aa_admin_password_reset_change')]
    public function resetPassword(Administrator $admin, AdministratorResettingService $service, Request $request): RedirectResponse|Response
    {
        $form = $this->createForm(ResettingType::class, $admin);
        $form->handleRequest($request);

        $templateOptions = [
            'form' => $form->createView(),
            'user' => $admin
        ];

        if ($form->isSubmitted() && $form->isValid()) {
            $validation = $service->validate($admin);

            if ($validation === true) {
                return $this->redirectToRoute("aa_admin_login");
            }

            $templateOptions['error'] = $validation;
        }

        return $this->render('@AutoAdminAdmin/resetting/resetPassword.html.twig', $templateOptions);
    }
}
