<?php

namespace Autogedal\Extend\Block\Product;

use Magediary\ProductQuestion\Model\Question;
use Magento\Framework\Exception\NoSuchEntityException;
use Magediary\ProductQuestion\Helper\Data;
use Magediary\ProductQuestion\Model\ResourceModel\Question\Collection;
use Magediary\ProductQuestion\Model\ResourceModel\Question\CollectionFactory;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Api\ProductRepositoryInterface;

class Tab extends \Magediary\ProductQuestion\Block\Product\Tab
{
    protected $productRepository;

    public function __construct(
        Context $context,
        Registry $registry,
        CollectionFactory $collectionFactory,
        Data $helperData,
        ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct(
            $context,
            $registry,
            $collectionFactory,
            $helperData,
            $data
        );
    }

    /**
     * Set tab title
     *
     * @return void
     */
    public function setTabTitle()
    {
        $tab_title = $this->_helperData->getConfig('question/general/tab_title');

        $title = $this->getCollectionSize()
            ? __("$tab_title (%1)", '<span class="counter">' . $this->getCollectionSize() . '</span>')
            : __($tab_title);
        $this->setTitle($title);
    }

    public function getProductId()
    {
        $productId = $this->getRequest()->getParam('id');
        return $productId ? $productId : null;
    }

    /**
     * Get size of question collection
     *
     * @return int
     */
    public function getCollectionSize()
    {
        
        $currentProductId = $this->getProductId();

        try{
            $currentProduct = $this->productRepository->getById($currentProductId);
        } catch (NoSuchEntityException $e) {
            $currentProduct = null;
        } catch (\Exception $e) {
            $currentProduct = null;
        }
        $categoryIds = [];
        if ($currentProduct) {
            $allCategoryIds = $currentProduct->getCategoryIds();
            $categoryIds = array_filter($allCategoryIds, function($categoryId) {
                return $categoryId != 2;
            });
        }
        
        $collection = $this->_questionsColFactory->create()
            ->addStoreFilter($this->_storeManager->getStore()->getId())
            ->addStatusFilter(\Magediary\ProductQuestion\Model\Question::STATUS_APPROVED);

        $connection = $collection->getConnection();
        
        if (!empty($categoryIds)) {
            $catalogProductEntityTable = $connection->getTableName('catalog_product_entity');
            $catalogCategoryProductTable = $connection->getTableName('catalog_category_product');
            
            $categoryProductsSelect = $connection->select()
                ->from($catalogCategoryProductTable, 'product_id')
                ->where('category_id IN (?)', $categoryIds);
            
            $categoryProductIds = $connection->fetchCol($categoryProductsSelect);
            
            $conditions = [
                $connection->quoteInto('product_id = ?', $currentProductId),
                $connection->quoteInto('(type = 3 AND product_id IN (?))', $categoryProductIds)
            ];
            
            $collection->getSelect()->where(
                '(' . implode(') OR (', $conditions) . ')'
            );
        } else {
            $collection->addProductFilter($currentProductId);
        }

        return $collection->getSize();
    }
}