<?php

namespace App\Repository;

use App\Entity\ExternalAdherentDatedData;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<ExternalAdherentDatedData>
 *
 * @method ExternalAdherentDatedData|null find($id, $lockMode = null, $lockVersion = null)
 * @method ExternalAdherentDatedData|null findOneBy(array $criteria, array $orderBy = null)
 * @method ExternalAdherentDatedData[]    findAll()
 * @method ExternalAdherentDatedData[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 * @method null                                       removeAll()
 */
class ExternalAdherentDatedDataRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ExternalAdherentDatedData::class);
        $em = $this->getEntityManager();
        $this->connection = $em->getConnection();
    }

    /**
     * @throws ORMException
     * @return int|Null Returns the max number of ExternalAdherentDatedData an adherent can have
     */
    public function getMaxDatedDataCount()
    {
        $sqlQuery = "SELECT MAX(dated_data_count.count) AS max_dated_data_count 
                    FROM (
                        SELECT COUNT(*) AS count 
                        FROM external_adherent_dated_data 
                        GROUP BY adherent_id
                    ) AS dated_data_count;";
        
        $statement = $this->connection->prepare($sqlQuery);
        $statement->execute();
        $result = $statement->fetchAll()[0]["max_dated_data_count"];

        return $result;
    }
}
