<?php

/*
 * 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\News\Repository;

use CpCreation\VitiCore\News\Model\Category;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends BaseRepository<Category>
 */
class CategoryRepository extends BaseRepository
{
    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Category::class);
    }

    /**
     * @return array<int, Category>
     */
    public function findCategories(): array
    {
        $date = new \DateTime('now');

        return $this
            ->createQueryBuilder('cat')
            ->innerJoin('cat.news', 'n')
            ->where('n.unPublishedAt >= :date OR n.unPublishedAt IS NULL')
            ->andWhere('n.publishedAt <= :date OR n.publishedAt IS NULL')
            ->andWhere('n.disabled = FALSE')
            ->addOrderBy('cat.position', 'ASC')
            ->addOrderBy('n.eventAt', 'DESC')
            ->setParameter('date', $date)
            ->getQuery()
            ->getResult();
    }
}
