<?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;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Form\Type\PickUserOrMeDynamicType;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Filter course where a user is "working" on it.
 *
 * Makes use of AccompanyingPeriodInfo
 */
final readonly class UserWorkingOnCourseFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        private UserRender $userRender,
        private RollingDateConverterInterface $rollingDateConverter,
        private UserRepositoryInterface $userRepository,
    ) {}

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('users', PickUserOrMeDynamicType::class, [
                'multiple' => true,
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_user_working.User working after',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_user_working.User working before',
            ])
        ;
    }

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

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'export.filter.course.by_user_working.Filtered by user working on course: only %users%, between %start_date% and %end_date%', [
                '%users%' => implode(
                    ', ',
                    array_map(
                        fn (User $u) => $this->userRender->renderString($u, []),
                        $this->userOrMe($data['users'], $context)
                    )
                ),
                '%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 addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $ai_alias = 'user_working_on_course_filter_acc_info';
        $ai_users = 'user_working_on_course_filter_users';
        $start = 'acp_use_work_on_start';
        $end = 'acp_use_work_on_end';

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.AccompanyingPeriod\AccompanyingPeriodInfo::class." {$ai_alias}  ".
                    "WHERE {$ai_alias}.user IN (:{$ai_users}) AND IDENTITY({$ai_alias}.accompanyingPeriod) = acp.id AND {$ai_alias}.infoDate >= :{$start} and {$ai_alias}.infoDate < :{$end}"
                )
            )
            ->setParameter($ai_users, $this->userOrMe($data['users'], $exportGenerationContext))
            ->setParameter($start, $this->rollingDateConverter->convert($data['start_date']))
            ->setParameter($end, $this->rollingDateConverter->convert($data['end_date']))
        ;
    }

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