<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Controller;

use Chill\MainBundle\Action\User\UpdateProfile\UpdateProfileCommand;
use Chill\MainBundle\Action\User\UpdateProfile\UpdateProfileCommandHandler;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Form\UpdateProfileType;
use Chill\MainBundle\Notification\NotificationFlagManager;
use Chill\MainBundle\Security\ChillSecurity;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;

final readonly class UserUpdateProfileController
{
    public function __construct(
        private TranslatorInterface $translator,
        private ChillSecurity $security,
        private EntityManagerInterface $entityManager,
        private NotificationFlagManager $notificationFlagManager,
        private FormFactoryInterface $formFactory,
        private UrlGeneratorInterface $urlGenerator,
        private Environment $twig,
        private UpdateProfileCommandHandler $updateProfileCommandHandler,
    ) {}

    /**
     * User profile that allows editing of phonenumber and visualization of certain data.
     */
    #[Route(path: '/{_locale}/main/user/my-profile', name: 'chill_main_user_profile')]
    public function __invoke(Request $request, Session $session)
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException();
        }

        $user = $this->security->getUser();

        $command = UpdateProfileCommand::create($user, $this->notificationFlagManager);
        $editForm = $this->formFactory->create(UpdateProfileType::class, $command);

        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->updateProfileCommandHandler->updateProfile($user, $command);
            $this->entityManager->flush();
            $session->getFlashBag()->add('success', $this->translator->trans('user.profile.Profile successfully updated!'));

            return new RedirectResponse($this->urlGenerator->generate('chill_main_user_profile'));
        }

        return new Response($this->twig->render('@ChillMain/User/profile.html.twig', [
            'user' => $user,
            'form' => $editForm->createView(),
        ]));
    }
}
