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

use Webkul\MpPaypal\Model\Paypal\Adapter as MpPaypalAdapter;
use Magento\Payment\Gateway\Http\ClientException;
use Magento\Payment\Gateway\Http\ClientInterface;
use Magento\Payment\Gateway\Http\TransferInterface;
use Magento\Payment\Model\Method\Logger;
use Psr\Log\LoggerInterface;

/**
 * Class AbstractTransaction
 */
abstract class AbstractTransaction implements ClientInterface
{
    /**
     * @var LoggerInterface
     */
    protected $_logger;

    /**
     * @var Logger
     */
    protected $_customLogger;

    /**
     * @var MpPaypalAdapter
     */
    protected $adapter;

    /**
     * constructor
     *
     * @param LoggerInterface $logger
     * @param Logger $customLogger
     * @param MpPaypalAdapter $adapter
     */
    public function __construct(
        \Webkul\MpPaypal\Helper\Data $helper,
        Logger $customLogger,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        MpPaypalAdapter $adapter
    ) {
        $this->helper = $helper;
        $this->storeManager = $storeManager;
        $this->jsonHelper = $jsonHelper;
        $this->_customLogger = $customLogger;
        $this->_date = $date;
        $this->adapter = $adapter;
    }

    /**
     * @inheritdoc
     */
    public function placeRequest(TransferInterface $paypalTransferObject)
    {
        $transferData = $paypalTransferObject->getBody();
        $log = [
            'request' => $transferData,
            'client' => static::class
        ];
        $response['object'] = [];

        try {
            $response['object'] = $this->process($transferData);
        } catch (\Exception $e) {
            $message = __($e->getMessage() ?: 'Sorry, but something went wrong');
            $this->helper->logDataInLogger($message);
            throw new ClientException($message);
        } finally {
            $log['response'] = (array) $response['object'];
            $this->helper->logDataInLogger('abstracttransaction '.$this->jsonHelper->jsonEncode($log));
        }

        return $response;
    }

    /**
     * Process http request
     * @param array $request
     * @return \Braintree\Result\Error|\Braintree\Result\Successful
     */
    abstract protected function process(array $request);
}
