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

use Chill\EventBundle\Export\Declarations;
use Chill\EventBundle\Repository\ParticipationRepository;
use Chill\EventBundle\Security\ParticipationVoter;
use Chill\MainBundle\Export\ExportInterface;
use Chill\MainBundle\Export\FormatterInterface;
use Chill\MainBundle\Export\GroupedExportInterface;
use Chill\PersonBundle\Entity\Person\PersonCenterHistory;
use Doctrine\ORM\Query;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\PersonBundle\Export\Declarations as PersonDeclarations;

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

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

    public function buildForm(FormBuilderInterface $builder) {}

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

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

    public function getDescription()
    {
        return 'Count participants to an event by various parameters.';
    }

    public function getGroup(): string
    {
        return 'Exports of events';
    }

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

        return static fn ($value) => '_header' === $value ? 'Count event participants' : $value;
    }

    public function getQueryKeys($data)
    {
        return ['export_count_event_participants'];
    }

    public function getResult($query, $data)
    {
        return $query->getQuery()->getResult(Query::HYDRATE_SCALAR);
    }

    public function getTitle()
    {
        return 'Count event participants';
    }

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

    public function initiateQuery(array $requiredModifiers, array $acl, array $data = [])
    {
        $centers = array_map(static fn ($el) => $el['center'], $acl);

        $qb = $this->participationRepository
            ->createQueryBuilder('event_part')
            ->join('event_part.person', 'person');

        $qb->select('COUNT(event_part.id) as export_count_event_participants');

        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);
        }

        return $qb;
    }

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

    public function supportsModifiers()
    {
        return [
            Declarations::EVENT_PARTICIPANTS,
            PersonDeclarations::PERSON_TYPE,
        ];
    }
}
