<?php

namespace AutoAdmin\Bundle\Admin\Controller\Admin;


use AutoAdmin\Bundle\Admin\Form\Type\ProfileType;
use AutoAdmin\Bundle\Admin\Model\AdministratorInterface;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;

class AdministratorController extends AbstractAdminController
{
    #[Route('/profile', name: 'aa_admin_administrator_profile')]
    public function profile(Request $request, PasswordHasherFactoryInterface $hasherFactory, TranslatorInterface $translator): Response
    {
        $currentUser = $this->getUser();
        $form = $this->createForm(ProfileType::class, $currentUser);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            /** @var AdministratorInterface $user */
            $user = $form->getData();
            $hasher = $hasherFactory->getPasswordHasher($user);

            $oldPassword = $form->get('oldPassword')->getData();
            if ($hasher->verify($user->getPassword(), $oldPassword)) {
                $user->setPassword($hasher->hash($user->getPlainPassword()));
                /** @var ObjectManager $em */
                $em = $this->entityHelper->getManager();
                $em->persist($user);
                $em->flush();
                $this->addFlash('success', 'Successfully updated account information.');
            } else {
                $this->addFlash('error', 'Invalid password.');
            }
        }

        return $this->render(
            '@AutoAdminAdmin/administrator/profile.html.twig',
            [
                'mainTitle' => $translator->trans('admin_profile.page_title', [], 'aa_admin'),
                'form' => $form->createView(),
            ]
        );
    }
}
