<?php

declare(strict_types=1);

namespace Webkul\DamBundle\ItemCount;

use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;

$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();

/**
 * Category product counter, using a PQB.
 *
 * @author    Aman Srivastava <aman.srivastava462@webkul.com>
 * @copyright 2019 Webkul Software Pvt. Ltd. (https://webkul.com)
 */
class AssetProductCounter implements \CategoryItemsCounterInterface
{


    /** @var CategoryRepositoryInterface */
    protected $categoryRepository;

    /**
     * @param ProductQueryBuilderFactoryInterface $pqbFactory
     * @param CategoryRepositoryInterface         $categoryRepository
     */
    public function __construct(
        \CategoryRepositoryInterface $categoryRepository
    ) {
        $this->categoryRepository = $categoryRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function getItemsCountInCategory(\CategoryInterface $category, $inChildren = false, $inProvided = true)
    {
        $categoryCodes = $inChildren
        ? $this->categoryRepository->getAllChildrenCodes($category, $inProvided)
        : [$category->getCode()];
        
        $options = [
            'filters' => [
                    [
                        'field' => 'categories',
                        'operator' => \Operators::IN_LIST,
                        'value' => $categoryCodes
                    ]
                ]
            ];
            
        $pqb = $this->categoryRepository->getCountAqb($options);
        
        
        $items = $pqb->getSingleScalarResult();
        
        return $items;
    }
}
