<?php

namespace AluPays\Entity;

use Exception;

/**
 * Solicitud de retiro.
 */
class WithdrawalRequest
{
    /**
     * @var string La moneda en la cual se realiza la solicitud (ISO 4217).
     *             Código de tres letras.
     */
    protected $currency = Transaction::CURRENCY_USD;
    /**
     * @var mixed. float o decimal en formato string. Representa el importe
     *             de la solicitud de retiro.
     */
    protected $amount = 0;
    protected $description = null;

    private function validateCurrency($currency)
    {
        return (in_array(strtoupper($currency), Transaction::validCurrencies()));
    }

    private function validateAmount($amount)
    {
        return is_numeric($amount) && $amount > 0;
    }

    /**
     * @param string $currency
     * @param mixed  $amount
     * @param string $description
     */
    public function __construct($currency, $amount, $description=null)
    {
        if (!$this->validateCurrency($currency)) {
            throw new Exception('[INVALID_CURRENCY] La moneda no es válida. No se encuentra entre las monedas aceptadas.');
        }
        if (!$this->validateAmount($amount)) {
            throw new Exception('[INVALID_AMOUNT] El monto no es válido. Debe especificar un número mayor que 0.');
        }
        $this->currency = strtoupper($currency);
        $this->amount = $amount;
        $this->description = $description;
    }

    public function getCurrency()
    {
        return $this->currency;
    }

    public function getAmount()
    {
        return $this->amount;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function toArray()
    {
        $out = [
           'withdrawal_request' => [
              'currency' => $this->currency,
              'amount' => $this->amount,
              'description' => $this->description,
            ]
        ];

        return $out;
    }

    public function toJSON()
    {
        return json_encode($this->toArray());
    }
}

