<?php
class ControllerPaymentPayU extends Controller {
  protected function index() {

    $this->language->load('payment/payu');

    $this->data['button_confirm']   = $this->language->get('button_confirm_pd');

    if ($this->config->get('payu_modoteste') == 1){
      $this->data['action'] = 'https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/';
    }else{
      $this->data['action'] = 'https://checkout.payulatam.com/ppp-web-gateway-payu/';
    }
    
    $this->data['text_information'] =  $this->language->get('text_information');
    $this->data['text_wait']        = $this->language->get('text_wait');

    $this->load->dmodel('checkout/order');
    $order_info = $this->dmodel_checkout_order->getOrder($this->session->data['order_id']);

    // valor do frete será 0 pois o módulo enviará de forma diferente este valor para o Pagamento Digital
    $this->data['shipping_total'] = 0;

    $this->data['products'] = array();

    $this->data['amount'] = $this->currency->format($order_info['total'], $order_info['currency_code'], false, false);
    $this->data['merchantId']    = $this->config->get('payu_merchantId');
    $this->data['accountId']  = $this->config->get('payu_accountId');

    /*if($this->config->get('payu_posfixo') != ""){
      $this->data['referenceCode'] = $this->session->data['order_id'];//."_".$this->config->get('payu_posfixo');
    }
    else{*/
    $this->data['referenceCode'] = $this->session->data['order_id'];
    
    $this->data['description'] = 'Pagamento pedido: '.$this->session->data['order_id']; 

    $this->load->model('localisation/zone');
    if ($this->cart->hasShipping()) {
      $zone = $this->model_localisation_zone->getZone($order_info['shipping_zone_id']);
      $this->data['buyerFullName']    = html_entity_decode($order_info['shipping_firstname'].' '.$order_info['shipping_lastname'], ENT_QUOTES, 'UTF-8');
      $this->data['shippingAddress']  = html_entity_decode($order_info['shipping_address_1'], ENT_QUOTES, 'UTF-8');
      $this->data['shippingCity']     = html_entity_decode($order_info['shipping_city'], ENT_QUOTES, 'UTF-8');
      $this->data['zipCode']          = preg_replace ("/[^0-9]/", '', $order_info['shipping_postcode']);
      $this->data['buyerEmail']       = html_entity_decode($order_info['email'], ENT_QUOTES, 'UTF-8');
      $this->data['telephone']        = html_entity_decode($order_info['telephone'], ENT_QUOTES, 'UTF-8');
    }
    else{
      $zone = $this->model_localisation_zone->getZone($order_info['payment_zone_id']);
      $this->data['buyerFullName']    = html_entity_decode($order_info['payment_firstname'].' '.$order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
      $this->data['shippingAddress']  = html_entity_decode($order_info['payment_address_1'], ENT_QUOTES, 'UTF-8');
      $this->data['shippingCity']     = html_entity_decode($order_info['payment_city'], ENT_QUOTES, 'UTF-8');
      $this->data['zipCode']          = preg_replace ("/[^0-9]/", '', $order_info['payment_postcode']);
      $this->data['buyerEmail']       = html_entity_decode($order_info['email'], ENT_QUOTES, 'UTF-8');
      $this->data['telephone']        = html_entity_decode($order_info['telephone'], ENT_QUOTES, 'UTF-8');
    }

    
    $this->data['tax']             = 0;
    $this->data['taxReturnBase']   = 0;
    $this->data['shippingCountry'] = 'BRA';
    $this->data['currency']        = 'BRL';
    $this->data['responseUrl']     = $this->url->link('payment/payu/callback');
    $this->data['confirmationUrl'] = $this->url->link('payment/payu/callback');

    $this->data['payu_modoteste']  = $this->config->get('payu_modoteste');

    $parametros               = $this->config->get('payu_apikey').'~'.$this->data['merchantId'].'~'.$this->data['referenceCode'].'~'.$this->data['amount'].'~'.$this->data['currency'];
    $this->data['signature'] = md5($parametros); 

    if ( isset($this->session->data['order_id']) && ( ! empty($this->session->data['order_id']))  ) {
    	$this->session->data['last_order_id'] = $this->session->data['order_id'];
    }
    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/payu.twig')) {
      $this->template = $this->config->get('config_template') . '/template/payment/payu.tptwigl';
    }
    else{
      $this->template = 'default/template/payment/payu.twig';
    }
    $this->load->model('checkout/order');
    $this->dmodel_checkout_order->confirm($this->session->data['order_id'], $this->config->get('payu_order_pendente'));
    $this->render();
  }

  public function confirm() {

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

    $this->dmodel_checkout_order->confirm($this->session->data['order_id'], $this->config->get('payu_order_pendente'));

    $this->cart->clear();

    unset($this->session->data['shipping_method']);
    unset($this->session->data['shipping_methods']);
    unset($this->session->data['payment_method']);
    unset($this->session->data['payment_methods']);
    unset($this->session->data['guest']);
    unset($this->session->data['comment']);
    unset($this->session->data['order_id']);
    unset($this->session->data['coupon']);
    unset($this->session->data['voucher']);
    unset($this->session->data['vouchers']);

  }

  public function callback() {
    $this->load->type('tipopayu');
    $this->load->model('checkout/order');
	$this->load->dmodel('checkout/order');
    $this->language->load('payment/payu');
    if (isset($_GET['merchantId'])){
      $dataRetorno = $_GET;
    }else{
      $dataRetorno = $_POST;
    }
    if (isset($dataRetorno['transactionState'])){
      $parametros  = $this->config->get('payu_apikey').'~'.$dataRetorno['merchantId'].'~'.$dataRetorno['referenceCode'].'~'.number_format($dataRetorno['TX_VALUE'], 1, '.', '').'~'.$dataRetorno['currency'].'~'.$dataRetorno['transactionState'];
      $signature = md5($parametros);
       
      if ($dataRetorno['signature'] == $signature){
        $idPedido = $dataRetorno['referenceCode'];
        $mensagem = Type_PayuStatusTransacao::getNickFromConstValue($dataRetorno['transactionState']);
        $update_status_alert =  $this->config->get('payu_update_status_alert');
        switch($dataRetorno['transactionState']){
          case Type_PayuStatusTransacao::Tp_PayuAprovada : $payu_status_id  = $this->config->get('payu_order_aprovado');
          break;
          case Type_PayuStatusTransacao::Tp_PayuPendente : $payu_status_id  = $this->config->get('payu_order_pendente');
          break;
          case Type_PayuStatusTransacao::Tp_PayuRejeitada : $payu_status_id  = $this->config->get('payu_order_rejeitado');
          break;
          case Type_PayuStatusTransacao::Tp_PayuErro : $payu_status_id  = $this->config->get('payu_order_erro');
          break;
          case Type_PayuStatusTransacao::Tp_PayuExpirada : $payu_status_id  = $this->config->get('payu_order_expirado');
          break;                        
          default: $payu_status_id  = $this->config->get('payu_order_erro'); 
        }
        $this->dmodel_checkout_order->update($idPedido, $payu_status_id, $mensagem);
      }
    }
    if (isset($_GET['merchantId'])){ //Só redireciona no get, pois o post é utilizado para atualização das informações
      $this->session->data['mensagem_payu'] = sprintf($this->language->get('text_mensagem_success'), $idPedido);
      $this->redirect($this->url->link('checkout/success'));
    }
  }


}
