<?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\Http\Client;

use Magento\Payment\Gateway\Http\ClientException;

class TransactionRefund extends AbstractTransaction
{
    /**
     * Process http request
     * @param array $data
     * @return
     */
    protected function process(array $data)
    {
        $transaction = $this->adapter->findOrder($data['transaction_id']);
        $purchaseUnit = $transaction['purchase_units'][0];
        $captureData = $purchaseUnit['payments']['captures'][0];
        
        if ($captureData && $captureData['status'] == 'COMPLETED') {
            $currencyCode = $this->storeManager->getStore()->getCurrentCurrencyCode();
            $requestData = [];
            $requestData['amount']['currency_code'] = $currencyCode;
            $requestData['amount']['value'] = $data['amount'];
            $requestData['invoice_id'] = "REFUND-INV-".strtotime($this->_date->gmtDate()).'-'.$captureData['id'];
            $requestData['custom'] = "REFUND-CUST-".strtotime($this->_date->gmtDate()).'-'.$captureData['id'];
            return $this->adapter->refundOrder(
                $requestData,
                $purchaseUnit
            );
        } else {
            throw new ClientException(__("cannot refund transaction currently, please try again later."));
        }
    }
}
