<?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\Export\Filter\AccompanyingCourseFilters;

use Chill\MainBundle\Entity\User\UserJobHistory;
use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\UserJobRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodInfo;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Filter course where a user with the given job is "working" on it.
 *
 * Makes use of AccompanyingPeriodInfo
 */
readonly class JobWorkingOnCourseFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'acp_filter_user_job_working_on_course';

    public function __construct(
        private UserJobRepositoryInterface $userJobRepository,
        private RollingDateConverterInterface $rollingDateConverter,
        private TranslatableStringHelperInterface $translatableStringHelper,
    ) {}

    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $p = self::PREFIX;

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.AccompanyingPeriodInfo::class." {$p}_info "
                    ."JOIN {$p}_info.user {$p}_user "
                    .'JOIN '.UserJobHistory::class." {$p}_history WITH {$p}_history.user = {$p}_user "
                    ."WHERE IDENTITY({$p}_info.accompanyingPeriod) = acp.id "
                    ."AND {$p}_history.job IN (:{$p}_jobs) "
                    // job_at based on _info.infoDate
                    ."AND {$p}_history.startDate <= {$p}_info.infoDate "
                    ."AND ({$p}_history.endDate IS NULL OR {$p}_history.endDate > {$p}_info.infoDate) "
                    ."AND {$p}_info.infoDate >= :{$p}_start and {$p}_info.infoDate < :{$p}_end"
                )
            )
            ->setParameter("{$p}_jobs", $data['jobs'])
            ->setParameter(
                "{$p}_start",
                $this->rollingDateConverter->convert($data['start_date']),
            )
            ->setParameter(
                "{$p}_end",
                $this->rollingDateConverter->convert($data['end_date'])
            )
        ;
    }

    public function applyOn(): string
    {
        return Declarations::ACP_TYPE;
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('jobs', EntityType::class, [
                'class' => UserJob::class,
                'choices' => $this->userJobRepository->findAllActive(),
                'choice_label' => fn (UserJob $userJob) => $this->translatableStringHelper->localize($userJob->getLabel()),
                'multiple' => true,
                'expanded' => true,
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_job_working.Job working after',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_job_working.Job working before',
            ])
            // ->add('job_at', PickRollingDateType::class, [
            //    'label' => 'bla',
            //    'help' => 'bli',
            //    'required' => false,
            // ])
        ;
    }

    public function getNormalizationVersion(): int
    {
        return 1;
    }

    public function normalizeFormData(array $formData): array
    {
        return ['jobs' => $this->normalizeDoctrineEntity($formData['jobs']), 'start_date' => $formData['start_date']->normalize(), 'end_date' => $formData['end_date']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['jobs' => $this->denormalizeDoctrineEntity($formData['jobs'], $this->userJobRepository), 'start_date' => RollingDate::fromNormalized($formData['start_date']), 'end_date' => RollingDate::fromNormalized($formData['end_date'])];
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'export.filter.course.by_job_working.Filtered by job working on course: only %jobs%, between %start_date% and %end_date%', [
                '%jobs%' => implode(
                    ', ',
                    array_map(
                        fn (UserJob $userJob) => $this->translatableStringHelper->localize($userJob->getLabel()),
                        $data['jobs'] instanceof Collection ? $data['jobs']->toArray() : $data['jobs']
                    )
                ),
                '%start_date%' => $this->rollingDateConverter->convert($data['start_date'])?->format('d-m-Y'),
                '%end_date%' => $this->rollingDateConverter->convert($data['end_date'])?->format('d-m-Y'),
            ],
        ];
    }

    public function getFormDefaultData(): array
    {
        return [
            'jobs' => [],
            'start_date' => new RollingDate(RollingDate::T_YEAR_CURRENT_START),
            'end_date' => new RollingDate(RollingDate::T_TODAY),
            // 'job_at' => null,
        ];
    }

    public function getTitle(): string
    {
        return 'export.filter.course.by_job_working.title';
    }
}
