<?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 Magento\Framework\Exception\LocalizedException;
use Webkul\MpPaypal\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Request\BuilderInterface;
use Magento\Payment\Helper\Formatter;
use Magento\Payment\Gateway\Http\ClientException;

class CaptureDataBuilder implements BuilderInterface
{
    use Formatter;

    const TRANSACTION_ID = 'id';

    const ADDITIONAL_DATA = 'additional_information';

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

    /**
     * Constructor
     *
     * @param SubjectReader $subjectReader
     */
    public function __construct(
        SubjectReader $subjectReader,
        \Webkul\MpPaypal\Model\Paypal\Adapter $adapter,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Webkul\MpPaypal\Helper\Data $helper
    ) {
        $this->subjectReader = $subjectReader;
        $this->adapter = $adapter;
        $this->jsonHelper = $jsonHelper;
        $this->helper = $helper;
    }

    /**
     * @inheritdoc
     */
    public function build(array $buildSubject)
    {
        $this->helper->logDataInLogger('captureDataBuilder '.$this->jsonHelper->jsonEncode($buildSubject));
        $paymentDO = $this->subjectReader->readPayment($buildSubject);

        $payment = $paymentDO->getPayment();
        $order = $paymentDO->getOrder();

        $transactionId = $payment->getTransactionId();
        if (!$transactionId) {
            $this->adapter->cancelOrder($order);
            $this->messageManager->addError(
                __(
                    'There was an error capturing the transaction, order has been cancelled'
                )
            );
            $this->helper->logDataInLogger("Controller_Index_Paymentsuccess execute : ".$e->getMessage());
            // restoring cart items
            $quote = $this->quoteRepository->get($order->getQuoteId());
            $quote->setIsActive(1)->setReservedOrderId(null);
            $this->quoteRepository->save($quote);
            $this->checkoutSession->setQuoteId($quote->getId());

            return $this->resultRedirectFactory->create()->setPath(
                'checkout/cart'
            );

        }
        $additionalInformation = $payment->getAdditionalInformation();
        return [
            self::TRANSACTION_ID => $transactionId,
            self::ADDITIONAL_DATA => $additionalInformation
        ];
    }
}
