<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\AnneeScolaire;
use App\Entity\Ecole;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<AnneeScolaire> */
final class AnneeScolaireRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry) { parent::__construct($registry, AnneeScolaire::class); }

    /** @return list<AnneeScolaire> */
    public function findForEcole(Ecole $ecole, bool $activeOnly = false): array
    {
        $qb = $this->createQueryBuilder('annee')
            ->leftJoin('annee.section', 'section')->addSelect('section')
            ->andWhere('annee.ecole = :ecole')
            ->setParameter('ecole', $ecole)
            ->orderBy('annee.dateDebut', 'DESC')
            ->addOrderBy('annee.libelle', 'ASC');
        if ($activeOnly) { $qb->andWhere('annee.active = :active')->setParameter('active', true); }
        return $qb->getQuery()->getResult();
    }

    public function countForEcole(Ecole $ecole): int
    {
        return (int) $this->createQueryBuilder('annee')->select('COUNT(annee.id)')
            ->andWhere('annee.ecole = :ecole')->setParameter('ecole', $ecole)
            ->getQuery()->getSingleScalarResult();
    }

    public function findCurrentForEcole(Ecole $ecole): ?AnneeScolaire
    {
        return $this->createQueryBuilder('annee')
            ->andWhere('annee.ecole = :ecole')
            ->andWhere('annee.active = :active')
            ->andWhere('annee.statut = :statut')
            ->setParameter('ecole', $ecole)
            ->setParameter('active', true)
            ->setParameter('statut', 'ACTIVE')
            ->orderBy('annee.dateDebut', 'DESC')
            ->addOrderBy('annee.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
