<?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\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Form\Type\PickUserDynamicType;
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\Common\Collections\Collection;
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
{
    public function __construct(
        private UserRender $userRender,
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('users', PickUserDynamicType::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 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, $format = 'string'): 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, []),
                        $data['users'] instanceof Collection ? $data['users']->toArray() : $data['users']
                    )
                ),
                '%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): 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, $data['users'])
            ->setParameter($start, $this->rollingDateConverter->convert($data['start_date']))
            ->setParameter($end, $this->rollingDateConverter->convert($data['end_date']))
        ;
    }

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