<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (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\News\Repository;

use CpCreation\VitiCore\News\Model\News;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;

class NewsRepository extends BaseRepository
{
    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, News::class);
    }

    /**
     * @return array<int, News>
     */
    public function findAvailableAndPublish(): array
    {
        return $this->createAvailableAndPublishQueryBuilder('DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return array<int, News>
     */
    public function findAvailableAndPublishDesc(): array
    {
        return $this->createAvailableAndPublishQueryBuilder('DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return array<int, News>
     */
    public function findAvailableAndPublishAsc(): array
    {
        return $this->createAvailableAndPublishQueryBuilder('ASC')
            ->getQuery()
            ->getResult();
    }

    public function findOneAvailableBySlug(string $slug): ?News
    {
        $date = new \DateTimeImmutable();

        return $this->createQueryBuilder('news')
            ->addSelect('translation')
            ->innerJoin('news.translations', 'matchingTranslation', Join::WITH, 'matchingTranslation.translatable = news.id')
            ->leftJoin('news.translations', 'translation', Join::WITH, 'translation.translatable = news.id')
            ->andWhere('matchingTranslation.slug = :slug')
            ->andWhere('news.unPublishedAt >= :date OR news.unPublishedAt IS NULL')
            ->andWhere('news.publishedAt <= :date OR news.publishedAt IS NULL')
            ->andWhere('news.disabled = FALSE')
            ->setParameter('slug', $slug)
            ->setParameter('date', $date)
            ->getQuery()
            ->getOneOrNullResult();
    }

    private function createAvailableAndPublishQueryBuilder(string $order): QueryBuilder
    {
        $date = new \DateTime('now');

        return $this->createQueryBuilder('n')
            ->where('n.unPublishedAt >= :date OR n.unPublishedAt IS NULL')
            ->andWhere('n.publishedAt <= :date OR n.publishedAt IS NULL')
            ->addSelect('tr')
            ->innerJoin('n.translations', 'tr', Join::WITH, 'tr.translatable = n.id')
            ->andWhere('n.disabled = FALSE')
            ->addOrderBy('n.eventAt', $order)
            ->setParameter('date', $date);
    }
}
