<?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\Observer;

use Magento\Framework\Event\ObserverInterface;
use Webkul\Marketplace\Model\SaleslistFactory;

/**
 * Webkul Marketplace SalesOrderSaveCommitAfterObserver Observer Model.
 */
class SalesOrderSaveCommitAfterObserver implements ObserverInterface
{
    /**
     * @var eventManager
     */
    protected $_eventManager;

    /**
     * @var Session
     */
    protected $_customerSession;

    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    protected $_date;

    /**
     * @var \Webkul\Marketplace\Model\OrdersFactory
     */
    protected $mpOrderFactory;

    /**
     * @param \Magento\Framework\Event\Manager            $eventManager
     * @param \Magento\Customer\Model\Session             $customerSession
     * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
     */
    public function __construct(
        \Magento\Framework\Event\Manager $eventManager,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        \Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory $transactions,
        \Webkul\MpPaypal\Gateway\Config\Config $modConfig,
        SaleslistFactory $saleslistFactory,
        \Webkul\MpPaypal\Model\MpPaypalFactory $paypalOrders,
        \Webkul\MpPaypal\Helper\Data $helper,
        \Webkul\Marketplace\Helper\Orders $mpHelperOrder,
        \Webkul\Marketplace\Model\OrdersFactory $mpOrderFactory
    ) {
        $this->_eventManager = $eventManager;
        $this->_customerSession = $customerSession;
        $this->_date = $date;
        $this->helper = $helper;
        $this->modConfig = $modConfig;
        $this->transactions = $transactions;
        $this->saleslistFactory = $saleslistFactory;
        $this->mpHelperOrder = $mpHelperOrder;
        $this->paypalOrders = $paypalOrders;
        $this->mpOrderFactory = $mpOrderFactory;
    }

    /**
     * Sales order save commmit after on order complete state event handler.
     *
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /** @var $orderInstance Order */
        $order = $observer->getOrder();
        if ($order) {
            $payment = $order->getPayment();
            $lastOrderId = $observer->getOrder()->getId();
            if ($order->getPayment()->getMethod() == 'mppaypal' && $order->canInvoice()) {
                $paypalAuthData = $payment->getAdditionalInformation();
                $order->getPayment()->capture(null);
                $order->save();
                if ($this->modConfig->getPaymentMode() != \Webkul\MpPaypal\Model\Source\Disbursement::MODE_DELAYED) {
                    
                    $payPalOrder = $this->paypalOrders->create()->getCollection()
                    ->addFieldToFilter('order_id', $order->getIncrementId())
                    ->getFirstItem();
                    $collection = $this->saleslistFactory->create()
                    ->getCollection()
                    ->addFieldToFilter(
                        'seller_id',
                        $payPalOrder->getSellerId()
                    )
                    ->addFieldToFilter(
                        'order_id',
                        $lastOrderId
                    )
                    ->addFieldToFilter(
                        'paid_status',
                        0
                    );
                    foreach ($collection as $item) {
                        $item->setCpprostatus(1)->save();
                    }
                    $this->mpHelperOrder->paysellerpayment(
                        $order,
                        $payPalOrder->getSellerId(),
                        $payment->getTransactionId()
                    );
                    $transactions = $this->transactions->create()->addOrderIdFilter($lastOrderId);
                    $transactionItems = $transactions->getItems();
                    foreach ($transactionItems as $txnData) {
                        $this->setTranasctionData($txnData, $paypalAuthData);
                        $txnData->save();
                    }
                }
            }
        }
    }

    public function setTranasctionData($txnData, $paypalAuthData)
    {
        $transactionArr = [];
        foreach ($paypalAuthData as $key => $value) {
            $validValue = '';
            if (is_array($value)) {
                $validValue = \Zend_Json::encode($value);
            } else {
                $validValue = $value;
            }
            $transactionArr[$key] = $validValue;
        }
        $txnData->setAdditionalInformation(
            \Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS,
            $transactionArr
        );
    }
}
