<?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\Gateway\Response;

use Magento\Payment\Gateway\Helper\ContextHelper;
use Webkul\MpPayPal\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Response\HandlerInterface;
use Magento\Sales\Api\Data\OrderPaymentInterface;

class PaymentDetailsHandler implements HandlerInterface
{
    /**
     * @var SubjectReader
     */
    private $subjectReader;

    /**
     * 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;
    }

    /**
     * @inheritdoc
     */
    public function handle(array $handlingSubject, array $response)
    {
        $this->helper->logDataInLogger('paymentdetailshandler '.$this->jsonHelper->jsonEncode($response));
        $paymentDO = $this->subjectReader->readPayment($handlingSubject);
        
        $payment = $paymentDO->getPayment();

        $transactions = $response['object'];
        
        $payment->unsAdditionalInformation();
        foreach ($transactions as $transactionData) {
            foreach ($transactionData['purchase_units'] as $transaction) {
                $payment->setAdditionalInformation($transaction['reference_id'], $transaction);
            }
        }
    }
}
