<?php

declare(strict_types=1);

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Popup\Repository;

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

class PopupRepository extends BaseRepository
{
    /**
     * @throws \ReflectionException
     */
    public function __construct(private ManagerRegistry $registry)
    {
        parent::__construct($this->registry, Popup::class);
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findOneOrNull(): ?Popup
    {
        $popup = $this->createActiveQueryBuilder()
            ->andWhere('p.popup = TRUE')
            ->setMaxResults(1)
            ->getQuery();

        /** @var Popup|null $result */
        $result = $popup->getOneOrNullResult();

        return $result;
    }

    /**
     * @return list<Popup>
     */
    public function findAllActive(): array
    {
        return $this->createActiveQueryBuilder()
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<Popup>
     */
    public function findAllActiveByMode(bool $popup): array
    {
        return $this->createActiveQueryBuilder()
            ->andWhere('p.popup = :popup')
            ->setParameter('popup', $popup)
            ->getQuery()
            ->getResult();
    }

    private function createActiveQueryBuilder()
    {
        return $this
            ->createQueryBuilder('p')
            ->andWhere('p.disabled = FALSE')
            ->andWhere('(p.publishedAt <= :datetime OR p.publishedAt IS NULL)')
            ->andWhere('(p.unPublishedAt >= :datetime OR p.unPublishedAt IS NULL)')
            ->setParameter('datetime', new \DateTime('now'))
            ->orderBy('p.publishedAt', 'DESC')
            ->addOrderBy('p.createdAt', 'DESC');
    }
}
