<?php

use Moip\Moip;
use Moip\Auth\OAuth;
use Moip\Auth\BasicAuth;

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

class ControllerPaymentWirecardLib extends ControllerPaymentPaymentInfo
{

  public $moip;

  public function __construct($registry)
  {
    parent::__construct($registry);

    $token = $this->config->get('wirecard_token');
    $key = $this->config->get('wirecard_key_access');

    if ($this->config->get('wirecard_ambiente') == Type_Environment::Tp_Sandbox) {
      $url = Moip::ENDPOINT_SANDBOX;
    } else {
      $url = Moip::ENDPOINT_PRODUCTION;
    }

    $this->moip = new Moip(new BasicAuth($token, $key), $url);

  }

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

    $language = $this->language->load('payment/wirecard');
    $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->load->dmodel('account/customer');

    $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('wirecard_order_status_waiting'), '');

    return $this->order_info;
  }

  public function getWireCardCustomer()
  {

    parent::setPaymentInfo();

    $customer = $this->moip->customers()->setOwnId(uniqid())
      ->setEmail($this->paymentInfo->getEmail())
      ->setFullname($this->paymentInfo->getNome())
      ->addAddress(Type_FormPgtoWirecardAddress::Tp_Entrega,
        $this->paymentInfo->getShippingAddress()->getRua(),
        $this->paymentInfo->getShippingAddress()->getNumero(),
        $this->paymentInfo->getShippingAddress()->getBairro(),
        $this->paymentInfo->getShippingAddress()->getCidade(),
        $this->paymentInfo->getShippingAddress()->getUf(),
        $this->paymentInfo->getShippingAddress()->getPostcode(),
        $this->paymentInfo->getShippingAddress()->getComplemento()
      );

    $customer->setPhone($this->paymentInfo->getTelefone()->ddd, $this->paymentInfo->getTelefone()->telefone);
    $customer->setTaxDocument($this->paymentInfo->getDocumento()->numero, $this->paymentInfo->getDocumento()->tipo);
    $customer->setBirthDate(ftr_geral::formatDate($this->paymentInfo->getDataNascimento(), 'en'));

    return $customer->create();
  }


  public function getWireCardOrder()
  {

    parent::setPaymentProducts();

    $order = $this->moip->orders()->setOwnId($this->order_info['order_id'])
      ->setCustomer($this->getWireCardCustomer())
      ->setShippingAmount((int)$this->currency->getValueCents($this->paymentInfo->getFrete()));

    foreach ($this->paymentInfo->getProducts() as $product) {
      $order->addItem(
        $product->getDescricao(),
        (int)$product->getQuantity(),
        $product->getModel(),
        (int)$this->currency->getValueCents($product->getPrice())
      );
    }

    if($this->paymentInfo->hasParam('price_additional')){
      $order->setAddition($this->paymentInfo->getParam('price_additional'));
    }

    if($this->paymentInfo->hasParam('price_discount')){
      $order->setDiscount($this->paymentInfo->getParam('price_discount'));
    }

    return $order;

  }


  public function setPaymentHolder(){

    $paymentHolder = new PaymentHolder();

    if(isset($this->request->post['creditcard_name']) && (!empty($this->request->post['creditcard_name']))){
      $paymentHolder->setNome($this->request->post['creditcard_name']);
    }else{
      $paymentHolder->setNome($this->order_info['firstname'].' '.$this->order_info['lastname']);
    }

    if(isset($this->request->post['data_nascimento']) && (!empty($this->request->post['data_nascimento']))){
      $paymentHolder->setDataNascimento(ftr_geral::formatDate($this->request->post['data_nascimento'], 'en'));
    }else{
      $paymentHolder->setDataNascimento($this->paymentInfo->getDataNascimento());
    }

    if(isset($this->request->post['cpf']) && (!empty($this->request->post['cpf'])) ) {
        $paymentHolder->setDocumento(Type_Document::Tp_Fisico, $this->request->post['cpf']);
    }else if(isset($this->request->post['cnpj']) && (!empty($this->request->post['cnpj'])) ){
        $paymentHolder->setDocumento(Type_Document::Tp_Juridico, $this->request->post['cnpj']);
    }else{
        $paymentHolder->setDocumento($this->paymentInfo->getDocumento()->tipo, $this->paymentInfo->getDocumento()->numero);
    }

    if(isset($this->request->post['tipo_telefone']) && isset($this->request->post['numero_telefone']) && !empty($this->request->post['numero_telefone'])){
      $numero = preg_replace("/[^0-9]/", "", $this->request->post['numero_telefone']);
      $paymentHolder->setTelefone($this->request->post['tipo_telefone'], substr($numero, 0,2), substr($numero, 2));
    }else{
      $paymentHolder->setTelefone($this->paymentInfo->getTelefone()->tipo, $this->paymentInfo->getTelefone()->ddd, $this->paymentInfo->getTelefone()->telefone);
    }

     $this->paymentInfo->setHolder($paymentHolder);

  }


  public function getWireCardHolder()
  {

    $this->setPaymentHolder();

    $holders = $this->moip->holders()->setFullname($this->paymentInfo->getHolder()->getNome());
    $holders->setPhone($this->paymentInfo->getHolder()->getTelefone()->ddd, $this->paymentInfo->getHolder()->getTelefone()->telefone);
    $holders->setTaxDocument($this->paymentInfo->getHolder()->getDocumento()->numero, $this->paymentInfo->getHolder()->getDocumento()->tipo);
    $holders->setBirthDate($this->paymentInfo->getHolder()->getDataNascimento());

    return $holders;

  }


  public function setErrorLog($msgError, $errors = array()){
    if($this->config->get('wirecard_log_error')){
      $this->log->write($msgError);
      if ($errors){
          if (is_array($errors)){
              foreach ($errors as $key => $error){
                  $this->log->write('Erro wirecard:'.PHP_EOL.print_r($error,true));
              }
          } else {
              $this->log->write('Erro wirecard:'.PHP_EOL.print_r($errors,true));
          }
      }
    }
  }


}
