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

use Chill\EventBundle\Entity\Participation;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * Class ParticipationRepository.
 */
class ParticipationRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Participation::class);
    }

    /**
     * Count number of participations per person.
     *
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function countByPerson($person_id): int
    {
        return $this->createQueryBuilder('p')
            ->select('COUNT (p.id)')
            ->where('p.id = :person_id')
            ->setParameter(':person_id', $person_id)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * Return paginated participations for a person and in reachables circles.
     */
    public function findByPersonInCircle($person_id, $reachablesCircles, $first, $max)
    {
        return $this->createQueryBuilder('p')
            ->join('p.event', 'e')
            ->where('p.person = :person_id')
            ->andWhere('e.circle IN (:reachable_circles)')
            ->orderBy('e.date', 'ASC')
            ->setParameters([
                ':person_id' => $person_id,
                ':reachable_circles' => $reachablesCircles,
            ])
            ->setFirstResult($first)
            ->setMaxResults($max)
            ->getQuery()
            ->getResult();
    }
}
