<?php
/**
 * Quote\Grid\Collection.php
 *
 * @category  Magetop Extensions
 * @package   Magetop_Quotesystem
 * @author    Magetop Developer
 * @copyright Copyright (c) Magetop (https://www.magetop.com)
 * @license   https://www.magetop.com/license.html
 */

namespace Magetop\Quotesystem\Model\ResourceModel\QuoteDetails\Grid;

use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Search\AggregationInterface;
use Magetop\Quotesystem\Model\ResourceModel\QuoteDetails\Collection as QuoteCollection;

class Collection extends QuoteCollection implements SearchResultInterface
{
    /**
     * @var AggregationInterface
     */
    protected $_aggregations;

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

    /**
     * @param \Magento\Framework\Data\Collection\EntityFactoryInterface    $entityFactory
     * @param \Psr\Log\LoggerInterface                                     $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface                    $eventManager
     * @param \Magento\Store\Model\StoreManagerInterface                   $storeManager
     * @param [type]                                                       $mainTable
     * @param [type]                                                       $eventPrefix
     * @param [type]                                                       $eventObject
     * @param [type]                                                       $resourceModel
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute            $eavAttribute
     * @param string                                                       $model
     * @param [type]                                                       $connection
     * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb         $resource
     */
    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        $mainTable,
        $eventPrefix,
        $eventObject,
        $resourceModel,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute,
        $model = \Magento\Framework\View\Element\UiComponent\DataProvider\Document ::class,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        $this->eavAttribute = $eavAttribute;
        parent::__construct(
            $entityFactory,
            $logger,
            $fetchStrategy,
            $eventManager,
            $storeManager,
            $connection,
            $resource
        );
        $this->_eventPrefix = $eventPrefix;
        $this->_eventObject = $eventObject;
        $this->_init($model, $resourceModel);
        $this->setMainTable($mainTable);
    }

    /**
     * Get Aggregations
     *
     * @return AggregationInterface
     */
    public function getAggregations()
    {
        return $this->_aggregations;
    }

    /**
     * Set Aggregations
     *
     * @param AggregationInterface $aggregations
     * @return $this
     */
    public function setAggregations($aggregations)
    {
        $this->_aggregations = $aggregations;
    }

    /**
     * Retrieve clear select
     *
     * @return \Magento\Framework\DB\Select
     */
    protected function _getClearSelectMethod()
    {
        return $this->_buildClearSelect();
    }
    /**
     * Build clear select
     *
     * @param  \Magento\Framework\DB\Select $select
     * @return \Magento\Framework\DB\Select
     */
    protected function _buildClearSelect($select = null)
    {
        if (null === $select) {
            $select = clone $this->getSelect();
        }
        $select->reset(\Magento\Framework\DB\Select::GROUP);
        $select->reset(\Magento\Framework\DB\Select::ORDER);
        $select->reset(\Magento\Framework\DB\Select::LIMIT_COUNT);
        $select->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET);
        $select->reset(\Magento\Framework\DB\Select::COLUMNS);
        return $select;
    }
     
    /**
     * Retrieve all ids for collection
     *
     * Backward compatibility with EAV collection
     *
     * @param  int $limit
     * @param  int $offset
     * @return array
     */
    public function getAllIds($limit = null, $offset = null)
    {
        $idsSelect = $this->_getClearSelectMethod();
        $idsSelect->columns('entity_id');
        $idsSelect->columns(['SUM(qts.quote_price) AS total_price']);
        $idsSelect->limit($limit, $offset);
        $idsSelect->resetJoinLeft();
        return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
    }

    /**
     * Get search criteria.
     *
     * @return \Magento\Framework\Api\SearchCriteriaInterface|null
     */
    public function getSearchCriteria()
    {
        return null;
    }

    /**
     * Set search criteria.
     *
     * @param  \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return $this
     */
    public function setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria = null)
    {
        return $this;
    }

    /**
     * Get total count.
     *
     * @return int
     */
    public function getTotalCount()
    {
        $size = $this->getSize();
        if ($size == 0 || $size == null) {
            $size = $this->getSizeAfterFilter();
        }
        return $size;
    }

    /**
     * Set total count.
     *
     * @param                                         int $totalCount
     * @return                                        $this
     */
    public function setTotalCount($totalCount)
    {
        return $this;
    }

    /**
     * Set items list.
     *
     * @param  \Magento\Framework\Api\ExtensibleDataInterface[] $items
     * @return $this
     */
    public function setItems(array $items = null)
    {
        return $this;
    }

    /**
     * Select data
     *
     * @return $this
     */
    protected function _initSelect()
    {
        $eavAttribute = $this->eavAttribute;
        $proAttrId = $eavAttribute->getIdByCode("catalog_product", "name");
        $catalogProductEntityVarchar = $this->getTable('catalog_product_entity_varchar');

        $joinTable = $this->getTable('customer_grid_flat');
        $this->getSelect()->join(
            $joinTable.' as cgf',
            'main_table.customer_id = cgf.entity_id',
            [
                'customer_name'=>'name',
                'email'=>'email',
            ]
        );
        $this->addFilterToMap("name", "cpev.value");
        $this->addFilterToMap("customer_name", "cgf.name");
        $this->addFilterToMap("email", "cgf.email");
        $this->addFilterToMap('created_at', 'main_table.created_at');
        $joinTable = $this->getTable('mt_quotes');
        $this->getSelect()->join(
            $joinTable.' as qts',
            'main_table.entity_id = qts.quote_id',
            [
                'quote_id' => 'qts.quote_id',
                'total_price'=>'SUM(qts.quote_price)'
            ]
        );
        $this->addFilterToMap('quote_id', 'qts.quote_id');
        $this->addFieldToFilter('quote_generate', 1);
        parent::_initSelect();
    }

    /**
     * Join to get Product name in grid.
     */
    protected function _renderFiltersBefore()
    {
        $select = $this->getSelect();
        $where = $this->getSelect()->getPart('where');
        foreach ($where as &$item) {
            if (strpos($item, '`total_price` >=') !== false) {
                $fromValueExplode = explode("`total_price` >=", $item);
                $fromValue = ltrim(str_replace(")))", "", $fromValueExplode[1]));
                $item = str_replace("AND (((`total_price` >= $fromValue)))", "", $item);
                $this->getSelect()->having('SUM(quote_price) >= '.$fromValue);
                
            }
            if (strpos($item, '`total_price` <=') !== false) {
                $endValueExplode = explode("`total_price` <=", $item);
                $endValue = ltrim(str_replace(")))", "", $endValueExplode[1]));
                $item = str_replace("AND (((`total_price` <= $endValue)))", "", $item);
                $this->getSelect()->having('SUM(quote_price) <= '.$endValue);
            }
        }
        $this->getSelect()->setPart('where', $where);
        $this->getSelect()->group("main_table.entity_id");
        parent::_renderFiltersBefore();
    }

    /**
     * Get collection size after filter
     */
    public function getSizeAfterFilter()
    {
        $sql = $this->getSelect();
        $this->_totalRecords = count($this->getConnection()->fetchAll($sql, $this->_bindParams));
        return $this->_totalRecords;
    }
}
