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

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Checkout\Model\Session as CheckoutSession;

class CaptureOrder extends Action implements CsrfAwareActionInterface
{
    protected $_publicActions = ['captureorder'];

    /**
     * @param Context $context
     * @param \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory
     * @param \Webkul\MpPayPal\Helper\Data $helper
     * @param CheckoutSession $checkoutSession
     * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
     * @param \Webkul\MpPayPal\Model\MpPayPalFactory $paypalOrders
     * @param \Webkul\MpPayPal\Gateway\Config\Config $modConfig
     * @param \Magento\Framework\Json\Helper\Data $jsonHelper
     * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepo
     * @param \Webkul\MpPayPal\Model\PayPal\Adapter $adapter
     */
    public function __construct(
        Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        \Webkul\MpPayPal\Helper\Data $helper,
        CheckoutSession $checkoutSession,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        \Webkul\MpPayPal\Model\MpPayPalFactory $paypalOrders,
        \Webkul\MpPayPal\Gateway\Config\Config $modConfig,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepo,
        \Webkul\MpPayPal\Model\PayPal\Adapter $adapter
    ) {
        parent::__construct($context);
        $this->jsonResultFactory = $jsonResultFactory;
        $this->adapter = $adapter;
        $this->paypalOrders = $paypalOrders;
        $this->_date = $date;
        $this->jsonHelper = $jsonHelper;
        $this->helper = $helper;
        $this->modConfig = $modConfig;
        $this->checkoutSession = $checkoutSession;
        $this->customerRepo = $customerRepo;
    }

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

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

    public function execute()
    {
        $resultJson = $this->jsonResultFactory->create();
        
        $requestData = $this->getRequest()->getParams('data');
        if ($requestData['data']['orderID']) {
            $returnData = $this->adapter->captureOrder($requestData['data']['orderID']);
            $this->helper->logDataInLogger('response captureorder '.$returnData);
            $returnData = $this->jsonHelper->jsonDecode($returnData, true);
            $returnData['error'] = 0;
            if (empty($returnData['debug_id'])) {
                $captureMode = $requestData['captureMode'];
                $sellerEmail = $requestData['sellerEmail'];
                $seller = $this->customerRepo->get($sellerEmail);
                $quote = $this->checkoutSession->getQuote();
                $delayedTrue = 0;
                if ($this->modConfig->getPaymentMode() == \Webkul\MpPayPal\Model\Source\Disbursement::MODE_DELAYED) {
                    $delayedTrue = 1;
                }
                $finalData = [
                    'quote_id' => $quote->getId(),
                    'delayed_payment' => $delayedTrue,
                    'seller_id' => $seller->getId(),
                    'capture_id' => $returnData['purchase_units'][0]['payments']['captures'][0]['id'],
                    'created_at' => $this->_date->gmtDate(),
                    'updated_at' => $this->_date->gmtDate()
                ];
                $paypalOrder = $this->paypalOrders->create();
    
                $paypalOrder->setData($finalData)->save();
            } else {
                $returnData['error'] = 1;
            }
            return $resultJson->setData($this->jsonHelper->jsonEncode($returnData));
        }
    }
}
