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

use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductVariant;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findAllPublishQuery(): QueryBuilder
    {
        return $this->createQueryBuilder('pv')
            ->innerJoin('pv.product', 'p')
            ->andWhere('p.disabled = FALSE')
            ->andWhere('pv.unPublished = FALSE')
            ->andWhere('pv.deletedAt IS NULL')
            ->orderBy('p.position', 'ASC');
    }

    public function getVariantsByProduct(Product $product): Collection
    {
        $qb = $this->createQueryBuilder('variant')
            ->innerJoin('variant.product', 'product', Join::WITH, 'product.id = :id')
            ->andWhere('variant.unPublished = FALSE')
            ->andWhere('variant.deletedAt is NULL')
            ->addOrderBy('variant.position', 'ASC')
            ->setParameter('id', $product->getId());

        return new ArrayCollection($qb->getQuery()->getResult());
    }
}
