<?php

namespace AluPays\Entity;

use Exception;

/**
 * Transacción.
 */
class Transaction
{
    /**
     * @const string Tipo "create" para la transacción.
     */
    const TX_CREATE = 'CREATE';
    /**
     * @const string Tipo "charge" para la transacción.
     */
    const TX_CHARGE = 'CHARGE';
    /**
     * @const string Tipo "authorization" para la transacción.
     */
    const TX_AUTHORIZATION = 'AUTHORIZATION';
    /**
     * @const string Tipo "capture" para la transacción.
     */
    const TX_CAPTURE = 'CAPTURE';
    /**
     * @const string Tipo "fund" para la transacción.
     */
    const TX_FUND = 'FUND';
    /**
     * @const string Tipo "moneda dolar" para la transacción.
     */
    const CURRENCY_USD = 'USD';
    /**
     * @const string Tipo "locale" para la transacción.
     */
    const LOCALE_ES = 'es';
    const LOCALE_EN = 'es';
    const LOCALE_PT = 'pt';

    /**
     * @var array urls para notificaciones.
     */
    protected $callback_urls = [
     'ipn' => '', // url notificación de pago
     'success' => '', // url notificación caso de éxito de la operación
     'fail' => '', // url notificación en caso de falla de la operaciñón
   ];

    /**
     * @var string El tipo de la transacción.
     */
    protected $type = null;

    /**
     * @var array urls para notificaciones.
     */
    protected $id = null;
    /**
     * @var string El ID o código interno utilizado por el sistema interno de la
     *             agencia.
     */
    protected $internal_id = null;
    /**
     * @var string La moneda en la cual se realiza la transacción (ISO 4217).
     *             Código de tres letras.
     */
    protected $currency = self::CURRENCY_USD;
    /**
     * @var array Los items de facturación asociados a la transacción.
     */
    protected $invoicing_items = [];
    /**
     * @var mixed. float o decimal en formato string. Representa el subtotal
     *             de la transacción.
     */
    protected $subtotal = 0;
    /**
     * @var AluPays\Entity\Booking los datos de la reserva asociada a la
     *                             transacción.
     */
    protected $booking = null;
    /**
     * @var AluPays\Entity\Listing los datos del anuncio asociado a la transacción.
     */
    protected $listing = null;

    protected $nonce = null;

    protected $locale = null;

    private function validateType($type)
    {
        return (in_array(strtoupper($type), [
          self::TX_CREATE,
          self::TX_CHARGE,
          self::TX_AUTHORIZATION,
          self::TX_CAPTURE,
          self::TX_FUND
        ]));
    }

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

    private function validateLocale($locale)
    {
        return (in_array(strtolower($locale), [
          self::LOCALE_ES,
          self::LOCALE_EN,
          self::LOCALE_PT
        ]));
    }

    /**
     * @param string $internal_id
     * @param string $currency
     * @param mixed  $subtotal
     * @param string $locale
     */
    public function __construct($internal_id, $currency, $subtotal, $locale=self::LOCALE_ES)
    {
        if (!$this->validateCurrency($currency)) {
            throw new Exception('[INVALID_CURRENCY] La moneda no es válida. No se encuentra entre las monedas aceptadas.');
        }
        if (!$this->validateLocale($locale)) {
            throw new Exception('[INVALID_LOCALE] El idioma no es válido. No se encuentra entre los idiomas aceptados.');
        }
        $this->currency = strtoupper($currency);
        $this->internal_id = $internal_id;
        $this->subtotal = $subtotal;
        $this->locale = strtolower($locale);
    }

    public static function validCurrencies()
    {
      return [
        self::CURRENCY_USD
      ];
    }

    public function &setId($id)
    {
        $this->id = $id;
        return $this;
    }

    public function getId()
    {
        return $this->id;
    }

    public function &setType($type)
    {
        if (!$this->validateType($type)) {
            throw new Exception('[INVALID_TYPE] El tipo de la transacción no es válido.');
        }
        $this->type = strtoupper($type);
        return $this;
    }

    public function getType()
    {
        return $this->type;
    }

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

    public function getLocale()
    {
        return $this->locale;
    }

    public function getSubtotal()
    {
        return $this->subtotal;
    }

    public function &setInternalId($id)
    {
        $this->internal_id = $id;
        return $this;
    }

    public function getInternalId()
    {
        return $this->internal_id;
    }

    public function &setNonce($nonce)
    {
        $this->nonce = $nonce;
        return $this;
    }

    public function getNonce()
    {
        return $this->nonce;
    }

    /**
     * @param array $callback_urls
     */
    public function &setCallbackUrls(array $callback_urls)
    {
        $this->callback_urls = array_merge($this->callback_urls, $callback_urls);
        return $this;
    }

    public function getCallbakUrls()
    {
        $this->callback_urls;
    }

    /**
     * @param AluPays\Entity\InvoiceItem $invoice_item
     */
    public function &addInvoiceItem(InvoiceItem $invoice_item)
    {
        $this->invoicing_items[] = $invoice_item;
        return $this;
    }

    public function getInvoiceItems()
    {
        return $this->invoicing_items;
    }

    /**
     * @param AluPays\Entity\Booking $booking
     */
    public function &setBooking(Booking $booking)
    {
        $this->booking = $booking;
        return $this;
    }

    public function getBooking()
    {
        return $this->booking;
    }

    /**
     * @param AluPays\Entity\Listing $listing
     */
    public function &setListing(Listing $listing)
    {
        $this->listing = $listing;
        return $this;
    }

    public function getListing()
    {
        return $this->listing;
    }

    public function toArray()
    {
        $out = [
           'ipn_url' => $this->callback_urls['ipn'],
           'success_url' => $this->callback_urls['success'],
           'fail_url' => $this->callback_urls['fail'],
           'transaction' => [
              'type' => $this->type,
              'internal_id' => $this->internal_id,
              'currency' => $this->currency,
              'invoicing_items' => array_map(function ($item) {
                  return $item->toArray();
              }, $this->invoicing_items),
              'subtotal' => $this->subtotal
            ],
            'booking' => (!empty($this->booking) ? $this->booking->toArray() : ''),
            'listing' => (!empty($this->listing) ? $this->listing->toArray() : ''),
            'locale' => $this->locale
        ];
        if (!empty($this->id)) {
          $out['transaction']['id'] = $this->id;
        }
        if (!empty($this->nonce)) {
          $out['transaction']['nonce'] = $this->nonce;
        }

        return $out;
    }

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

