<?php

/**
 * @author Julien Colinet
 */

namespace CpCreation\VitiCore\Popup\Repository;

use CpCreation\VitiCore\Popup\Model\Popup;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\Persistence\ManagerRegistry;

class PopupRepository extends BaseRepository
{
    /**
     * PopupRepository constructor.
     * @param ManagerRegistry $registry
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Popup::class);
    }

    /**
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findOneOrNull()
    {
        $popup = $this
            ->createQueryBuilder('p')
            ->andWhere('p.publishedAt <= :datetime ')
            ->andWhere('p.unPublishedAt >= :datetime')
            ->setMaxResults(1)
            ->setParameter('datetime', new \DateTime('now'))
            ->getQuery()
            ->setMaxResults(1)
        ;

        return $popup->getOneOrNullResult();
    }
}