<?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\PersonBundle\Controller;

use Chill\MainBundle\Entity\Location;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Repository\AccompanyingPeriodACLAwareRepositoryInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;

class AccompanyingPeriodRegulationListController
{
    public function __construct(private readonly AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository, private readonly \Twig\Environment $engine, private readonly FormFactoryInterface $formFactory, private readonly PaginatorFactory $paginatorFactory, private readonly Security $security, private readonly TranslatableStringHelperInterface $translatableStringHelper) {}

    #[Route(path: '/{_locale}/person/periods/undispatched', name: 'chill_person_course_list_regulation')]
    public function listRegul(Request $request): Response
    {
        if (!$this->security->isGranted('ROLE_USER') || !$this->security->getUser() instanceof User) {
            throw new AccessDeniedHttpException();
        }

        $form = $this->buildFilterForm();

        $form->handleRequest($request);

        $total = $this->accompanyingPeriodACLAwareRepository->countByUnDispatched(
            $form['jobs']->getData(),
            $form['services']->getData(),
            $form['locations']->getData(),
        );
        $paginator = $this->paginatorFactory->create($total);
        $periods = $this->accompanyingPeriodACLAwareRepository
            ->findByUnDispatched(
                $form['jobs']->getData(),
                $form['services']->getData(),
                $form['locations']->getData(),
                ['openingDate' => 'DESC', 'id' => 'DESC'],
                $paginator->getItemsPerPage(),
                $paginator->getCurrentPageFirstItemNumber()
            );

        return new Response(
            $this->engine->render('@ChillPerson/AccompanyingCourse/dispatch_list.html.twig', [
                'paginator' => $paginator,
                'periods' => $periods,
                'form' => $form->createView(),
            ])
        );
    }

    private function buildFilterForm(): FormInterface
    {
        $data = [
            'services' => [],
            'jobs' => [],
            'locations' => [],
        ];

        $builder = $this->formFactory->createBuilder(FormType::class, $data, [
            'method' => 'get', 'csrf_protection' => false, ]);

        $builder
            ->add('services', EntityType::class, [
                'class' => Scope::class,
                'query_builder' => static fn (EntityRepository $er) => $er->createQueryBuilder('s'),
                'choice_label' => fn (Scope $s) => $this->translatableStringHelper->localize($s->getName()),
                'multiple' => true,
                'label' => 'Service',
                'required' => false,
            ])
            ->add('jobs', EntityType::class, [
                'class' => UserJob::class,
                'query_builder' => static function (EntityRepository $er) {
                    $qb = $er->createQueryBuilder('j');
                    $qb->andWhere($qb->expr()->eq('j.active', "'TRUE'"));

                    return $qb;
                },
                'choice_label' => fn (UserJob $j) => $this->translatableStringHelper->localize($j->getLabel()),
                'multiple' => true,
                'label' => 'Métier',
                'required' => false,
            ])
            ->add('locations', EntityType::class, [
                'class' => Location::class,
                'query_builder' => static function (EntityRepository $er) {
                    $qb = $er->createQueryBuilder('l');
                    $qb
                        ->join('l.locationType', 't')
                        ->where(
                            $qb->expr()->andX(
                                $qb->expr()->eq('t.availableForUsers', "'TRUE'"),
                                $qb->expr()->eq('t.active', "'TRUE'"),
                                $qb->expr()->eq('l.active', "'TRUE'"),
                                $qb->expr()->eq('l.availableForUsers', "'TRUE'")
                            )
                        );

                    return $qb;
                },
                'choice_label' => static fn (Location $l) => $l->getName(),
                'multiple' => true,
                'group_by' => function (Location $l) {
                    if (null === $type = $l->getLocationType()) {
                        return null;
                    }

                    return $this->translatableStringHelper->localize($type->getTitle());
                },
                'label' => 'Localisation administrative',
                'required' => false,
            ]);

        return $builder->getForm();
    }
}
