<?php

namespace App\Entity\EntityTrait;

use App\Entity\Geoloc;
use App\Entity\Groupe;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

trait PersonRepositoryTrait
{
    /**
     * Count adherent/prestataire by 'year', 'month', 'day'
     * @param  string      $groupBy  'year', 'month', 'day'
     * @param  Groupe|null $groupe   Groupe local
     * @return ArrayCollection       ArrayCollection[Adherent|Prestataire]
     */
    public function findCountBy(string $groupBy = 'month', ?Groupe $groupe = null)
    {
        try {
            $qb = $this->createQueryBuilder('p');
            $qb = $this->addDefaultFilter($qb);
            $qb->addSelect('COUNT(p.id) AS total');
            if ($groupBy == 'month') {
                $qb
                    ->addSelect('CONCAT(YEAR(p.createdAt), \'-\', MONTH(p.createdAt)) AS month')
                    ->groupBy('month')
                ;
            } else if ($groupBy == 'year') {
                $qb
                    ->addSelect('YEAR(p.createdAt) AS year')
                    ->groupBy('year')
                ;
            } else if ($groupBy == 'day') {
                $qb
                    ->addSelect('DATE(p.createdAt) AS day')
                    ->groupBy('day')
                ;
            }
            if ($groupe != null) {
                $qb
                    ->andWhere('p.groupe = :groupe')
                    ->setParameter('groupe', $groupe)
                ;
            }
            return $qb->getQuery()->getResult();
        } catch(DBALException $e) {
            return $e;
        }
    }
}
