<?php

namespace Lc\ShopBundle\Repository;

use Doctrine\ORM\QueryBuilder;
use Lc\ShopBundle\Context\DefaultRepositoryInterface;
use Lc\ShopBundle\Context\ProductCategoryInterface;

/**
 * @method ProductCategoryInterface|null find($id, $lockMode = null, $lockVersion = null)
 * @method ProductCategoryInterface|null findOneBy(array $criteria, array $orderBy = null)
 * @method ProductCategoryInterface[]    findAll()
 * @method ProductCategoryInterface[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class ProductCategoryRepository extends BaseRepository implements DefaultRepositoryInterface
{

        public function getInterfaceClass()
        {
                return ProductCategoryInterface::class;
        }

        public static function adminQueryBuilderForTree(BaseRepository $e): QueryBuilder
        {
                return $e->createQueryBuilder('e')
                        ->where('e.parent is NULL')
                        ->andWhere('e.status >= 0')
                        ->orderBy('e.position', 'ASC');
        }

        public function findOneBySlug($slug)
        {
                $query = $this->findByMerchantQuery() ;
                $query->andWhere('e.slug = :slug')->setParameter('slug',$slug) ;
                return $query->getQuery()->getOneOrNullResult() ;
        }

        public function findAllParents($withOffline = false)
        {
                $query = $this->findByMerchantQuery()
                        ->andWhere('e.parent is NULL');

                if ($withOffline) $query->andWhere('e.status >= 0');
                else $query->andWhere('e.status = 1');

                $query->orderBy('e.position', 'ASC');

                return $query->getQuery()->getResult();
        }

        public function findAllByParent($parentCategory, $withOffline = false, $withEmptyCategories = true)
        {
                $query = $this->createQueryBuilder('e');
                $query->andWhere('e.parent = :idParentCategory');
                $query->setParameter('idParentCategory', $parentCategory->getId());

                if ($withOffline) $query->andWhere('e.status >= 0');
                else $query->andWhere('e.status = 1');

                if(!$withEmptyCategories) {
                        $query->innerJoin('e.productFamilies','pf') ;
                        $query->andWhere('pf.status = 1') ;
                }

                $query->addOrderBy('e.position', 'ASC') ;

                return $query->getQuery()->getResult();
        }
}
