<?php
namespace AluPays\Command;

use AluPays\Entity\Transaction;
use AluPays\Entity\TransactionResult;
use AluPays\Entity\Booking;
use AluPays\Exception\AluPaysException as Exception;

class RefundTransactionCmd extends AbstractCommand {
  /**
   * @const string Punto de entrada de API de transacciones.
   */
  const API_ENTRYPOINT = 'transaction';

  public function execute($transaction, $raw = false) {
    if (empty($transaction)) {
        throw new Exception('Debe suministrar una transacción');
    }

    $transaction->setType(Transaction::TX_FUND);

    $response = $this->http_client->put($this->base_url, self::API_ENTRYPOINT, $transaction->toJSON());
    $retTx = $response->then(function ($result) use ($raw) {
          if (!$raw) {
              $retTx = new TransactionResult(
                $result['result']['transaction']['id'],
                $result['result']['transaction']['internal_id'],
                $result['result']['transaction']['status']
              );
              if (!empty($result['result']['payment_url'])) {
                $retTx->setPaymentUrl($result['result']['payment_url']);
              }

              if (!empty($result['result']['booking']['code'])) {
                $booking = new Booking($result['result']['booking']['code']);
                $retTx->setBooking($booking);
              }

              return $retTx;
          } else {
              return $result['result'];
          }
    }, function ($result, $rawResponse) {
          if (!empty($result['message'])) {
            return $result['message'];
          } else {
            return $rawResponse;
          }
    });
    $this->response = $response->getRawResponse();

    return $retTx;
  }
}

