<?php

namespace Lc\SovBundle\Controller\User;

use Doctrine\ORM\EntityManagerInterface;
use Lc\SovBundle\Controller\ControllerTrait;
use Lc\SovBundle\Doctrine\EntityManager;
use Lc\SovBundle\Form\User\ChangePasswordFormType;
use Lc\SovBundle\Form\User\ProfileFormType;
use Lc\SovBundle\Model\User\UserModel;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Component\Routing\Annotation\Route;

class AccountAdminController extends AbstractController
{
    use ControllerTrait;

    protected EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @Route("/admin/account/profile", name="sov_admin_account_profile")
     */
    public function profile(Request $request): Response
    {
        $user = $this->getUser();
        $form = $this->createForm(ProfileFormType::class, $user);

        $form->handleRequest($request);


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

            $this->entityManager->update($user);
            $this->entityManager->flush();

            $this->addFlashTranslator('success', 'updated');
        }

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

    /**
     * @Route("/admin/account/password", name="sov_admin_account_password")
     */
    public function changePassword(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $user = $this->getUser();
        $form = $this->createForm(ChangePasswordFormType::class, $user);

        $form->handleRequest($request);

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

            $plainPassword = $form->get('plain_password')->getData();

            $user->setPassword($passwordEncoder->encodePassword($user, $plainPassword));

            $this->entityManager->update($user);
            $this->entityManager->flush();

            $this->addFlashTranslator('success', 'passwordUpdated');
        }

        return $this->render(
                '@LcSov/admin/user/edit_password.html.twig',
                [
                        'entity_class' => UserModel::class,
                        'form' => $form->createView()
                ]
        );
    }

}
