<?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\Product\Repository;

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

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

    /**
     * @return ProductCollection[]
     */
    public function findPublished(): array
    {
        return $this->createQueryBuilder('collection')
            ->select('DISTINCT collection, tr, item, product, image')
            ->innerJoin('collection.translations', 'tr', Join::WITH, 'tr.translatable = collection.id')
            ->innerJoin('collection.items', 'item')
            ->innerJoin('item.product', 'product', Join::WITH, 'product.disabled = FALSE AND product.deletedAt IS NULL')
            ->leftJoin('product.image', 'image')
            ->andWhere('collection.disabled = FALSE')
            ->orderBy('collection.position', 'ASC')
            ->addOrderBy('item.position', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findOneBySlug(string $slug): ?ProductCollection
    {
        return $this->createQueryBuilder('collection')
            ->select('DISTINCT collection, tr, item, product, image')
            ->innerJoin('collection.translations', 'tr', Join::WITH, 'tr.translatable = collection.id')
            ->leftJoin('collection.items', 'item')
            ->leftJoin('item.product', 'product', Join::WITH, 'product.disabled = FALSE AND product.deletedAt IS NULL')
            ->leftJoin('product.image', 'image')
            ->andWhere('tr.slug = :slug')
            ->setParameter('slug', $slug)
            ->addOrderBy('item.position', 'ASC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
