<?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\Request;

use Webkul\MpPayPal\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Request\BuilderInterface;
use Magento\Payment\Helper\Formatter;
use Magento\Sales\Api\Data\TransactionInterface;
use Magento\Sales\Model\Order\Payment;

class RefundDataBuilder implements BuilderInterface
{
    use Formatter;

    /**
     * @var SubjectReader
     */
    private $subjectReader;

    /**
     * Constructor
     *
     * @param SubjectReader $subjectReader
     */
    public function __construct(SubjectReader $subjectReader)
    {
        $this->subjectReader = $subjectReader;
    }

    /**
     * Builds ENV request
     *
     * @param array $buildSubject
     * @return array
     */
    public function build(array $buildSubject)
    {
        $paymentDO = $this->subjectReader->readPayment($buildSubject);

        /** @var Payment $payment */
        $payment = $paymentDO->getPayment();
        
        $amount = $this->formatPrice($this->subjectReader->readAmount($buildSubject));

        $txnId = str_replace(
            '-' . TransactionInterface::TYPE_CAPTURE,
            '',
            $payment->getRefundTransactionId()
        );
        $sellerData = $payment->getAdditionalInformation();
        $transactionData = '';
        foreach ($sellerData as $key => $data) {
            $isSeller = explode('sellerId_', $key);
            if (isset($isSeller[1])) {
                if ($data['payments']['captures'][0]['id'] == $txnId) {
                    $transactionData = $data;
                }
            }
        }
        return [
            'transaction_id' => $txnId,
            'amount' => $amount,
            'transaction_data' => $transactionData
        ];
    }
}
