<?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\Export\ExportDataNormalizerTrait;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Form\Type\PickSocialIssueType;
use Chill\PersonBundle\Repository\SocialWork\SocialIssueRepository;
use Chill\PersonBundle\Templating\Entity\SocialIssueRender;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class SocialIssueFilter implements FilterInterface
{
    use ExportDataNormalizerTrait;

    public function __construct(
        private readonly SocialIssueRender $socialIssueRender,
        private readonly SocialIssueRepository $socialIssueRepository,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        if (!\in_array('acpsocialissue', $qb->getAllAliases(), true)) {
            $qb->join('acp.socialIssues', 'acpsocialissue');
        }

        $clause = $qb->expr()->in('acpsocialissue.id', ':socialissues');

        $qb->andWhere($clause)
            ->setParameter(
                'socialissues',
                SocialIssue::getDescendantsWithThisForIssues(
                    $data['accepted_socialissues'] instanceof Collection ? $data['accepted_socialissues']->toArray() : $data['accepted_socialissues']
                )
            );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_socialissues', PickSocialIssueType::class, [
            'multiple' => true,
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_socialissues' => $this->normalizeDoctrineEntity($formData['accepted_socialissues'])];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_socialissues' => $this->denormalizeDoctrineEntity($formData['accepted_socialissues'], $this->socialIssueRepository)];
    }

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $issues = [];

        $socialissues = $data['accepted_socialissues'];

        foreach ($socialissues as $issue) {
            $issues[] = $this->socialIssueRender->renderString($issue, [
                'show_and_children' => true,
            ]);
        }

        return [
            'Filtered by socialissues: only %socialissues%', [
                '%socialissues%' => implode(', ', $issues),
            ], ];
    }

    public function getTitle(): string
    {
        return 'Filter by social issue';
    }
}
