<?php
/**
 * Webkul Software.
 *
 * @category   Webkul
 * @package    Webkul_Agorae
 * @author     Webkul Software Private Limited
 * @copyright  Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license    https://store.webkul.com/license.html
 */
namespace Webkul\Agorae\Block;

use Magento\Framework\View\Element\Template\Context;

/**
 * Agorae Sellercategory Block
 */
class Sellercategory extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Framework\Module\Manager
     */
    protected $moduleManager;

    /**
     * @var \Webkul\Marketplace\Block\Sellercategory
     */
    protected $sellerCategory;

    /**
     * @var \Magento\Framework\App\ObjectManager::getInstance();
     */
    protected $objectManager;

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;

    /**
     * @var \Webkul\Marketplace\Helper\Data
     */
    protected $mpHelper;

    /**
     * @var \Webkul\Marketplace\Model\ResourceModel\Seller\Collection
     */
    protected $mpSeller;

    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute
     */
    protected $eavAttribute;

    /**
     * @var \Webkul\Marketplace\Model\ResourceModel\Product\Collection
     */
    protected $mpProduct;

    /**
     * @var \Webkul\Marketplace\Model\Product
     */
    protected $mpProductModel;

    /**
     * @param Context                                           $context
     * @param \Magento\Framework\Module\Manager                 $moduleManager
     * @param \Magento\Catalog\Model\ProductFactory             $productFactory
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
     * @param array                                             $data
     */
    public function __construct(
        Context $context,
        \Magento\Framework\Module\Manager $moduleManager,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute,
        array $data = []
    ) {
        $this->objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $this->productFactory = $productFactory;
        $this->moduleManager = $moduleManager;
        $this->eavAttribute = $eavAttribute;
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $this->sellerCategory = $this->objectManager->create(\Webkul\Marketplace\Block\Sellercategory::class);
            $this->mpHelper = $this->objectManager->create(\Webkul\Marketplace\Helper\Data::class);
            $this->mpSeller = $this->objectManager->create(
                \Webkul\Marketplace\Model\ResourceModel\Seller\Collection::class
            );
            $this->mpProduct = $this->objectManager->create(
                \Webkul\Marketplace\Model\ResourceModel\Product\Collection::class
            );
            $this->mpProductModel = $this->objectManager->create(\Webkul\Marketplace\Model\Product::class);
        }
        parent::__construct($context, $data);
    }
    /**
     * GetCategoryList used to get category list
     *
     * @return object
     */
    public function getCategoryList()
    {
        $sellerId = $this->sellerCategory->getProfileDetail()->getSellerId();
        $querydata = $this->mpProductModel->getCollection()
        ->addFieldToFilter('seller_id', $sellerId)
        ->addFieldToFilter('status', ['neq' => 2])
        ->addFieldToSelect('mageproduct_id')
        ->setOrder('mageproduct_id');
        $collection = $this->productFactory->create()->getCollection()
        ->addAttributeToSelect('entity_id')
        ->addAttributeToFilter('entity_id', ['in' => $querydata->getData()])
        ->addAttributeToFilter('visibility', ['in' => [4]])
        ->addAttributeToFilter(
            'is_seller_pick',
            1
        );// updated this
        $collection->addStoreFilter();
        $collectionConfigurable = $this->productFactory->create()
        ->getCollection()
        ->addAttributeToFilter('type_id', 'configurable')
        ->addAttributeToFilter('entity_id', ['in' => $querydata->getData()]);
        $outOfStockConfis = [];
        foreach ($collectionConfigurable as $_configurableproduct) {
            $product = $this->productFactory->create()->load($_configurableproduct->getId());
            if (!$product->getData('is_salable')) {
                $outOfStockConfis[] = $product->getId();
            }
        }
        if (count($outOfStockConfis)) {
            $collection->addAttributeToFilter(
                'entity_id',
                ['nin' => $outOfStockConfis]
            );
        }
        $collectionBundle = $this->productFactory->create()->getCollection()
        ->addAttributeToFilter('type_id', 'bundle')
        ->addAttributeToFilter(
            'entity_id',
            ['in' => $querydata->getData()]
        );
        $outOfStockConfis = [];
        foreach ($collectionBundle as $_bundleproduct) {
            $product = $this->productFactory->create()->load($_bundleproduct->getId());
            if (!$product->getData('is_salable')) {
                $outOfStockConfis[] = $product->getId();
            }
        }
        if (count($outOfStockConfis)) {
            $collection->addAttributeToFilter(
                'entity_id',
                ['nin' => $outOfStockConfis]
            );
        }
        $collectionGrouped = $this->productFactory->create()->getCollection()
        ->addAttributeToFilter('type_id', 'grouped')
        ->addAttributeToFilter('entity_id', ['in' => $querydata->getData()]);
        $outOfStockConfis = [];
        foreach ($collectionGrouped as $_groupedproduct) {
            $product = $this->productFactory->create()->load($_groupedproduct->getId());
            if (!$product->getData('is_salable')) {
                $outOfStockConfis[] = $product->getId();
            }
        }
        if (count($outOfStockConfis)) {
            $collection->addAttributeToFilter(
                'entity_id',
                ['nin' => $outOfStockConfis]
            );
        }
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $marketplaceProduct = $this->mpProduct->getTable('marketplace_product');
            $collection->getSelect()->join(
                ['mpp' => $marketplaceProduct],
                'mpp.mageproduct_id = e.entity_id',
                ['mageproduct_id' => 'e.entity_id']
            );
        }
        $eavAttribute = $this->eavAttribute;
        $proAttId = $eavAttribute->getIdByCode('catalog_category', 'name');
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $storeId = $this->mpHelper->getCurrentStoreId();
            $paramData = $this->getRequest()->getParams();
            if (!isset($paramData['c'])) {
                $paramData['c'] = '';
            }
            if (!$paramData['c']) {
                $parentid = $this->mpHelper->getRootCategoryIdByStoreId($storeId);
            } else {
                $parentid = $paramData['c'];
            }
            $catalogCategoryProduct = $this->mpSeller->getTable('catalog_category_product');
            $catalogCategoryEntity = $this->mpSeller->getTable('catalog_category_entity');
            $catalogCategoryEntityVarchar = $this->mpSeller->getTable('catalog_category_entity_varchar');
            $collection->getSelect()->join(
                ['ccp' => $catalogCategoryProduct],
                'ccp.product_id = mpp.mageproduct_id',
                ['category_id' => 'category_id']
            )->join(
                ['cce' => $catalogCategoryEntity],
                'cce.entity_id = ccp.category_id',
                ['parent_id' => 'parent_id']
            )
            ->where("cce.parent_id = '".$parentid."'")
            ->columns('COUNT(*) AS countCategory')
            ->group('category_id')
            ->join(
                ['ce1' => $catalogCategoryEntityVarchar],
                'ce1.entity_id = ccp.category_id',
                ['catname' => 'value']
            )->where('ce1.attribute_id = '.$proAttId.' AND ce1.store_id = 0')
            ->order('catname');
        }
        return $collection->getData();
    }
}
