<?php

namespace AutoAdmin\Bundle\Admin\Controller\Resetting;

use AutoAdmin\Bundle\Admin\Form\ResettingType;
use AutoAdmin\Bundle\Admin\Model\AdministratorInterface;
use AutoAdmin\Bundle\Admin\Service\AdministratorResettingService;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\OptimisticLockException;
use Exception;
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\Attribute\Route;

class ResettingController extends AbstractController
{
    #[Route('/password-reset', name: 'aa_admin_password_reset')]
    public function request(Request $request, AdministratorResettingService $service): Response
    {
        $options = [];
        if ($request->getMethod() === Request::METHOD_POST) {
            $submittedToken = $request->request->get('token');
            if ($this->isCsrfTokenValid('password-reset', $submittedToken)) {
                try {
                    $service->request($request);
                } catch (Exception $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 OptimisticLockException
     * @throws ORMException
     */
    #[Route('/password-reset/{passwordRequestToken}', name: 'aa_admin_password_reset_change')]
    public function resetPassword(
        AdministratorInterface $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);
    }
}
