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

use Magento\Checkout\Model\ConfigProviderInterface;
use Webkul\MpPayPal\Gateway\Config\Config;
use Magento\Framework\Locale\ResolverInterface;

class ConfigProvider implements ConfigProviderInterface
{
    const CODE = 'mppaypal';

    /**
     * @var Config
     */
    private $config;

    /**
     * @var Magento\Store\Api\Data\StoreInterface
     */
    protected $store;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;

    /**
     * Constructor
     *
     * @param Config $config
     * @param PayPalConfig $payPalConfig No longer used by internal code and not recommended.
     * @param \Webkul\MpPayPal\Model\PayPal\Adapter $adapter
     * @param ResolverInterface $localeResolver No longer used by internal code and not recommended.
     */
    public function __construct(
        Config $config,
        ResolverInterface $localeResolver,
        \Magento\Store\Api\Data\StoreInterface $store,
        \Magento\Framework\UrlInterface $urlInterface,
        \Webkul\MpPayPal\Helper\Data $helper,
        \Webkul\Marketplace\Helper\Data $mpHelper,
        \Webkul\Marketplace\Model\ProductFactory $mpProductFactory,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Webkul\MpPayPal\Model\PayPal\Adapter $adapter,
        \Magento\Framework\Encryption\EncryptorInterface $encryptor,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->config = $config;
        $this->store = $store;
        $this->urlInterface = $urlInterface;
        $this->customerSession = $customerSession;
        $this->mpProductFactory = $mpProductFactory;
        $this->helper = $helper;
        $this->mpHelper = $mpHelper;
        $this->jsonHelper = $jsonHelper;
        $this->adapter = $adapter;
        $this->_encryptor = $encryptor;
        $this->checkoutSession = $checkoutSession;
    }

    /**
     * Retrieve assoc array of checkout configuration
     *
     * @return array
     */
    public function getConfig()
    {
        $unbranded = (int)$this->config->getUnbrandedEnable();
        $sellersData = $this->getSellersData();
        $isActive = false;
        $clientId = $this->_encryptor->decrypt($this->config->getClientId());
        $clientToken = $this->adapter->generateClientToken();
        if ($this->config->isActive($this->store->getId())) {
            $isActive = ($clientToken && $clientId)?true:false;
        }
        return [
            'payment' => [
                self::CODE => [
                    'isActive' => $isActive,
                    'environment' => $this->config->getEnvironment(),
                    'locale' => strtolower($this->store->getLocaleCode()),
                    'createOrderUrl' => $this->urlInterface->getUrl('mppaypal/seller/createorder'),
                    'captureOrderUrl' => $this->urlInterface->getUrl('mppaypal/seller/captureorder'),
                    'isSellerInCart' => $this->helper->checkSellerInCart(),
                    'client_id' => $clientId,
                    'client_token' => $clientToken,
                    'enable_default' => (int) $this->config->getEnableDefault(),
                    'unbranded' => $unbranded,
                    'branded' => false,
                    'unbrandedScriptUrl' => 'https://www.paypal.com/sdk/js?components=hosted-fields',
                    'buttonImg' => 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/checkout-logo-medium.png',
                    'sellersData' => $sellersData,
                    'purchaseUnitLimitReached' => (count($sellersData) > 10)?true:false
                ]
            ]
        ];
    }

    public function getSellersData()
    {
        $quote = $this->checkoutSession->getQuote();
        $quoteItems = $quote->getAllVisibleItems();
        $data = [];
        foreach ($quoteItems as $item) {
            $itemId = $item->getProductId();
            $sellerId = 0;
            /**
             * $assignSellerId variable to store assign seller id.
             *
             * @var int
             */
            $assignSellerId = $this->helper->getAssignSellerId($item);

            $seller = $this->mpProductFactory->create()->getCollection();

            /*
             * check if assign seller id exists then add filter for seller id else product id
             */
            if ($assignSellerId) {
                $sellerId = $assignSellerId;
            } else {
                $seller->addFieldToFilter('mageproduct_id', $itemId);
                if ($seller->getSize() > 0) {
                    foreach ($seller as $obj) {
                        $sellerId = $obj->getSellerId();
                    }
                }
            }
            if ($sellerId) {
                $sellerStatus = $this->getSellerPayPalStatus($sellerId);
                $sellerInfo = $this->mpHelper->getSellerInfo($sellerId);
                $sellerProData = [];
                $sellerProData['seller_id'] = $sellerId;
                $sellerProData['seller_status'] = (boolean) $sellerStatus;
                $sellerProData['seller_name'] = $sellerInfo['shop_title']??$sellerInfo['shop_url'];
                $sellerProData['product_id'] = $itemId;
                $sellerProData['product_name'] = $item->getProduct()->getName();
            } else {
                $sellerProData = [];
                $sellerProData['seller_name'] = 0;
                $sellerProData['seller_status'] = false;
                $sellerProData['seller_name'] = 'Admin';
                $sellerProData['product_id'] = $itemId;
                $sellerProData['product_name'] = $item->getProduct()->getName();
            }
            $data[] = $sellerProData;
        }
        
        return $data;
    }

    /**
     * to check status of seller on paypal
     *
     * @param int $sellerId
     * @return boolean
     */
    public function getSellerPayPalStatus($sellerId)
    {
        $submerchantId = $this->helper->getSubmerchantId($sellerId);
        $merchantDataJson = $this->adapter->getMerchantStatus($submerchantId);
        if ($merchantDataJson) {
            $merchantData = $this->jsonHelper->jsonDecode($merchantDataJson);
            if (isset($merchantData['payments_receivable']) && isset($merchantData['primary_email_confirmed'])) {
                if (!$merchantData['payments_receivable'] || !$merchantData['primary_email_confirmed']) {
                    return false;
                }
            } else {
                return false;
            }
            return true;
        }
        return false;
    }
}
