<?php

$loader = $this->registry->get('load');
$loader->controller('payment/payment_info');

class ControllerPaymentGetnetLib extends ControllerPaymentPaymentInfo
{

  public function load()
  {
    $this->load->dmodel('checkout/order');

    $language = $this->language->load('payment/getnet');
    $this->data = array_merge($this->data, $language);

    $this->data['back'] = $this->url->link('checkout/checkout', '', 'SSL');
    $this->data['continue'] = $this->url->link('checkout/success');
  }

  public function getOrder()
  {

    $this->load->dmodel('checkout/order');

    $this->order_info = $this->dmodel_checkout_order->getOrder($this->session->data['order_id']);

    $this->dmodel_checkout_order->confirm($this->order_info['order_id'], $this->config->get('getnet_order_status_pending'), '');

    return $this->order_info;
  }

  public function getTransactionInfo()
  {

    parent::setPaymentInfo();
    parent::setPaymentProducts();

    $customerData = array(
        'customer_id' => $this->paymentInfo->getId(),
        'first_name' => $this->paymentInfo->getPrimeiroNome(),
        'last_name' => $this->paymentInfo->getUltimoNome(),
        'name' => $this->paymentInfo->getNome(),
        'email' => $this->paymentInfo->getEmail(),
        'document_type' =>  $this->paymentInfo->getDocumento()->tipo,
        'document_number' => $this->paymentInfo->getDocumento()->numero,
        'phone_number' => preg_replace("/[^0-9]/", "", $this->paymentInfo->getTelefone()->completo),
    );

    $customerData['billing_address'] = array(
      'postal_code' => $this->paymentInfo->getPaymentAddress()->getPostcode(),
      'street' => $this->paymentInfo->getPaymentAddress()->getRua(),
      'number' => $this->paymentInfo->getPaymentAddress()->getNumero(),
      'complement' => $this->paymentInfo->getPaymentAddress()->getComplemento() ?? '',
      'district' => $this->paymentInfo->getPaymentAddress()->getBairro(),
      'city' => $this->paymentInfo->getPaymentAddress()->getCidade(),
      'state' => $this->paymentInfo->getPaymentAddress()->getUf(),
      'country' => Type_PaisId::getNickFromConstValue(Type_PaisId::Tp_Brasil)
    );

    $shippingAddress = array(
      'postal_code' => $this->paymentInfo->getShippingAddress()->getPostcode(),
      'street' => $this->paymentInfo->getShippingAddress()->getRua(),
      'number' => $this->paymentInfo->getShippingAddress()->getNumero(),
      'complement' => $this->paymentInfo->getShippingAddress()->getComplemento() ?? '',
      'district' => $this->paymentInfo->getShippingAddress()->getBairro(),
      'city' => $this->paymentInfo->getShippingAddress()->getCidade(),
      'state' => $this->paymentInfo->getShippingAddress()->getUf(),
      'country' => Type_PaisId::getNickFromConstValue(Type_PaisId::Tp_Brasil)
    );

    $shipping = array(
        'first_name' => $this->paymentInfo->getPrimeiroNome(),
        'name' => $this->paymentInfo->getNome(),
        'email' => $this->paymentInfo->getEmail(),
        'phone_number' => preg_replace("/[^0-9]/", "", $this->paymentInfo->getTelefone()->completo),
        'address' => $shippingAddress,
    );;

    foreach ($this->paymentInfo->getProducts() as $product) {
      $productData[] = array(
        'description' => $product->getDescricao(),
        'quantity' => $product->getQuantity(),
        'price_unit' => number_format($product->getPrice(), 2, '.', '')
      );
    }

    $value = $this->paymentInfo->getParam('amount')*100;
    $transaction = array(
      'customer_ip' => $this->order_info['ip'],
      'shipping_type' => $this->order_info['shipping_method'],
      'shipping_price' => number_format($this->paymentInfo->getFrete(), 2, '.', ''),
      'amount' => intval("$value"), // Preço em centavos, essas aspas na variavel é necessário porque o PHP tem um bug pra converter float para integer :[
      'currency' => 'BRL',
    );

    if($this->paymentInfo->hasParam('price_additional')){
      $transaction['price_additional'] = number_format($this->paymentInfo->getParam('price_additional'), 2, '.', '');
    }

    if($this->paymentInfo->hasParam('price_discount')){
      $transaction['price_discount'] = number_format($this->paymentInfo->getParam('price_discount'), 2, '.', '');
    }

    $device = array(
      'ip_address' => $this->order_info['ip'],
      'device_id' => (preg_replace("/[^0-9]/", "", $this->config->get('config_cnpj')) . $this->session->data['getnet_fingerprint_id']),
    );

    $order['order_id'] = $this->order_info['order_id'];

    $data = array(
        'customer' => $customerData,
        'transaction_product' => $productData,
        'transaction' => $transaction,
        'order' => $order,
        'device' => $device,
        'shipping' => $shipping,
    );

    $billet = $this->getBilletObject($data);
    $credit_card = $this->getCreditCardObject($data);
    $debit_card = $this->getDebitCardObject($data);
    $pix = $this->getPix($data);


    return [
        'billet' => $billet,
        'credit_card' => $credit_card,
        'debit' => $debit_card,
        'pix' => $pix
    ];

  }

  private function getPix($data){
    return [
      'amount' => $data['transaction']['amount'],
      'currency' => $data['transaction']['currency'],
      'seller_id' => $this->config->get('getnet_seller_id'),
      'customer' => $data['customer'],
      'order' => $data['order'],
    ];
  }

  private function getBilletObject($data){
      return [
          'seller_id' => $this->config->get('getnet_seller_id'),
          'amount' => $data['transaction']['amount'],
          'currency' => $data['transaction']['currency'],
          'customer' => $data['customer'],
          'order' => $data['order'],
      ];
  }

  private function getCreditCardObject($data){
      return [
          'seller_id' => $this->config->get('getnet_seller_id'),
          'amount' => $data['transaction']['amount'],
          'currency' => $data['transaction']['currency'],
          'order' => $data['order'],
          'customer' => $data['customer'],
          'device' => $data['device'],
          'shippings' => [$data['shipping']],
      ];
  }

  private function getDebitCardObject($data){
    return [
      'seller_id' => $this->config->get('getnet_seller_id'),
      'amount' => isset($data['transaction']['price_discount']) ? $data['transaction']['amount'] - intval($data['transaction']['price_discount'] * 100): $data['transaction']['amount'],
      'currency' => $data['transaction']['currency'],
      'order' => $data['order'],
      'customer' => $data['customer'],
      'device' => $data['device'],
      'shippings' => [$data['shipping']],
    ];
  }
}
