<?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\Entity\User;
use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Form\Type\PickUserDynamicType;
use Chill\MainBundle\Pagination\PaginatorFactoryInterface;
use Chill\MainBundle\Repository\UserGroupRepositoryInterface;
use Chill\MainBundle\Routing\ChillUrlGeneratorInterface;
use Chill\MainBundle\Security\Authorization\UserGroupVoter;
use Chill\MainBundle\Templating\Entity\ChillEntityRenderManagerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
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\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\TranslatableMessage;
use Twig\Environment;

/**
 * Controller to see and manage user groups.
 */
final readonly class UserGroupController
{
    public function __construct(
        private UserGroupRepositoryInterface $userGroupRepository,
        private Security $security,
        private PaginatorFactoryInterface $paginatorFactory,
        private Environment $twig,
        private FormFactoryInterface $formFactory,
        private ChillUrlGeneratorInterface $chillUrlGenerator,
        private EntityManagerInterface $objectManager,
        private ChillEntityRenderManagerInterface $chillEntityRenderManager,
    ) {}

    #[Route('/{_locale}/main/user-groups/my', name: 'chill_main_user_groups_my')]
    public function myUserGroups(): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException();
        }

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

        if (!$user instanceof User) {
            throw new AccessDeniedHttpException();
        }

        $nb = $this->userGroupRepository->countByUser($user);
        $paginator = $this->paginatorFactory->create($nb);

        $groups = $this->userGroupRepository->findByUser($user, true, $paginator->getItemsPerPage(), $paginator->getCurrentPageFirstItemNumber());
        $forms = new \SplObjectStorage();

        foreach ($groups as $group) {
            $forms->attach($group, $this->createFormAppendUserForGroup($group)?->createView());
        }

        return new Response($this->twig->render('@ChillMain/UserGroup/my_user_groups.html.twig', [
            'groups' => $groups,
            'paginator' => $paginator,
            'forms' => $forms,
        ]));
    }

    #[Route('/{_locale}/main/user-groups/{id}/append', name: 'chill_main_user_groups_append_users')]
    public function appendUsersToGroup(UserGroup $userGroup, Request $request, Session $session): Response
    {
        if (!$this->security->isGranted(UserGroupVoter::APPEND_TO_GROUP, $userGroup)) {
            throw new AccessDeniedHttpException();
        }

        $form = $this->createFormAppendUserForGroup($userGroup);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            foreach ($form['users']->getData() as $user) {
                $userGroup->addUser($user);

                $session->getFlashBag()->add(
                    'success',
                    new TranslatableMessage(
                        'user_group.user_added',
                        [
                            'user_group' => $this->chillEntityRenderManager->renderString($userGroup, []),
                            'user' => $this->chillEntityRenderManager->renderString($user, []),
                        ]
                    )
                );
            }

            $this->objectManager->flush();

            return new RedirectResponse(
                $this->chillUrlGenerator->returnPathOr('chill_main_user_groups_my')
            );
        }
        if ($form->isSubmitted()) {
            $errors = [];
            foreach ($form->getErrors() as $error) {
                $errors[] = $error->getMessage();
            }

            return new Response(implode(', ', $errors));
        }

        return new RedirectResponse(
            $this->chillUrlGenerator->returnPathOr('chill_main_user_groups_my')
        );
    }

    /**
     * @ParamConverter("user", class=User::class, options={"id" = "userId"})
     */
    #[Route('/{_locale}/main/user-group/{id}/user/{userId}/remove', name: 'chill_main_user_groups_remove_user')]
    public function removeUserToGroup(UserGroup $userGroup, User $user, Session $session): Response
    {
        if (!$this->security->isGranted(UserGroupVoter::APPEND_TO_GROUP, $userGroup)) {
            throw new AccessDeniedHttpException();
        }

        $userGroup->removeUser($user);
        $this->objectManager->flush();

        $session->getFlashBag()->add(
            'success',
            new TranslatableMessage(
                'user_group.user_removed',
                [
                    'user_group' => $this->chillEntityRenderManager->renderString($userGroup, []),
                    'user' => $this->chillEntityRenderManager->renderString($user, []),
                ]
            )
        );

        return new RedirectResponse(
            $this->chillUrlGenerator->returnPathOr('chill_main_user_groups_my')
        );
    }

    private function createFormAppendUserForGroup(UserGroup $group): ?FormInterface
    {
        if (!$this->security->isGranted(UserGroupVoter::APPEND_TO_GROUP, $group)) {
            return null;
        }

        $builder = $this->formFactory->createBuilder(FormType::class, ['users' => []], [
            'action' => $this->chillUrlGenerator->generateWithReturnPath('chill_main_user_groups_append_users', ['id' => $group->getId()]),
        ]);
        $builder->add('users', PickUserDynamicType::class, [
            'submit_on_adding_new_entity' => true,
            'label' => 'user_group.append_users',
            'mapped' => false,
            'multiple' => true,
        ]);

        return $builder->getForm();
    }
}
