<?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);
        $transactions = $this->subjectReader->readTransaction($response['object']);
        $this->helper->logDataInLogger('TransactionIdHandler transactions'.
        $this->jsonHelper->jsonEncode($transactions));
        
        if ($paymentDO->getPayment() instanceof Payment) {

            foreach ($transactions as $transaction) {
                /** @var Payment $orderPayment */
                $orderPayment = $paymentDO->getPayment();
                $this->setTransactionId(
                    $orderPayment,
                    $transaction['id']
                );
                $orderPayment->setIsTransactionClosed($this->shouldCloseTransaction());
                $closed = $this->shouldCloseParentTransaction($orderPayment);
                $orderPayment->setShouldCloseParentTransaction($closed);
            }

        }
        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 false;
    }

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