<?php
/**
 * Webkul Software.
 *
 * @category Webkul
 *
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\MpPaypal\Gateway\Response;

use Webkul\MpPaypal\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Response\HandlerInterface;
use Magento\Sales\Model\Order\Payment;

class TransactionIdHandler implements HandlerInterface
{
    /**
     * @var SubjectReader
     */
    protected $subjectReader;

    /**
     * TransactionIdHandler constructor.
     * @param SubjectReader $subjectReader
     */
    public function __construct(
        SubjectReader $subjectReader,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Webkul\MpPaypal\Helper\Data $helper
    ) {
        $this->subjectReader = $subjectReader;
        $this->helper = $helper;
        $this->jsonHelper = $jsonHelper;
    }

    /**
     * Handles response
     *
     * @param array $handlingSubject
     * @param array $response
     * @return void
     */
    public function handle(array $handlingSubject, array $response)
    {
        $this->helper->logDataInLogger('TransactionIdHandler '.$this->jsonHelper->jsonEncode($response));
        $paymentDO = $this->subjectReader->readPayment($handlingSubject);

        if ($paymentDO->getPayment() instanceof Payment) {

            foreach ($response['object'] as $transaction) {
                /** @var Payment $orderPayment */
                $orderPayment = $paymentDO->getPayment();
                $transactionId = '';
                if (!empty($transaction['additional_information'])) {
                    $purchaseUnits = \Zend_Json::decode($transaction['additional_information']['purchase_units']);
                    foreach ($purchaseUnits as $purchaseDetails) {
                        foreach ($purchaseDetails['payments']['captures'] as $captureData) {
                            $transactionId = $captureData['id'];
                        }
                    }
                } else {
                    foreach ($transaction['purchase_units'] as $purchaseDetails) {
                        foreach ($purchaseDetails['payments']['captures'] as $captureData) {
                            $transactionId = $captureData['id'];
                        }
                    }
                }
                
                $this->setTransactionId(
                    $orderPayment,
                    $transactionId
                );

                $orderPayment->setIsTransactionClosed($this->shouldCloseTransaction());
                $closed = $this->shouldCloseParentTransaction($orderPayment);
                $orderPayment->setShouldCloseParentTransaction($closed);
        
                foreach ($transaction as $key => $value) {
                    $validValue = '';
                    if (is_array($value)) {
                        $validValue = \Zend_Json::encode($value);
                    } else {
                        $validValue = $value;
                    }
                    $this->helper->logDataInLogger('additional_information '.$key.' validValue '.$validValue);

                    $orderPayment->setAdditionalInformation($key, $validValue);
                }
            }
        }
        return $response;
    }

    /**
     * @param Payment $orderPayment
     * @param array $transaction
     * @return void
     */
    protected function setTransactionId(Payment $orderPayment, $transactionId)
    {
        $orderPayment->setTransactionId($transactionId);
    }

    /**
     * Whether transaction should be closed
     *
     * @return bool
     */
    protected function shouldCloseTransaction()
    {
        return true;
    }

    /**
     * Whether parent transaction should be closed
     *
     * @param Payment $orderPayment
     * @return bool
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    protected function shouldCloseParentTransaction(Payment $orderPayment)
    {
        return false;
    }
}
