<?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;
use Webkul\MpPayPal\Logger\Logger;
use Webkul\MpPayPal\Model\Ui\ConfigProvider;

/**
 * Webkul CheckoutSubmitAllAfterObserver Observer Model.
 */
class CheckoutSubmitAllAfterObserver 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(
        Logger $logger,
        \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->_logger = $logger;
        $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 != null && $order->getPayment()->getMethod() == ConfigProvider::CODE && !$order->canInvoice()) {
            $payment = $order->getPayment();
            $lastOrderId = $observer->getOrder()->getId();
            $paypalAuthData = $payment->getAdditionalInformation();
            if ($this->modConfig->getPaymentMode() != \Webkul\MpPayPal\Model\Source\Disbursement::MODE_DELAYED) {
                
                $sellerInvoiceData = $payment->getAdditionalInformation('item__invoice__data');
                $payment = $order->getPayment();
                $lastOrderId = $observer->getOrder()->getId();
                if ($sellerInvoiceData) {
                    $this->_logger->critical('sellerInvoiceData '.$sellerInvoiceData);
                    $sellerInvoiceData = \Zend\Json\Json::decode($sellerInvoiceData, true);
                    $this->manageInvoiceData($sellerInvoiceData);
                }
            }
            $transactions = $this->transactions->create()->addOrderIdFilter($lastOrderId);
            $transactionItems = $transactions->getItems();
            foreach ($transactionItems as $txnData) {
                $this->setTranasctionData($txnData, $paypalAuthData);
                $txnData->save();
            }
        }
    }

    /**
     * add invoice data to marketplace orders
     *
     * @param array $sellerInvoiceData
     * @return void
     */
    public function manageInvoiceData($sellerInvoiceData)
    {
        foreach ($sellerInvoiceData as $invoiceData) {
            $mpTracking = $this->mpOrderFactory->create()
                ->getCollection()
                ->addFieldToFilter('order_id', $invoiceData['order_id'])
                ->addFieldToFilter('seller_id', $invoiceData['seller_id']);

            if ($mpTracking->getSize() > 0) {
                foreach ($mpTracking as $row) {
                    $row->setInvoiceId($invoiceData['invoice_id']);
                    $row->save();
                }
            }
        }
    }

    /**
     * set transacrion data in additonal info
     *
     * @return void
     */
    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
        );
    }
}
