<?php

namespace App\Repository;

use App\Entity\SectorisationVersion;
use App\Entity\Site;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method SectorisationVersion|null find($id, $lockMode = null, $lockVersion = null)
 * @method SectorisationVersion|null findOneBy(array $criteria, array $orderBy = null)
 * @method SectorisationVersion[]    findAll()
 * @method SectorisationVersion[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class SectorisationVersionRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, SectorisationVersion::class);
    }

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function add(SectorisationVersion $entity, bool $flush = true): void
    {
        $this->_em->persist($entity);
        if ($flush) {
            $this->_em->flush();
        }
    }

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function remove(SectorisationVersion $entity, bool $flush = true): void
    {
        $this->_em->remove($entity);
        if ($flush) {
            $this->_em->flush();
        }
    }

    public function getLastVersion(Site $site){
        $qb = $this->createQueryBuilder('s');
        $expr = $qb->expr();
        $qb->andWhere($expr->in('s.site',  ':ids'))
            ->andWhere('s.date_debut <= :now')
            ->orderBy('s.date_debut')
            ->setParameter('ids', [$site->getId(), null])
            ->setParameter('now', new \DateTime())
            ->getQuery()->getResult();

        $query = $qb->getQuery();
        return $query->getOneOrNullResult();
    }

    public function getVersionProd(Site $site){
        $qb = $this->createQueryBuilder('s');
        $expr = $qb->expr();
        $qb->andWhere($expr->in('s.site',  ':ids'))
            ->andWhere('s.en_prod = true')
            ->setParameter('ids', [$site->getId(), null])
            ->getQuery()->getResult();

        $query = $qb->getQuery();
        return $query->getOneOrNullResult();
    }


}
