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

use Webkul\Agorae\Model\Sliderimages as Sliderimages;
use Magento\Framework\App\Filesystem\DirectoryList;
use Webkul\Agorae\Model\ResourceModel\Sliderimages\CollectionFactory as SliderImagesCollectionFactory;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollection;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Element\AbstractBlock;
use Magento\Framework\Filter\StripTags;

/**
 * Webkul Agorae Helper Data
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    const XML_PATH_EMAIL_PRODUCT_NOTIFY_CUSTOMERS = 'new_product_notify_follower_template';
    const XML_PATH_EMAIL_NOTIFY_CUSTOMERS = 'email_follower_template';

    /**
     * @var ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @var Session
     */
    protected $_customerSession;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Framework\Filesystem\Driver\File
     */
    protected $_file;

    /**
     * @var \Webkul\Agorae\Model\ResourceModel\Sliderimages\CollectionFactory
     */
    protected $_sliderimagesCollection;

    /**
     * @var \Magento\Customer\Model\Url
     */
    protected $_customerUrl;

    /**
     * @var \Magento\Catalog\Helper\Category
     */
    protected $category;

    /**
     * @var \Magento\Catalog\Model\CategoryRepository
     */
    protected $categoryRepository;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    protected $categoryCollection;

    /**
     * @var \Magento\Reports\Model\ResourceModel\Product\Sold\CollectionFactory
     */
    protected $bestSellCollection;

    /**
     * @var \Magento\Catalog\Model\Product\Attribute\Source\Status
     */
    protected $productStatus;

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    protected $productVisibility;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $productCollection;

    /**
     * @var \Magento\Customer\Model\Customer
     */
    protected $customerModel;

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

     /**
      * @var \Magento\Framework\Translate\Inline\StateInterface
      */
    protected $_inlineTranslation;

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var null|array
     */
    protected $_template;

    /**
     * @var \Magento\Framework\Filter\StripTags
     */
    protected $_stripTags;
    /**
     * @var \Magento\Framework\View\Design\Theme\ThemeProviderInterface
     */
    protected $_themeProvider;

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

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;

    /**
     * @var \Webkul\Agorae\Model\Sliderimages
     */
    protected $sliderImages;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $fileSystem;

    /**
     * @var \Magento\Catalog\Model\Category
     */
    protected $categoryFactory;

    /**
     * @var \Webkul\MpFavouriteSeller\Model\MpfavouritesellerRepository
     */
    protected $mpFavouriteSellerRepository;

    /**
     * @var \Webkul\Agorae\Model\MpfavouritesellerRepository
     */
    protected $agoraeFavouriteSellerRepository;

    /**
     * @var \Webkul\Marketplace\Model\SellerFactory
     */
    protected $mpSeller;

    /**
     * @var \Webkul\Marketplace\Model\Product
     */
    protected $mpProduct;

    /**
     * @var \Magento\Directory\Model\CountryFactory
     */
    protected $countryFactory;

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

    /**
     * @var \Magento\Framework\Module\Status
     */
    protected $moduleStatus;

    /**
     * @var \Magento\Config\Model\ResourceModel\Config
     */
    protected $config;
 
    /**
     * @param \Magento\Framework\App\Helper\Context                               $context
     * @param \Magento\Customer\Model\Customer                                    $customerModel
     * @param \Magento\Store\Model\StoreManagerInterface                          $storeManager
     * @param \Magento\Framework\Filesystem\Driver\File                           $file
     * @param SliderImagesCollectionFactory                                       $sliderimagesCollection
     * @param \Magento\Customer\Model\Url                                         $customerUrl
     * @param \Magento\Catalog\Helper\Category                                    $category
     * @param \Magento\Catalog\Model\CategoryRepository                           $categoryRepository
     * @param CategoryCollection                                                  $categoryCollection
     * @param \Magento\Reports\Model\ResourceModel\Product\Sold\CollectionFactory $bestSellCollection
     * @param \Magento\Catalog\Model\Product\Attribute\Source\Status              $productStatus
     * @param \Magento\Catalog\Model\Product\Visibility                           $productVisibility
     * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory      $productCollection
     * @param \Magento\Framework\Translate\Inline\StateInterface                  $inlineTranslation
     * @param \Magento\Framework\Mail\Template\TransportBuilder                   $transportBuilder
     * @param StripTags                                                           $stripTags
     * @param \Magento\Framework\Module\Manager                                   $moduleManager
     * @param \Magento\Catalog\Model\ProductFactory                               $productFactory
     * @param \Webkul\Agorae\Model\Sliderimages                                   $sliderImages
     * @param \Magento\Framework\Filesystem                                       $fileSystem
     * @param \Magento\Catalog\Model\Category                                     $categoryFactory
     * @param \Webkul\Agorae\Model\MpfavouritesellerRepository                    $agoraeFavouriteSellerRepository
     * @param \Magento\Directory\Model\CountryFactory                             $countryFactory
     * @param \Magento\Framework\Module\Status                                    $moduleStatus
     * @param \Magento\Config\Model\ResourceModel\Config                          $config
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context                                     $context,
        \Magento\Customer\Model\Customer                                          $customerModel,
        \Magento\Store\Model\StoreManagerInterface                                $storeManager,
        \Magento\Framework\Filesystem\Driver\File                                 $file,
        SliderImagesCollectionFactory                                             $sliderimagesCollection,
        \Magento\Customer\Model\Url                                               $customerUrl,
        \Magento\Catalog\Helper\Category                                          $category,
        \Magento\Catalog\Model\CategoryRepository                                 $categoryRepository,
        CategoryCollection                                                        $categoryCollection,
        \Magento\Reports\Model\ResourceModel\Product\Sold\CollectionFactory       $bestSellCollection,
        \Magento\Catalog\Model\Product\Attribute\Source\Status                    $productStatus,
        \Magento\Catalog\Model\Product\Visibility                                 $productVisibility,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory            $productCollection,
        \Magento\Framework\Translate\Inline\StateInterface                        $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder                         $transportBuilder,
        \Magento\Customer\Model\SessionFactory                                    $sessionFactory,
        \Magento\Framework\View\Design\Theme\ThemeProviderInterface               $themeProvider,
        StripTags                                                                 $stripTags,
        \Magento\Framework\Module\Manager                                         $moduleManager,
        \Magento\Catalog\Model\ProductFactory                                     $productFactory,
        \Webkul\Agorae\Model\Sliderimages                                         $sliderImages,
        \Magento\Framework\Filesystem                                             $fileSystem,
        \Magento\Catalog\Model\Category                                           $categoryFactory,
        \Webkul\Agorae\Model\MpfavouritesellerRepository                          $agoraeFavouriteSellerRepository,
        \Magento\Directory\Model\CountryFactory                                   $countryFactory,
        \Magento\Framework\Module\Status                                          $moduleStatus,
        \Magento\Config\Model\ResourceModel\Config                                $config
    ) {
        $this->_objectManager                  = \Magento\Framework\App\ObjectManager::getInstance();
        $this->_themeProvider                  = $themeProvider;
        $this->_customerSession                = $sessionFactory->create();
        $this->customerModel                   = $customerModel;
        $this->_storeManager                   = $storeManager;
        $this->_file                           = $file;
        $this->_sliderimagesCollection         = $sliderimagesCollection;
        $this->_customerUrl                    = $customerUrl;
        $this->category                        = $category;
        $this->categoryRepository              = $categoryRepository;
        $this->categoryCollection              = $categoryCollection;
        $this->bestSellCollection              = $bestSellCollection;
        $this->productStatus                   = $productStatus;
        $this->productVisibility               = $productVisibility;
        $this->productCollection               = $productCollection;
        $this->_inlineTranslation              = $inlineTranslation;
        $this->_transportBuilder               = $transportBuilder;
        $this->_stripTags                      = $stripTags;
        $this->productFactory                  = $productFactory;
        $this->moduleManager                   = $moduleManager;
        $this->sliderImages                    = $sliderImages;
        $this->categoryFactory                 = $categoryFactory;
        $this->fileSystem                      = $fileSystem;
        $this->agoraeFavouriteSellerRepository = $agoraeFavouriteSellerRepository;
        $this->countryFactory                  = $countryFactory;
        $this->moduleStatus                    = $moduleStatus;
        $this->config                          = $config;
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $this->mpSeller = $this->_objectManager->create(\Webkul\Marketplace\Model\Seller::class);
            $this->_mpHelper = $this->_objectManager->create(\Webkul\Marketplace\Helper\Data::class);
            //$this->mpHelper = $this->_objectManager->create(\Webkul\Marketplace\Helper\Data::class);
            $this->mpProduct = $this->_objectManager->create(\Webkul\Marketplace\Model\Product::class);
            $this->mpOrders = $this->_objectManager->create(\Webkul\Marketplace\Model\Orders::class);
        }
        if ($this->moduleManager->isOutputEnabled('Webkul_MpFavouriteSeller')) {
            $this->mpFavouriteSellerRepository = $this->_objectManager->create(
                \Webkul\MpFavouriteSeller\Model\MpfavouritesellerRepository::class
            );
        }
        parent::__construct($context);
    }
    
    /**
     * GetAgoraeThemeRTLConfig get system configuration for theme rtl setting
     *
     * @return string
     */
    public function getThemeData()
    {
        $themeId = $this->scopeConfig->getValue(
            \Magento\Framework\View\DesignInterface::XML_PATH_THEME_ID,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $this->_storeManager->getStore()->getId()
        );
        /** @var $theme \Magento\Framework\View\Design\ThemeInterface */
        $theme = $this->_themeProvider->getThemeById($themeId);
        return $theme->getData();
    }

    /**
     * GetAgoraeThemeRTLConfig get system configuration for theme rtl setting
     *
     * @return string
     */
    public function getAgoraeThemeRTLConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/rtl_settings/rtl_enable',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetRootCategoryIdByStoreId
     *
     * @param  string $storeId [contains store id]
     * @return int
     */
    public function getRootCategoryIdByStoreId($storeId = '')
    {
        return $this->_storeManager->getStore($storeId)->getRootCategoryId();
    }

    /**
     * GetCurrentStoreId
     *
     * @return id
     */
    public function getCurrentStoreId()
    {
        // give the current store id
        return $this->_storeManager->getStore()->getStoreId();
    }

    /**
     * GetAgoraeThemeColorConfig get system configuration for theme background color
     *
     * @return string
     */
    public function getAgoraeThemeColorConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/color_settings/bg_color',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetAgoraeTopHeaderTextColorConfig system config for theme header text color
     *
     * @return string
     */
    public function getAgoraeTopHeaderTextColorConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/color_settings/top_header_text_color',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetTopTwoCategories system config top two categories selected
     *
     * @return array
     */
    public function getTopTwoCategories()
    {
        return $this->scopeConfig->getValue(
            'agorae/category_settings/top_category',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetStoreCategories all store categories
     *
     * @return object
     */
    public function getStoreCategories()
    {
        return $this->category->getStoreCategories();
    }

    /**
     * GetCategory get category data by id
     *
     * @param  int $id category Id
     * @return object
     */
    public function getCategory($id)
    {
        return $this->categoryRepository->get($id);
    }

    /**
     * GetProduct get product data by Id
     *
     * @param  int $id product Id
     * @return object
     */
    public function getProduct($id)
    {
        $product = $this->productFactory->create();
        return $product->load($id);
    }

    /**
     * GetCategoryCollection get categories collection
     *
     * @return object
     */
    public function getCategoryCollection()
    {
        return $this->categoryCollection->create();
    }

    /**
     * GetBestSellingProductCollection used to get best selling products
     *
     * @return object
     */
    public function getBestSellingProductCollection()
    {
        $storeId = $this->getCurrentStoreId();
        $collection = $this->bestSellCollection->create()
        ->addOrderedQty()
        ->setOrder('ordered_qty', 'desc');
        $bestSellProductIds = $collection->getColumnValues('order_items_product_id');
        $products = $this->productCollection->create()
        ->addFieldToFilter(
            'entity_id',
            ['in'=>$bestSellProductIds]
        )->addStoreFilter()
        ->addAttributeToFilter(
            'status',
            ['in' => $this->productStatus->getVisibleStatusIds()]
        )->addAttributeToFilter(
            'visibility',
            ['in' => $this->productVisibility->getVisibleInSiteIds()]
        )->setPageSize(4)->setCurPage(1);
        $productIds = $products->getColumnValues('entity_id');
        return $productIds;
    }

    /**
     * GetTopTwoLevelCategories used to get top two level categories
     *
     * @return array
     */
    public function getTopTwoLevelCategories()
    {
        $options = [];
        $currentStoreId = $this->getCurrentStoreId();
        $rootCategoryId = $this->getRootCategoryIdByStoreId($currentStoreId);
        $collection = $this->getCategoryCollection();
        $collection->addAttributeToSelect('*')
            ->addIsActiveFilter(true)
            ->addLevelFilter(2);
        $categories = $this->getStoreCategories();
        foreach ($collection as $category) {
            $categoryObj = $this->getCategory($category->getId());
            $subcategories = $categoryObj->getChildrenCategories();
            if ($category->getLevel()==2 && count($subcategories)>=1) {
                $flag = false;
                foreach ($subcategories as $subcategorie) {
                    $thirdCategoryObj = $this->getCategory(
                        $subcategorie->getId()
                    );
                    $thirdSubcategories = $thirdCategoryObj->getChildrenCategories();
                    if (count($thirdSubcategories)>=1 && $category->getIsActive()) {
                        $flag = true;
                        break;
                    } else {
                        $flag = false;
                    }
                }
                if ($flag) {
                    $options[] = [
                        'label' => $category->getName(),
                        'value' => $category->getId()
                    ];
                }
            }
        }
        return $options;
    }

    /**
     * GetAllowedExtensions used to get allowed extension for image
     *
     * @param  boolean $flag
     * @return array
     */
    public function getAllowedExtensions($flag)
    {
        if ($flag) {
            return ['\'gif\'','\'png\'','\'jpg\'','\'jpeg\''];
        } else {
            return ['gif','png','jpg','jpeg'];
        }
    }

    /**
     * GetSliderImagePath get upload path for agorae slider images
     *
     * @return string
     */
    public function getSliderImagePath()
    {
        return 'agorae/slider/images/';
    }

    /**
     * GetSliderimagesModel
     *
     * @return object
     */
    public function getSliderimagesModel()
    {
        return $this->sliderImages;
    }

    /**
     * GetSliderImagesCollection
     *
     * @return object
     */
    public function getSliderImagesCollection()
    {
        return $this->_sliderimagesCollection->create()
        ->addFieldToFilter('status', ['neq'=>0])
        ->setOrder('sort_order', 'ASC');
    }

    /**
     * GetFileDriver
     *
     * @return object
     */
    public function getFileDriver()
    {
        return $this->_file;
    }

    /**
     * DeleteUploadedFile deletes uploaded file
     *
     * @param  boolean $delete
     * @param  string $data
     * @return void
     */
    public function deleteUploadedFile($delete, $data)
    {
        if ($delete) {
            $file = $this->getFileDriver();
            $mediaPath = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
            $deletePath = $mediaPath.$data;
            if ($file->isExists($deletePath)) {
                $file->deleteFile($deletePath);
            }
        }
    }

    /**
     * DeleteDirectories
     *
     * @param  string $path
     * @return void
     */
    public function deleteDirectories($path)
    {
        $this->_file->deleteDirectory($path);
    }

    /**
     * GetBaseUrl
     *
     * @return string
     */
    public function getBaseUrl()
    {
        return $this->_storeManager->getStore()->getBaseUrl();
    }

    /**
     * GetAgoraeFooterBlogLink used to get footer blog link from system config
     *
     * @return string
     */
    public function getAgoraeFooterBlogLink()
    {
        $blogLink = $this->scopeConfig->getValue(
            'agorae/agorae_footer_settings/agorae_blog',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        if ($blogLink && $blogLink!=="") {
            return $blogLink;
        } else {
            return $this->getBaseUrl();
        }
    }

    /**
     * GetAgoraeFooterTwitterLink used to get footer twitter link from system config
     *
     * @return string
     */
    public function getAgoraeFooterTwitterLink()
    {
        $link = "//twitter.com/";
        $link .= $this->scopeConfig->getValue(
            'agorae/agorae_footer_settings/agorae_twitter',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        return $link;
    }

    /**
     * GetAgoraeFooterFacebookLink used to get footer facebook link from system config
     *
     * @return string
     */
    public function getAgoraeFooterFacebookLink()
    {
        $link = "//www.facebook.com/";
        $link .= $this->scopeConfig->getValue(
            'agorae/agorae_footer_settings/agorae_facebook',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        return $link;
    }

    /**
     * GetAgoraeFooterGoogleLink used to get footer google link from system config
     *
     * @return string
     */
    public function getAgoraeFooterGoogleLink()
    {
        $link = "//plus.google.com/";
        $link .= $this->scopeConfig->getValue(
            'agorae/agorae_footer_settings/agorae_google',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        return $link;
    }

    /**
     * GetAgoraeFooterRssLink used to get footer RSS link from system config
     *
     * @return string
     */
    public function getAgoraeFooterRssLink()
    {
        $link = $this->scopeConfig->getValue(
            'agorae/agorae_footer_settings/agorae_rss',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        if ($link && $link!=="") {
            return $link;
        } else {
            return $this->getBaseUrl();
        }
    }

    /**
     * GetAdminOriginCountry used to get admin country origin
     *
     * @return string
     */
    public function getAdminOriginCountry()
    {
        return $this->scopeConfig->getValue(
            'shipping/origin/country_id',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * IsFeaturedProductCarousalEnable is featured product carousal enable or not from system config
     *
     * @return boolean
     */
    public function isFeaturedProductCarousalEnable()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/featured_product_enable',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetFeaturedProductCarousalSortOrder get featured product carousal sort order from system config
     *
     * @return int
     */
    public function getFeaturedProductCarousalSortOrder()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/sort_featured_product',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * IsNewProductCarousalEnable is new product carousal enable or not from system config
     *
     * @return boolean
     */
    public function isNewProductCarousalEnable()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/new_product_enable',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetNewProductCarousalSortOrder get new product carousal sort order from system config
     *
     * @return int
     */
    public function getNewProductCarousalSortOrder()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/sort_new_product',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetNumberOfProductsForNewProductCarousal get number of products shown
     * in new productcarousal sort order from system config
     *
     * @return int
     */
    public function getNumberOfProductsForNewProductCarousal()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/limit_new_product',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetSellerProductTopHeadingHomepage get seller product top heading for homepage from system config
     *
     * @return string
     */
    public function getSellerProductTopHeadingHomepage()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/seller_product_top',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetSellerProductContentHomepage get seller product content for homepage from system config
     *
     * @return string
     */
    public function getSellerProductContentHomepage()
    {
        return $this->scopeConfig->getValue(
            'agorae/agorae_carousal_settings/seller_product_content',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetSaleProductImageConfig get sale product image label from system config
     *
     * @return string
     */
    public function getSaleProductImageConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/product_image_settings/sale',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetNewProductImageConfig get new product image label from system config
     *
     * @return string
     */
    public function getNewProductImageConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/product_image_settings/latest',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetDiscountProductImageConfig get discount product image label from system config
     *
     * @return string
     */
    public function getDiscountProductImageConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/product_image_settings/discount',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetEditorPickProductImageConfig get editor pick product image label from system config
     *
     * @return string
     */
    public function getEditorPickProductImageConfig()
    {
        return $this->scopeConfig->getValue(
            'agorae/product_image_settings/pick',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * GetCategoryImage get category Image URL by Id
     *
     * @param  int $id category Id
     * @return int | string
     */
    public function getCategoryImage($id)
    {
        $categoryCollection = $this->categoryFactory->create();
        $category = $categoryCollection->load($id);
        if (isset($category['image'])) {
            return $category->getImageUrl();
        } else {
            return 0;
        }
    }

    /**
     * GetMediaUrl
     *
     * @return string
     */
    public function getMediaUrl()
    {
        return $this->_storeManager->getStore()->getBaseUrl(
            \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
        );
    }

    /**
     * IsModuleEnabled checks a given module is enabled or not
     *
     * @param  string  $moduleName
     * @return boolean
     */
    public function isModuleEnabled($moduleName)
    {
        return $this->_moduleManager->isEnabled($moduleName);
    }

    /**
     * IsOutputEnabled checks a given module is enabled or not
     *
     * @param  string  $moduleName
     * @return boolean
     */
    public function isOutputEnabled($moduleName)
    {
        return $this->_moduleManager->isOutputEnabled($moduleName);
    }

    /**
     * CheckCustomerLoggedIn used to check current customer session is logged in or not
     *
     * @return boolean
     */
    public function checkCustomerLoggedIn()
    {
        if ($this->_customerSession->isLoggedIn()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * GetLoggedInCustomer get customer data for logged in customer
     *
     * @return object
     */
    public function getLoggedInCustomer()
    {
        $customerId = $this->_customerSession->getId();
        $customer = $this->getCustomerData($customerId);
        return $customer;
    }

    /**
     * GetCustomerLoginUrl
     *
     * @return string
     */
    public function getCustomerLoginUrl()
    {
        return $this->_customerUrl->getLoginUrl();
    }

    /**
     * GetCustomerRegisterUrl
     *
     * @return string
     */
    public function getCustomerRegisterUrl()
    {
        return $this->_customerUrl->getRegisterUrl();
    }

    /**
     * GetCustomerLogoutUrl
     *
     * @return string
     */
    public function getCustomerLogoutUrl()
    {
        return $this->_customerUrl->getLogoutUrl();
    }

    /**
     * GetCustomerData get customer data by Id
     *
     * @param  int $id customer Id
     * @return object
     */
    public function getCustomerData($id)
    {
        return $this->customerModel->load($id);
    }

    /**
     * GetFollowersCount used to get count of favourite sellers
     *
     * @param  int $sellerId seller Id
     * @return int
     */
    public function getFollowersCount($sellerId)
    {
        return $this->getFollowersData($sellerId)->getSize();
    }

    /**
     * GetFollowersData used to get customers who have added sellers to his/her favourite seller list
     *
     * @param  int $sellerId seller Id
     * @return object
     */
    public function getFollowersData($sellerId)
    {
        $favouriteSellerModuleEnabled = $this->isModuleEnabled('Webkul_MpFavouriteSeller');
        $favouriteSellerOutputEnabled = $this->isOutputEnabled('Webkul_MpFavouriteSeller');
        if ($favouriteSellerModuleEnabled && $favouriteSellerOutputEnabled) {
            $collection = $this->mpFavouriteSellerRepository->getCustomersCollectionBySellerId($sellerId);
            return $collection;
        } else {
            $collection = $this->agoraeFavouriteSellerRepository->getCustomersCollectionBySellerId($sellerId);
            return $collection;
        }
    }

    /**
     * GetSellersAsFollowers used to get those sellers which are also followers of other sellers
     *
     * @param  array $customerIds contains customer Ids
     * @return object
     */
    public function getSellersAsFollowers($customerIds)
    {
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $model = $this->mpSeller->getCollection()
            ->addFieldToFilter(
                'seller_id',
                ['in'=>$customerIds]
            );
            return $model;
        }
    }

    /**
     * CheckIsSeller checks if customer is seller or not
     *
     * @return int
     */
    public function checkIsSeller()
    {
        return $this->_mpHelper->isSeller();
    }

    /**
     * [notifyFollowers description]
     *
     * @param  [type] $emailTemplateVariables [description]
     * @param  [type] $senderInfo             [description]
     * @param  [type] $receiverInfo           [description]
     * @return [type]                         [description]
     */
    public function notifyFollowers($emailTemplateVariables, $senderInfo, $receiverInfo)
    {
        $this->_template = self::XML_PATH_EMAIL_NOTIFY_CUSTOMERS;
        $this->_inlineTranslation->suspend();
        $this->generateTemplate($emailTemplateVariables, $senderInfo, $receiverInfo);
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();
        $this->_inlineTranslation->resume();
    }

    /**
     * [followersNotifyProductApprove description]
     *
     * @param  Mixed $emailTemplateVariables
     * @param  Mixed $senderInfo
     * @param  Mixed $receiverInfo
     */
    public function followersNotifyProductApprove($emailTemplateVariables, $senderInfo, $receiverInfo)
    {
        $this->_template = self::XML_PATH_EMAIL_PRODUCT_NOTIFY_CUSTOMERS;
        $this->_inlineTranslation->suspend();
        $this->generateTemplate($emailTemplateVariables, $senderInfo, $receiverInfo);
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();
        $this->_inlineTranslation->resume();
    }

    /**
     * GenerateTemplate description
     *
     * @param Mixed $emailTemplateVariables
     * @param Mixed $senderInfo
     * @param Mixed $receiverInfo
     */
    public function generateTemplate($emailTemplateVariables, $senderInfo, $receiverInfo)
    {
        $template = $this->_transportBuilder
            ->setTemplateIdentifier($this->_template)
            ->setTemplateOptions(
                [
                    'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                    'store' => $this->_storeManager->getStore()->getId(),
                ]
            )
            ->setTemplateVars($emailTemplateVariables)
            ->setFrom($senderInfo)
            ->addTo($receiverInfo['email'], $receiverInfo['name']);

        return $this;
    }

    /**
     * GetSellerProductDataBySellerId used to get seller product Data by giving seller Id
     *
     * @param  int $sellerId seller Id
     * @return object
     */
    public function getSellerProductDataBySellerId($sellerId)
    {
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $model = $this->mpProduct->getCollection()
            ->addFieldToFilter(
                'seller_id',
                $sellerId
            );
            return $model;
        }
    }

    /**
     * StripTags used to strip a string from HTML, XML, and PHP tags
     *
     * @param  string $value
     * @return string
     */
    public function stripTags($value)
    {
        return $this->_stripTags->filter($value);
    }

    /**
     * GetSellerIdByProductId used to get seller Id from Product Id
     *
     * @param  int $productId product Id
     * @return int returns Seller Id
     */
    public function getSellerIdByProductId($productId)
    { //echo $productId; die(" id");
        $sellerId = 0;
        $collection = $this->_mpHelper
            ->getSellerProductDataByProductId($productId);
        if ($collection->getSize()) {
            foreach ($collection as $value) {
                if ($value->getSellerId()) {
                    $sellerId = $value->getSellerId();
                }
            }
        }
        return $sellerId;
    }

    /**
     * GetFeaturedProductsList used to get featured products
     *
     * @return object
     */
    public function getFeaturedProductsList()
    {
        $model = $this->productCollection->create()
        ->addAttributeToSelect('*')
        ->addStoreFilter()
        ->addAttributeToFilter(
            'status',
            ['in' => $this->productStatus->getVisibleStatusIds()]
        )->addAttributeToFilter(
            'visibility',
            ['in' => $this->productVisibility->getVisibleInSiteIds()]
        )->addFieldToFilter(
            'is_featured_agorae',
            1
        );
        return $model;
    }

    /**
     * GetLatestProductsList used to get latest products with a limit
     *
     * @return object
     */
    public function getLatestProductsList()
    {
        $limitOfNewProducts = $this->getNumberOfProductsForNewProductCarousal();
        if ($limitOfNewProducts && $limitOfNewProducts < 10) {
            $limitOfNewProducts = 10;
        }

        $model = $this->productCollection->create()
        ->addAttributeToSelect('*')
        ->addStoreFilter()
        ->addAttributeToFilter(
            'status',
            ['in' => $this->productStatus->getVisibleStatusIds()]
        )->addAttributeToFilter(
            'visibility',
            ['in' => $this->productVisibility->getVisibleInSiteIds()]
        )->setPageSize($limitOfNewProducts)
        ->setOrder('entity_id', 'DESC');

        return $model;
    }

    /**
     * GetAgoraeImageCustomLabel used to get image custom labels html
     *
     * @return array
     */
    public function getAgoraeImageCustomLabel()
    {
        $customLabels                 = [];
        $editorPickImageConfig        = $this->getEditorPickProductImageConfig();
        $saleProductImageConfig       = $this->getSaleProductImageConfig();
        $newProductImageConfig        = $this->getNewProductImageConfig();
        $discountProductImageConfig   = $this->getDiscountProductImageConfig();
        if ($editorPickImageConfig) {
            $customLabels['editorpick'] = '<img src="'.$this->getMediaUrl()
                .'agorae/product/pick/'
                .$editorPickImageConfig
                .'" class="soldoutimgcss">';
        }
        if ($saleProductImageConfig) {
            $customLabels['sale'] = '<img src="'
                .$this->getMediaUrl()
                .'agorae/product/sale/'
                .$saleProductImageConfig
                .'" class="soldoutimgcss">';
        }
        if ($newProductImageConfig) {
            $customLabels['new'] = '<img src="'
                .$this->getMediaUrl()
                .'agorae/product/latest/'
                .$newProductImageConfig
                .'" class="soldoutimgcss">';
        }
        if ($discountProductImageConfig) {
            $customLabels['discount'] = '<img src="'.$this->getMediaUrl()
                .'agorae/product/discount/'
                .$discountProductImageConfig
                .'" class="soldoutimgcss">';
        }

        return $customLabels;
    }

    /**
     * GetSellerBlockHtml used to get seller block HTML which is shown below a product
     *
     * @param  object  $product      contains Product
     * @param  object  $block        contains block reference
     * @param  boolean  $templateType
     * @param  boolean $flag
     * @return string
     */
    public function getSellerBlockHtml($product, $block, $templateType, $flag = true)
    {
        $html = '';
        $shopTitle = '';
        $marketplaceModuleEnabled = $this->isModuleEnabled('Webkul_Marketplace');
        $marketplaceModuleOutputEnabled = $this->isOutputEnabled('Webkul_Marketplace');
        $sellerBlock = $block->getLayout()->createBlock(
            \Webkul\Agorae\Block\Sellerblock::class
        );
        $sellerData = $sellerBlock->getSellerDetailsByProductId($product->getId());
        if ($sellerData && $marketplaceModuleEnabled && $marketplaceModuleOutputEnabled) {
            $ratings = $this->_mpHelper->getSelleRating($sellerData->getSellerId());
            $ratingdata = $this->_mpHelper->getFeedTotal($sellerData->getSellerId());
            if (!$ratingdata
                || !$ratingdata['feedcount']
                || $ratingdata==0
            ) {
                $ratingdata = [];
                $ratingdata['feedcount'] = 0;
            }
            if ($sellerData->getLogoPic()) {
                $logoPic = $sellerData->getLogoPic();
            } else {
                $logoPic = 'noimage.png';
            }

            if ($sellerData->getShopTitle()) {
                $shopTitle = substr($sellerData->getShopTitle(), 0, 20);
                if (strlen($sellerData->getShopTitle()) > 20) {
                    $shopTitle .= " ...";
                }
            } else {
                $shopTitle = substr(
                    $this->getCustomerData(
                        $sellerData->getSellerId()
                    )->getName().__("'s shop"),
                    0,
                    20
                );
                if (strlen($this->getCustomerData($sellerData->getSellerId())->getName().__("'s shop")) > 20) {
                    $shopTitle .= " ...";
                }
            }

            if ($sellerData->getCountryPic()) {
                $sellerCountry = $this->getCountry($sellerData->getCountryPic());
            } else {
                $sellerCountry = "";
            }

            $html.= '<div class ="seller-info">';
            $html.= '<div class="sd-left">
                        <a href="'
                        .$this->_mpHelper->getRewriteUrl(
                            'marketplace/seller/collection/shop/'
                            .$sellerData->getShopUrl()
                        ).'">
                            <div class="sellerlogo">
                                <img src="'.$this->getMediaUrl().'avatar/'.$logoPic.'" />
                            </div>
                        </a>
                    </div>';
            $html.= '<div class="sd-right">';
            $html.= '<div class="shoptitle">
                        <a href="'.$this->_mpHelper->getRewriteUrl(
                'marketplace/seller/collection/shop/'
                .$sellerData->getShopUrl()
            ).'"
                            title="'.$sellerData->getShopTitle().'">'
                            .$shopTitle.
                        '</a>
                    </div>';
            if ($sellerCountry) {
                $html .= '<div class="sellercountry">
                            <i> '.__("from ").' </i>
                            <span>'
                                .$sellerCountry.'
                            </span>
                        </div>';
            }
            $html .= '<div class="ratings">
                        <div class="rating-box">
                            <div style="width:'.(($ratings*100)/5).'%"
                                class="rating">
                            </div>
                        </div>'.
                        '<span class="total-ratings">('.$ratings.'/5)</span>'.
                        '<p class="rating-links">
                            <a href="'.$this->_mpHelper->getRewriteUrl('marketplace/seller/feedback/shop/'
                                .$sellerData->getShopUrl()) .'">'
                                .__("%1 Reviews", $ratingdata['feedcount']).'
                            </a>
                        </p>
                    </div>
                </div>
            </div>';
        } else {
            if ($this->getAdminOriginCountry()) {
                $adminCountry = $this->getCountry($this->getAdminOriginCountry());
            } else {
                $adminCountry = "";
            }
            $html.= '<div class ="seller-info">
                        <div class="sd-left">
                            <a href="#">
                                <div class="sellerlogo">
                                    <img src="'.$this->getMediaUrl()
                                            .'avatar/'
                                            .'noimage.png'. '" />
                                </div>
                            </a>
                        </div>
                        <div class="sd-right">
                            <div class="shoptitle">
                                <a href="#"
                                    title="'. __('Admin Product').'">
                                    '.__('Admin Product').'
                                </a>
                            </div>';
            if ($adminCountry) {
                $html .= '<div class="sellercountry">
                            <i>' .__('from ').'</i>
                            <span>
                                '.$adminCountry.'
                            </span>
                        </div>';
            }
            $html .= $block->getReviewsSummaryHtml($product, $templateType, $flag).'
                    </div>
                </div>';
        }
        return $html;
    }

    /**
     * GetCountry used to get Full Country name
     *
     * @param  string $countryCode contains country code, i.e., US
     * @return string
     */
    public function getCountry($countryCode)
    {
        if ($countryCode) {
            $data = $this->countryFactory->create()->setId(
                $countryCode
            );
            if ($data) {
                return $data->getName();
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    /**
     * GetSellerOrdersCount used to count all orders of a seller
     *
     * @param  int $sellerId seller Id
     * @return int
     */
    public function getSellerOrdersCount($sellerId)
    {
        if ($this->moduleManager->isOutputEnabled('Webkul_Marketplace')) {
            $model = $this->mpOrders->getCollection()
            ->addFieldToFilter(
                'seller_id',
                $sellerId
            );
            return $model->getSize();
        }
    }

    /**
     * GetModifiedArrayOfVariablesForLess used to get modified variables for less
     *
     * @return array
     */
    public function getModifiedArrayOfVariablesForLess()
    {
        $array = [];
        $array['themeColor'] = $this->getAgoraeThemeColorConfig();
        $array['color'] = $this->getAgoraeTopHeaderTextColorConfig();
        $array['color-color-lighter'] = 'lighten('.$this->getAgoraeTopHeaderTextColorConfig().', 20%)';
        $array['themeColor-color-lighter'] = 'lighten('.$this->getAgoraeThemeColorConfig().', 35%)';
        $array['themeColor-color-lighter-20'] = 'lighten('.$this->getAgoraeThemeColorConfig().', 20%)';
        return $array;
    }

    /**
     * GetAgoraeCustomProductAttributes used to get agorae product custom attributes
     *
     * @return array
     */
    public function getAgoraeCustomProductAttributes()
    {
        $attributesCode = [];
        $attributesCode['admin'][] = 'is_featured_agorae';
        $attributesCode['seller'][] = 'is_seller_pick';
        $attributesCode['seller'][] = 'image_custom_label';

        return $attributesCode;
    }

    /**
     * DisableModule disabled the module
     *
     * @param  string $module contains module name
     * @return void
     */
    public function disableModule($module)
    {
        $status = $this->moduleStatus;
        $status->setIsEnabled(false, [$module]);
        $outputPath = "advanced/modules_disable_output/$module";
        $config = $this->config;
        $config->saveConfig($outputPath, true, 'default', 0);
    }
}
