<?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 Magento\Sales\Model\Order\Payment\Transaction;

class PaymentCaptureRefunded
{
    public function __construct(
        \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\CollectionFactory $transactionFactory,
        \Webkul\MpPayPal\Helper\Data $helper
    ) {
        $this->transactionFactory = $transactionFactory;
        $this->helper = $helper;
    }

    public function process($resource)
    {
        $this->helper->logDataInLogger('PaymentCaptureRefunded '.json_encode($resource));
        if ($resource['status'] == 'COMPLETED') {
            $invoiceId = explode('-', $resource['invoice_id']);
            $pyapalCaptureId = $invoiceId[count($invoiceId)-1];
            
            $transactionData = $this->transactionFactory->create()
            ->addFieldToFilter('txn_id', $pyapalCaptureId.'-refund');

            if ($transactionData->getSize() > 0) {
                foreach ($transactionData as $transactionData) {
                    $finalData = [];
                    foreach ($resource as $key => $value) {
                        if (is_array($value)) {
                            $value = \Zend\Json\Json::encode($value);
                        }
                        $finalData[$key] = $value;
                    }
                    $transactionData->setAdditionalInformation(
                        Transaction::RAW_DETAILS,
                        $finalData
                    );
                    $transactionData->save();
                }
            }
        }
    }
}
