<?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\Payment\PayPal;

use Magento\Sales\Api\OrderRepositoryInterface;
use Webkul\Marketplace\Model\SaleslistFactory;

class PaymentPayoutComplete
{

    /**
     * @param \Webkul\MpPayPal\Helper\Data $helper
     * @param SaleslistFactory $saleslistFactory
     * @param OrderRepositoryInterface $orderRepository
     * @param \Webkul\Marketplace\Helper\Orders $mpHelperOrder
     * @param \Webkul\MpPayPal\Model\ResourceModel\MpPayPal\CollectionFactory $paypalOrders
     */
    public function __construct(
        \Webkul\MpPayPal\Helper\Data $helper,
        SaleslistFactory $saleslistFactory,
        OrderRepositoryInterface $orderRepository,
        \Webkul\Marketplace\Helper\Orders $mpHelperOrder,
        \Webkul\MpPayPal\Model\ResourceModel\MpPayPal\CollectionFactory $paypalOrders
    ) {
        $this->helper = $helper;
        $this->orderRepository = $orderRepository;
        $this->mpHelperOrder = $mpHelperOrder;
        $this->saleslistFactory = $saleslistFactory;
        $this->paypalOrders = $paypalOrders;
    }
    
    /**
     * manage seller transaction payout
     *
     * @param array $resource
     * @return void
     */
    public function process($resource)
    {
        $this->helper->logDataInLogger('PaymentPayoutComplete '.json_encode($resource));
        if ($response['processing_state']['status'] == 'SUCCESS') {

            $payPalOrder = $this->paypalOrders->create()
            ->addFieldToFilter('invoice_id', $resource['invoice_id'])
            ->getFirstItem();
            $orderId = $payPalOrder->getOrderId();
            $payPalOrder->setPaymentStatus(1)->save();
            $collection = $this->saleslistFactory->create()
                ->getCollection()
                ->addFieldToFilter(
                    'seller_id',
                    $payPalOrder->getSellerId()
                )
                ->addFieldToFilter(
                    'magerealorder_id',
                    $orderId
                )
                ->addFieldToFilter(
                    'paid_status',
                    0
                );
            if ($collection->getSize()) {
                $orderId = 0;
                foreach ($collection as $item) {
                    $orderId = $item->getOrderId();
                    $item->setCpprostatus(1)->save();
                }
                if ($orderId) {
                    $order = $this->orderRepository->get($orderId);
    
                    $this->mpHelperOrder->paysellerpayment(
                        $order,
                        $payPalOrder->getSellerId(),
                        $resource['payout_transaction_id']
                    );
                }
            }
        }
    }
}
