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

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;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;

class Success extends Action implements CsrfAwareActionInterface
{

    protected $_publicActions = ['success'];

    /**
     * @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,
        \Webkul\MpPayPal\Model\PayPal\Adapter $adapter,
        \Webkul\MpPayPal\Api\PayPalOrderManagementInterface $paypalOrdermanagement,
        \Webkul\MpPayPal\Helper\Data $helper
    ) {
        parent::__construct($context);
        $this->adapter = $adapter;
        $this->paypalOrdermanagement = $paypalOrdermanagement;
        $this->helper = $helper;
    }

    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

    public function validateForCsrf(RequestInterface $request): ?bool
    {
        return true;
    }

    public function execute()
    {
        $request = $this->getRequest()->getParams();

        $payerId = (isset($request['PayerID']))?$request['PayerID']:'';
        $token = (isset($request['token']))?$request['token']:'';
        if ($payerId && $token) {
            try {
                $orderData = $this->adapter->findOrder($token);
                if ($orderData['status'] == 'APPROVED' && $orderData['payer']['payer_id'] == $payerId) {
                    
                    $this->paypalOrdermanagement->createOrder($orderData);
    
                    return $this->resultRedirectFactory->create()->setPath(
                        'checkout/onepage/success',
                        ['_secure'=>true]
                    );
                } else {
                    $this->helper->logDataInLogger('success order');
                    $this->messageManager->addError(__('There were some errors from PayPal, order was not completed'));
                    /** @var \Magento\Framework\View\Result\Page $resultPage */
                    $resultPage = $this->resultRedirectFactory->create();
                    $resultPage->setPath('checkout/cart', ['_current' => true]);
                    return $resultPage;
                }
            } catch (\Exception $e) {
                $this->messageManager->addError(__('There were some errors from PayPal, order was not completed'));
                $this->helper->logDataInLogger('success error'.$e->getMessage());
                /** @var \Magento\Framework\View\Result\Page $resultPage */
                $resultPage = $this->resultRedirectFactory->create();
                $resultPage->setPath('checkout/cart', ['_current' => true]);
                return $resultPage;
            }
        } else {
            $this->messageManager->addError(__('There were some errors from PayPal, order was not completed'));
            /** @var \Magento\Framework\View\Result\Page $resultPage */
            $resultPage = $this->resultRedirectFactory->create();
            $resultPage->setPath('checkout/cart', ['_current' => true]);
            return $resultPage;
        }
    }
}
