<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\News\Repository;

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

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

    public function findAvailableAndPublish()
    {
        $date = new \DateTime('now');

        $qb = $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', 'DESC')
                   ->setParameter('date', $date)
                   ->getQuery();

        return $qb->execute();
    }

    public function findAvailableAndPublishDesc()
    {
        $date = new \DateTime('now');

        $qb = $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', 'DESC')
                   ->setParameter('date', $date)
                   ->getQuery();

        return $qb->execute();
    }

    public function findAvailableAndPublishAsc()
    {
        $date = new \DateTime('now');

        $qb = $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', 'ASC')
                   ->setParameter('date', $date)
                   ->getQuery();

        return $qb->execute();
    }
}