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

use Chill\MainBundle\Export\AccompanyingCourseExportHelper;
use Chill\MainBundle\Export\ExportInterface;
use Chill\MainBundle\Export\FormatterInterface;
use Chill\MainBundle\Export\GroupedExportInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person\PersonCenterHistory;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormBuilderInterface;

class CountPersonOnAccompanyingPeriodWorkAssociatePersonOnWork implements ExportInterface, GroupedExportInterface
{
    private readonly bool $filterStatsByCenters;

    public function __construct(
        protected EntityManagerInterface $em,
        ParameterBagInterface $parameterBag,
    ) {
        $this->filterStatsByCenters = $parameterBag->get('chill_main')['acl']['filter_stats_by_center'];
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        // No form necessary?
    }

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

    public function normalizeFormData(array $formData): array
    {
        return [];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return [];
    }

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

    public function getAllowedFormattersTypes(): array
    {
        return [FormatterInterface::TYPE_TABULAR];
    }

    public function getDescription(): string
    {
        return 'export.export.count_person_on_acpw_associate_person_on_work.description';
    }

    public function getGroup(): string
    {
        return 'Exports of social work actions';
    }

    public function getLabels($key, array $values, $data)
    {
        if ('export_result' !== $key) {
            throw new \LogicException("the key {$key} is not used by this export");
        }

        $labels = array_combine($values, $values);
        $labels['_header'] = 'export.export.count_person_on_acpw_associate_person_on_work.header';

        return static fn ($value) => $labels[$value];
    }

    public function getQueryKeys($data): array
    {
        return ['export_result'];
    }

    public function getResult($query, $data, \Chill\MainBundle\Export\ExportGenerationContext $context): array
    {
        return $query->getQuery()->getResult(Query::HYDRATE_SCALAR);
    }

    public function getTitle(): string
    {
        return 'export.export.count_person_on_acpw_associate_person_on_work.title';
    }

    public function getType(): string
    {
        return Declarations::SOCIAL_WORK_ACTION_TYPE;
    }

    public function initiateQuery(array $requiredModifiers, array $acl, array $data, \Chill\MainBundle\Export\ExportGenerationContext $context): QueryBuilder
    {
        $centers = array_map(static fn ($el) => $el['center'], $acl);

        $qb = $this->em->createQueryBuilder();

        $qb
            ->from(AccompanyingPeriod\AccompanyingPeriodWork::class, 'acpw')
            ->join('acpw.accompanyingPeriod', 'acp')
            ->join('acpw.persons', 'person');

        if ($this->filterStatsByCenters) {
            $qb
                ->andWhere(
                    $qb->expr()->exists(
                        'SELECT 1 FROM '.PersonCenterHistory::class.' acl_count_person_history WHERE acl_count_person_history.person = person
                    AND acl_count_person_history.center IN (:authorized_centers)
                    '
                    )
                )
                ->setParameter('authorized_centers', $centers);
        }

        $qb->select('COUNT(DISTINCT person.id) as export_result');

        AccompanyingCourseExportHelper::addClosingMotiveExclusionClause($qb);

        return $qb;
    }

    public function requiredRole(): string
    {
        return AccompanyingPeriodVoter::STATS;
    }

    public function supportsModifiers(): array
    {
        return [
            Declarations::SOCIAL_WORK_ACTION_TYPE,
            Declarations::ACP_TYPE,
            Declarations::PERSON_TYPE,
        ];
    }
}
