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

/**
 * Agorae Model Plugin Bestsellproducts
 */
class Bestsellproducts
{
    /**
     * aroundAddOrderedQty calls in place of addOrderedQty
     *
     * @return object
     */
    public function aroundAddOrderedQty(
        \Magento\Reports\Model\ResourceModel\Product\Sold\Collection $subject,
        \Closure $proceed,
        $from = '',
        $to = ''
    ) {
        $connection = $subject->getConnection();
        $orderTableAliasName = $connection->quoteIdentifier('order');
        $orderJoinCondition = [
            $orderTableAliasName . '.entity_id = order_items.order_id',
            $connection->quoteInto("{$orderTableAliasName}.state <> ?", \Magento\Sales\Model\Order::STATE_CANCELED),
        ];
        if ($from != '' && $to != '') {
            $fieldName = $orderTableAliasName . '.created_at';
            $orderJoinCondition[] = $subject->prepareBetweenSql($fieldName, $from, $to);
        }
        $subject->getSelect()->reset()->from(
            ['order_items' => $subject->getTable('sales_order_item')],
            ['ordered_qty' => 'SUM(order_items.qty_ordered)',
                'order_items_name' => 'order_items.name',
                'order_items_id' => 'order_items.item_id',
                'order_items_product_id' => 'order_items.product_id',
            ]
        )->joinInner(
            ['order' => $subject->getTable('sales_order')],
            implode(' AND ', $orderJoinCondition),
            []
        )->where(
            'parent_item_id IS NULL'
        )->group(
            'order_items.product_id'
        )->having(
            'SUM(order_items.qty_ordered) > ?',
            0
        );
        return $subject;
    }
}
