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

namespace CpCreation\VitiCore\Product\Repository;

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

class ProductTypeRepository extends BaseRepository
{
    /**
     * ProductTypeRepository constructor.
     * @param ManagerRegistry $registry
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ProductType::class);
    }
    public function findTypes()
    {
        return $this->createQueryBuilder('productType')
                    ->select('productType.name')
                    ->groupBy('productType.name')
                    ->getQuery()
                    ->getArrayResult();
    }

    /**
     * @param string $name
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findTypeByName(string $name)
    {
        $qb = $this
            ->createQueryBuilder('p')
            ->innerJoin('p.translations', 'tr', Join::WITH,'tr.name = :name')
            ->setParameter('name', $name)
            ->getQuery()
            ->setMaxResults(1)
            ->getOneOrNullResult();

        return $qb;
    }

    /**
     * @param string $slug
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findTypeBySlug(string $slug)
    {
        $qb = $this
            ->createQueryBuilder('p')
            ->innerJoin('p.translations', 'tr', Join::WITH,'tr.slug = :slug')
            ->setParameter('slug', $slug)
            ->getQuery()
            ->setMaxResults(1)
            ->getOneOrNullResult();

        return $qb;
    }

    /**
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findDefaultType()
    {
        $qb = $this
            ->createQueryBuilder('p')
            ->andWhere('p.equivalencyDefault = TRUE')
            ->getQuery()
            ->setMaxResults(1)
            ->getOneOrNullResult();

        return $qb;
    }
}
