<?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;

/**
 * Agorae Homepage Block
 */
class Homepage extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Webkul\Agorae\Helper\Data
     */
    protected $_helper;

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

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

    /**
     * @var \Webkul\Marketplace\Model\Saleslist
     */
    protected $_salesList;

    /**
     * @var \Webkul\Marketplace\Model\Saleslist
     */
    protected $_attributes;

    /**
     * @var \Webkul\Marketplace\Model\Orders
     */
    protected $_mpOrders;

    /**
     * @var sellerArr
     */
    protected $sellerArr = [];

    /**
     * @var \Magento\Framework\Module\Manager
     */
    protected $moduleManager;

    /**
     * @var \Magento\Framework\App\ObjectManager
     */
    protected $objectManager;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Webkul\Agorae\Helper\Data                       $helper
     * @param \Magento\Framework\Module\Manager                $moduleManager
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Webkul\Agorae\Helper\Data $helper,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute $attributes,
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    ) {
        $this->objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $this->_helper = $helper;
        $this->_attributes = $attributes;
        $this->moduleManager = $moduleManager;
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $this->_marketplaceProductsFactory = $this->objectManager->create(
                \Webkul\Marketplace\Model\ResourceModel\Seller\CollectionFactory::class
            );
            $this->_salesList = $this->objectManager->create(\Webkul\Marketplace\Model\Saleslist::class);
            $this->_marketplaceDataHelper = $this->objectManager->create(\Webkul\Marketplace\Helper\Data::class);
            $this->_mpOrders = $this->objectManager->create(\Webkul\Marketplace\Model\Orders::class);
        }
        parent::__construct($context, $data);
    }

    /**
     * [getSliderImages used to get slider images used on frontend]
     *
     * @return boolean | array
     */
    public function getSliderImages()
    {
        $images = [];
        try {
            $collection = $this->_helper->getSliderImagesCollection();
            if ($collection->getSize()) {
                foreach ($collection as $value) {
                    $images[] = $value->getLink();
                }
            }
            return $images;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * [getTopCategories used to get top categories]
     *
     * @return array
     */
    public function getTopCategories()
    {
        $options = [];
        try {
            $categoriesConfig = $this->_helper->getTopTwoCategories();
            if ($categoriesConfig) {
                $categories = explode(",", $categoriesConfig);
                if (count($categories)==2) {
                    foreach ($categories as $categoryId) {
                        $categoryObj = $this->_helper->getCategory($categoryId);
                        $options[] = [
                            'name' => $categoryObj->getName(),
                            'id' => $categoryObj->getId()
                        ];
                    }
                } else {
                    $categoryOptions = $this->_helper->getTopTwoLevelCategories();
                }
            } else {
                $categoryOptions = $this->_helper->getTopTwoLevelCategories();
            }
            if (isset($categoryOptions) && count($categoryOptions)) {
                $i = 0;
                foreach ($categoryOptions as $key => $value) {
                    if ($i<2) {
                        $options[] = [
                            'name' => $value['label'],
                            'id' => $value['value']
                        ];
                    } else {
                        break;
                    }
                    $i++;
                }
            }
            return $options;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetSubCategories getting child categories of parent category
     *
     * @param  int $id [contains parent category id]
     * @return object
     */
    public function getSubCategories($id)
    {
        try {
            $collection = $this->_helper->getCategoryCollection();
            $collection->addAttributeToSelect('*')
                ->addAttributeToFilter('level', 3)
                ->addAttributeToFilter('is_active', 1)
                ->addFieldToFilter('parent_id', $id)
                ->setPageSize(5)
                ->setCurPage(1);

            return $collection;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetLevel4Categories used to get forth level category
     *
     * @return object
     */
    public function getLevel4Categories($categoryId)
    {
        try {
            $collection = $this->_helper->getCategoryCollection();
            $collection->addAttributeToSelect('*')
            ->addAttributeToFilter('level', 4)
            ->addAttributeToFilter('is_active', 1)
            ->addFieldToFilter('parent_id', ['in'=>$categoryId])
            ->setPageSize(6)
            ->setCurPage(1);

            return $collection;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetCategoryImage get Agorae category Image
     *
     * @param  int $categoryId [contains category ID]
     * @return boolean | string
     */
    public function getCategoryImage($wkImage, $categoryImageUrl)
    {
        try {
            $imageUrl = $this->_helper->getMediaUrl();
            $imageUrl .= 'catalog/category/';
            $imageUrl .= $wkImage;
            if ($wkImage && $wkImage!=="" && $wkImage!==null) {
                return $imageUrl;
            } elseif ($categoryImageUrl) {
                return $categoryImageUrl;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetDefaultCategoryImage used to get default image for category
     *
     * @return string || boolean
     */
    public function getDefaultCategoryImage()
    {
        $imageUrl = $this->_helper->getMediaUrl();
        $imageUrl .= 'agorae/category/slider-avatar.jpg';
        $imageCheck = getimagesize($imageUrl);
        if (count($imageCheck)>0
            && $imageCheck!==false
        ) {
            return $imageUrl;
        } else {
            return false;
        }
    }

    /**
     * GetTopSellingProducts used to get top selling product collection
     *
     * @return object
     */
    public function getTopSellingProducts()
    {
        try {
            $products = $this->_helper->getBestSellingProductCollection();
            if ($products && count($products)>0) {
                $productIds = implode(",", $products);
                if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
                    $marketplaceProduct = $this->_marketplaceProductsFactory->create()->getTable(
                        'marketplace_product'
                    );
                    $marketplaceUserdata = $this->_marketplaceProductsFactory->create()->getTable(
                        'marketplace_userdata'
                    );
                    $sellerProducts = $this->_salesList->getCollection()
                    ->addFieldToSelect('mageproduct_id')
                    ->addFieldToSelect('seller_id');
                    $sellerProducts->getSelect()
                    ->join(
                        ['mpro' => $marketplaceProduct],
                        'mpro.mageproduct_id = main_table.mageproduct_id',
                        ['status' => 'status']
                    )->where(
                        'mpro.mageproduct_id IN ('.$productIds.')
                        AND mpro.status = 1'
                    );
                    $sellerProducts->getSelect()
                    ->join(
                        ['ccp' => $marketplaceUserdata],
                        'ccp.seller_id = main_table.seller_id',
                        ['is_seller' => 'is_seller']
                    )->where(
                        'ccp.is_seller = 1'
                    );
                    $sellerProducts->getSelect()
                    ->columns('COUNT(*) as countProducts')
                    ->group('seller_id');
                    $productArray = $sellerProducts->getData();
                    return $productArray;
                }
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetProductImage used to get product image URL
     *
     * @param  object $pro       [contains product]
     * @param  string $imageType [contains type of product image]
     * @return string
     */
    public function getProductImage($pro, $imageType = 'product_small_image')
    {
        try {
            $product = $this->_helper->getProduct($pro->getId());

            $imageBlock =  $this->getLayout()->createBlock(
                \Magento\Catalog\Block\Product\ListProduct::class
            );
            $productImage = $imageBlock->getImage($product, $imageType);

            return $productImage->getImageUrl();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetAllSellerProduct used to get All seller Products ids
     *
     * @param  int $sellerId [contains seller ID]
     * @return array
     */
    public function getAllSellerProduct($sellerId)
    {
        $productIds = [];
        try {
            $collection = $this->_helper
            ->getSellerProductDataBySellerId($sellerId);
            if ($collection->getSize()) {
                foreach ($collection as $value) {
                    if ($value->getMageproductId()) {
                        $productIds[] = $value->getMageproductId();
                    }
                }
            }
            return $productIds;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * GetFavouriteSellerLink used to get link to add favourite seller
     *
     * @param  int $sellerId [contains seller Id]
     * @return string
     */
    public function getFavouriteSellerLink($sellerId)
    {
        try {
            $url = $this->getUrl(
                'agorae/favouriteseller/addfavouriteseller',
                [
                    'seller_id'=>$sellerId
                ]
            );
            return $url;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get Best Sale Sellers
     *
     * @return array
     */
    public function getBestSaleSellers()
    {
        try {
            if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
                $marketplaceUserdata = $this->_marketplaceProductsFactory->create()->getTable('marketplace_userdata');
                $catalogProductEntityInt = $this->_marketplaceProductsFactory->create()
                ->getTable('catalog_product_entity_int');
                $marketplaceProduct = $this->_marketplaceProductsFactory->create()->getTable('marketplace_product');
                $proAttId = $this->_attributes->getIdByCode('catalog_product', 'visibility');
                $sellersOrder = $this->_mpOrders->getCollection();
                $sellersOrder->getSelect()
                ->join(
                    ['ccp' => $marketplaceUserdata],
                    'ccp.seller_id = main_table.seller_id',
                    ['is_seller' => 'is_seller']
                )->where(
                    'main_table.invoice_id!=0 AND ccp.is_seller = 1'
                );
                $sellersOrder->getSelect()
                ->columns('COUNT(*) as countOrder')
                ->group('seller_id');
                $this->seller($sellersOrder);
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get seller
     *
     * @return boolean|int
     */
    public function seller($orders)
    {
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            foreach ($sellersOrder as $value) {
                if ($this->_marketplaceDataHelper->getSellerProCount($value['seller_id'])) {
                    $this->sellerArr[$value['seller_id']] = 0;
                    $sellerProducts = $this->_salesList->getCollection()
                    ->addFieldToSelect('mageproduct_id')
                    ->addFieldToSelect('magequantity')
                    ->addFieldToSelect('seller_id')
                    ->addFieldToSelect('cpprostatus');
    
                    $sellerProducts->getSelect()
                    ->join(
                        ['mpro' => $marketplaceProduct],
                        'mpro.mageproduct_id = main_table.mageproduct_id',
                        ['status' => 'status']
                    )->where(
                        'main_table.seller_id='.$value['seller_id'].'
                        AND main_table.cpprostatus=1
                        AND mpro.status = 1'
                    );
    
                    $sellerProducts->getSelect()
                    ->columns('SUM(magequantity) as countOrderedProduct')
                    ->group('mageproduct_id');
    
                    $sellerProducts->setOrder('countOrderedProduct', 'DESC');
    
                    if ($sellerProducts->count()>0) {
                        foreach ($sellerProducts as $sellerProductValue) {
                            if (isset($this->sellerArr[$value['seller_id']])) {
                                $this->sellerArr[$value['seller_id']] += $sellerProductValue['countOrderedProduct'];
                            } else {
                                $this->sellerArr[$value['seller_id']] = $sellerProductValue['countOrderedProduct'];
                            }
                        }
                    }
    
                }
            }
            $sellerId =  array_search(max($this->sellerArr), $this->sellerArr);
            if ($sellerId) {
                return $sellerId;
            } else {
                return false;
            }
        }
    }

    /**
     * Get module manager object
     *
     * @return object
     */
    public function getModuleManager()
    {
        return $this->moduleManager;
    }
}
