<?php

namespace App\Repository;

use App\Entity\Adherent;
use App\Entity\CotisationAdherent;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function isCotisationAdherentExist(Adherent $adherent, $montant, $year): bool
    {
        $qb = $this->createQueryBuilder('f');

        $result = $qb
            ->leftJoin('f.cotisationInfos', 'i')
            ->where("f.type = 'cotisation_adherent'")
            ->andWhere('f.montant = :montant')
            ->andWhere('f.expediteur = :adherent')
            ->andWhere('i.annee = :year')
            ->setParameter('montant', $montant)
            ->setParameter('adherent', $adherent)
            ->setParameter('year', $year)
            ->getQuery()
            ->getResult();

        return !empty($result);
    }
}
