<?php

namespace Autogedal\Extend\Block\Question;

use Magediary\ProductQuestion\Model\Answer;
use Magento\Framework\Exception\NoSuchEntityException;

class ListView extends \Magediary\ProductQuestion\Block\Question\ListView
{
    public function getProductId()
    {
        $productId = $this->getRequest()->getParam('id');
        return $productId ? $productId : null;
    }

    /**
     * Get collection of questions
     *
     * @return QuestionCollection
     */
    public function getQuestionsCollection()
    {
        if (null === $this->_questionsCollection) {
            
            $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;
                });
            }
            
            
            $this->_questionsCollection = $this->_questionsColFactory->create()
                ->addStoreFilter($this->_storeManager->getStore()->getId())
                ->addStatusFilter(\Magediary\ProductQuestion\Model\Question::STATUS_APPROVED);

            $connection = $this->_questionsCollection->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)
                ];
                
                $this->_questionsCollection->getSelect()->where(
                    '(' . implode(') OR (', $conditions) . ')'
                );
            } else {
                $this->_questionsCollection->addProductFilter($currentProductId);
            }

            $searchTerm = $this->getRequest()->getParam('search_term');
            if (!empty($searchTerm)) {
                $this->_questionsCollection->addFieldToFilter(
                    'detail',
                    ['like' => '%' . $searchTerm . '%']
                );
            }

            $this->_questionsCollection->getSelect()->order([
                new \Zend_Db_Expr('CASE WHEN type = 3 THEN 0 ELSE 1 END ASC'),
                new \Zend_Db_Expr('created_at DESC')
            ]);
        }

        return $this->_questionsCollection;
    }
    
    /**
     * Get collection of answers
     *
     * @param int $questionId
     * @return mixed
     */
    public function getFullAnswersCollection($questionId)
    {
        $answersCollection = $this->_answersColFactory->create()->addStatusFilter(
            Answer::STATUS_APPROVED
        )->addQuestionFilter(
            $questionId
        )->setDateOrder()
        ->load();

        return $answersCollection;
    }

    /**
     * Prepare product question list toolbar
     *
     * @return $this
     */
    protected function _prepareLayout()
    {
        \Magediary\ProductQuestion\Block\Product\View::_prepareLayout();

        $toolbar = $this->getLayout()->getBlock('product_question_list.toolbar');
        if ($toolbar) {
            $toolbar->setAvailableLimit([5 => 5]);
            $toolbar->setCollection($this->getQuestionsCollection());
            $this->setChild('toolbar', $toolbar);
        }

        return $this;
    }

    /**
     * Get answer trigger URL for ajax call
     *
     * @return string
     */
    public function getAnswerTriggerUrl()
    {
        return $this->getUrl(
            'prodquestion/answer/trigger',
            [
                '_secure' => $this->getRequest()->isSecure(),
            ]
        );
    }
}
