<?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\Controller\Adminhtml\Index;

use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Webkul\Marketplace\Model\SaleslistFactory;

class ExecutePayment extends Action
{
    /**
     * @var PageFactory
     */
    private $resultPageFactory;

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var \Webkul\Marketplace\Helper\Orders
     */
    private $mpHelperOrder;

    /**
     * @var Magento\Sales\Model\Order\Payment\Transaction
     */
    private $transactionModel;

    /**
     * @var \Webkul\Marketplace\Model\ResourceModel\Saleslist\CollectionFactory
     */
    private $saleslistCollection;

    /**
     * @param Action\Context $context
     * @param OrderRepositoryInterface $orderRepository
     * @param PageFactory $resultPageFactory
     * @param \Webkul\MpPayPal\Helper\Data $helper
     * @param \Webkul\MpPayPal\Model\PayPal\Adapter $adapter
     * @param \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param SaleslistFactory $saleslistFactory
     * @param \Webkul\Marketplace\Helper\Orders $mpHelperOrder
     * @param \Magento\Sales\Model\Order\Payment\Transaction $transactionModel
     * @param \Webkul\MpPayPal\Model\ResourceModel\MpPayPal\CollectionFactory $paypalOrders
     */
    public function __construct(
        Action\Context $context,
        OrderRepositoryInterface $orderRepository,
        PageFactory $resultPageFactory,
        \Webkul\MpPayPal\Helper\Data $helper,
        \Webkul\MpPayPal\Model\PayPal\Adapter $adapter,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        SaleslistFactory $saleslistFactory,
        \Webkul\Marketplace\Helper\Orders $mpHelperOrder,
        \Magento\Sales\Model\Order\Payment\Transaction $transactionModel,
        \Magento\Framework\Session\SessionManagerInterface $coreSession,
        \Webkul\MpPayPal\Model\ResourceModel\MpPayPal\CollectionFactory $paypalOrders
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->orderRepository = $orderRepository;
        $this->helper = $helper;
        $this->mpHelperOrder = $mpHelperOrder;
        $this->messageManager = $messageManager;
        $this->saleslistFactory = $saleslistFactory;
        $this->adapter = $adapter;
        $this->jsonResultFactory = $jsonResultFactory;
        $this->transactionModel = $transactionModel;
        $this->coreSession = $coreSession;
        $this->paypalOrders = $paypalOrders;
        parent::__construct($context);
    }

    /**
     * Default customer account page
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $resultJson = $this->jsonResultFactory->create();
        $orderId = $this->getRequest()->getParam('order_id');
        $captureId = $this->getRequest()->getParam('capture_id');
        $order = $this->orderRepository->get($orderId);
        $payPalOrder = $this->paypalOrders->create()
        ->addFieldToFilter('order_id', $order->getIncrementId())
        ->addFieldToFilter('capture_id', $captureId)
        ->getFirstItem();
        $captureId = $payPalOrder->getCaptureId();
        $response = $this->adapter->releasePayment($captureId);
        if (isset($response['error']) && $response['error']) {

            $this->coreSession->setErrorMessage($response['message']);

        } elseif ($response['processing_state']['status'] == 'SUCCESS') {
            $payPalOrder->setPaymentStatus(1)->save();
            $collection = $this->saleslistFactory->create()
                ->getCollection()
                ->addFieldToFilter(
                    'seller_id',
                    $payPalOrder->getSellerId()
                )
                ->addFieldToFilter(
                    'order_id',
                    $orderId
                )
                ->addFieldToFilter(
                    'paid_status',
                    0
                );
            foreach ($collection as $item) {
                $item->setCpprostatus(1)->save();
            }
            $this->mpHelperOrder->paysellerpayment(
                $order,
                $payPalOrder->getSellerId(),
                $response['payout_transaction_id']
            );

            $response['error'] = 0;
            $message = __('Payment Released');
            $this->coreSession->setSuccessMessage($message);
        }
        /**
         * @var \Magento\Backend\Model\View\Result\Page $resultPage
        */
        $resultPage = $this->resultPageFactory->create();
        $block = $resultPage->getLayout()->createBlock(
            \Webkul\MpPayPal\Block\Adminhtml\Order\View\Tabs\Delayed::class
        )->toHtml();
        $this->getResponse()->setBody($block);
    }
}
