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

class PaymentCaptureCompleted
{

    /**
     * @param \Webkul\MpPayPal\Api\PayPalOrderManagementInterface $paypalOrderManager
     * @param \Webkul\MpPayPal\Model\MpPayPalFactory $transactionData
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
     * @param \Webkul\MpPayPal\Helper\Data $helper
     */
    public function __construct(
        \Webkul\MpPayPal\Api\PayPalOrderManagementInterface $paypalOrderManager,
        \Webkul\MpPayPal\Model\MpPayPalFactory $transactionData,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
        \Webkul\MpPayPal\Gateway\Config\Config $modConfig,
        \Webkul\MpPayPal\Helper\Data $helper
    ) {
        $this->_paypalOrderManager = $paypalOrderManager;
        $this->transactionData = $transactionData;
        $this->orderFactory = $orderFactory;
        $this->quoteRepository = $quoteRepository;
        $this->modConfig = $modConfig;
        $this->helper = $helper;
    }

    /**
     * process invoice and transaction
     *
     * @param array $resource
     * @return void
     */
    public function process($resource)
    {
        if ($resource['status'] == 'COMPLETED') {
            $paypalOrderId = $resource['id'];
            $mpPayPalOrder = $this->transactionData->create()->getCollection()
            ->addFieldToFilter('capture_id', $paypalOrderId)->getFirstItem();
            $orderId = $mpPayPalOrder->getOrderId();
            $quoteId = $mpPayPalOrder->getQuoteId();
            $sellerId = $mpPayPalOrder->getSellerId();
            $order = $this->orderFactory->create()->loadByIncrementId($orderId);
            $quote = $this->quoteRepository->get($quoteId);
            if ($order->getPayment()->getMethod() == ConfigProvider::CODE) {
                $this->helper->logDataInLogger('PaymentCaptureCompleted');
                //this code will be only executed if
                $totalDue = 0;
                if ($order->getTotalDue()) {
                    $totalDue = $order->getTotalDue();
                }
                if ($totalDue > 0) {
    
                    $cartData = $this->helper->createFinalCart($quote);
                    /**
                     * $ifSellerInCart check if there is atlest one seller product is order.
                     *
                     * @var bool
                     */
                    $ifSellerInCart = $this->_paypalOrderManager->getIfSellerInCart($cartData);
                    $this->manageInvoice($ifSellerInCart, $cartData, $order, $sellerId);
                }
            }
        }
    }

    /**
     * manage invoice
     *
     * @param boolean $ifSellerInCart
     * @param array $cartData
     * @param \Magento\Sales\Model\Order $order
     * @param int $sellerId
     * @return void
     */
    public function manageInvoice($ifSellerInCart, $cartData, $order, $sellerId)
    {
        try {
            $transactionIds = [];
            $sellerInvoiceData = [];
            if ($ifSellerInCart) {
                // manage admin shipping
                $shippingArray = [];
                $sellerCount = 0;
                foreach ($cartData as $cart) {
                    if ($cart['seller']) {
                        $sellerCount++;
                    } else {
                        $shippingArray = $cart;
                    }
                }
                foreach ($cartData as $cart) {
                    if ($cart['seller'] && ($sellerId == $cart['seller'])) {
                        /**
                         * $transactionId create transaction.
                         *
                         * @var string
                         */
                        $transactionId = $this->_paypalOrderManager->doTransaction($order, $cart);
                        $transactionIds[] = $transactionId;
                        $realTransactionId = $this->_paypalOrderManager->getRealTransactionId($transactionId);
                        $invoiceId = $this->_paypalOrderManager
                                ->doSellerOrderInvoice($order, $cart, $realTransactionId, $sellerCount, $shippingArray);
                        $sellerInvoiceData[] = $this->handlePaymentInformation(
                            $invoiceId,
                            $cart,
                            $order,
                            $realTransactionId,
                            $transactionId
                        );
                    }
                }
            }
            
            if (count($transactionIds) > 0) {
                $payment = $order->getPayment();
                $payment->setAdditionalInformation(
                    'item__transaction__data',
                    \Zend\Json\Json::encode($transactionIds)
                );
                $payment->save();
            }

            if (count($sellerInvoiceData) > 0) {
                $payment = $order->getPayment();
                $this->helper->logDataInLogger('sellerInvoiceData observer'.json_encode($sellerInvoiceData));
                $payment->setAdditionalInformation(
                    'item__invoice__data',
                    \Zend\Json\Json::encode($sellerInvoiceData)
                );
                $payment->save();
            }
        } catch (\Exception $e) {
            $this->helper->logDataInLogger($e);
            throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
        }
    }

    private function handlePaymentInformation($invoiceId, $cart, $order, $realTransactionId, $transactionId)
    {
        $this->helper->logDataInLogger('handlePaymentInformation');
        $sellerInvoiceData = [];
        if ($invoiceId) {
            $finalArr['order_id'] = $order->getId();
            $finalArr['invoice_id'] = $invoiceId;
            $finalArr['seller_id'] = $cart['seller'];
            $sellerInvoiceData = $finalArr;
        }
        if (isset($cart['seller']) && $cart['seller']) {
            if ($this->modConfig->getPaymentMode() == Disbursement::MODE_INSTANT) {
                $this->helper->logDataInLogger('handlePaymentInformation seller payout');
                $this->_paypalOrderManager->payToSeller($order, $cart['seller'], $transactionId);
            }
        }

        return $sellerInvoiceData;
    }
}
