<?php
namespace Webkul\MpPayPal\Controller\Seller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Customer\Model\Session;
use Magento\Framework\App\RequestInterface;

class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;

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

    /**
     * @var Magento\Framework\Registry
     */
    protected $_coreRegistry;

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

    /**
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param Session $customerSession
     * @param \Webkul\Marketplace\Helper\Data $marketplaceHelper
     * @param \Magento\Customer\Model\Url $url
     * @param \Magento\Framework\Registry $coreRegistry
     * @param \Magento\Customer\Model\CustomerFactory $customerFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Session $customerSession,
        \Webkul\Marketplace\Helper\Data $marketplaceHelper,
        \Magento\Customer\Model\Url $url,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Customer\Model\CustomerFactory $customerFactory
    ) {
        parent::__construct($context);
        $this->_customerSession = $customerSession;
        $this->_resultPageFactory = $resultPageFactory;
        $this->_marketplaceHelper = $marketplaceHelper;
        $this->_coreRegistry = $coreRegistry;
        $this->url = $url;
        $this->customerFactory = $customerFactory;
    }

    /**
     * Retrieve customer session object.
     *
     * @return \Magento\Customer\Model\Session
     */
    protected function _getSession()
    {
        return $this->_customerSession;
    }

    /**
     * Check customer authentication.
     *
     * @param RequestInterface $request
     *
     * @return \Magento\Framework\App\ResponseInterface
     */
    public function dispatch(RequestInterface $request)
    {
        $loginUrl = $this->url->getLoginUrl();

        if (!$this->_customerSession->authenticate($loginUrl)) {
            $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
        }
        return parent::dispatch($request);
    }

    public function execute()
    {
        $helper = $this->_marketplaceHelper;
        $isPartner = $helper->isSeller();
        if ($isPartner == 1) {
            /** @var \Magento\Framework\View\Result\Page $resultPage */
            $resultPage = $this->_resultPageFactory->create();
            if ($helper->getIsSeparatePanel()) {
                $resultPage->addHandle('mppaypal_layout2_seller_index');
            }
            $resultPage->getConfig()->getTitle()->set(__('PayPal Merchant Onboard'));
            /**
             * to manage response from PayPal onboarding
             */
            $this->checkSellerOnBoarding();

            return $resultPage;
        } else {
            return $this->resultRedirectFactory->create()->setPath(
                '*/*/becomeseller',
                ['_secure' => $this->getRequest()->isSecure()]
            );
        }
    }

    /**
     * to check if seller connected on PayPal with partner
     *
     * @return void
     */
    public function checkSellerOnBoarding()
    {
        $request = $this->getRequest()->getParams();
        if (!empty($request['merchantId']) && !empty($request['merchantIdInPayPal'])) {
            $trackingId = $request['merchantId'];
            $merchantId = $request['merchantIdInPayPal'];
            $customer = $this->_marketplaceHelper->getCustomer();
            $customer->setMppaypalSubmerchantId($request['merchantIdInPayPal']);
            if ($request['isEmailConfirmed'] && $request['consentStatus'] && $request['permissionsGranted']) {
                $customer->setMppaypalMerchantStatus(1);
            }
            $customer->setMppaypalMerchantTrackingId($request['merchantId']);
            $customer->save();
            if (isset($request['returnMessage'])) {
                $this->mesageManager->addNotice($request['returnMessage']);
            }
        }
    }
}
