<?php

class ControllerPaymentEredeRedirect extends Controller
{

	private $_tokenEnvio = array();
	private $_enderecos = array();
	private $_servicos = array();
	private $_produtos  = array();
	private $order = array();
	private $ultimoErro = "";

	public function index()
	{
		$this->_addRedeLibrary();
		$this->language->load('payment/erede');
		$this->load->model('checkout/order');
		$this->load->model('payment/erede'); 
		$this->load->model('catalog/information');
		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
		$this->order = $order_info;

		if (!empty($order_info))
		{
			//echo "<pre>";
			//var_dump($this->order);
			//die();

			$codeToken = $this->load();
			//echo "<br><br>Code Token: ".$codeToken;
          
			$this->data['codeToken'] = $codeToken;
			$this->data['text_redirect'] = $this->language->get('text_redirect');
			$this->data['url_redirect'] = $this->config->get('url_post');
		}

	   	$breadcrumbs = array(); 

      	$breadcrumbs[] = array(
        	'href'      => $this->url->link('common/home'),
        	'text'      => $this->language->get('text_home'),
        	'separator' => false
      	); 

		
      	$breadcrumbs[] = array(
      		'href'      => 'javascript:void(0)',
        	'text'      => $this->language->get('text_confirmation'),
        	'separator' => $this->language->get('text_separator')
      	);	

      	$this->data['breadcrumbs'] = $breadcrumbs;

	    $this->children = array(
			'common/header',
			'common/footer'
		);

		if ($codeToken)
		{
			$this->template = 'default/template/payment/erede_redirect.tpl';
			$this->model_checkout_order->confirm($this->session->data['order_id'], 1);
		}
		else
		{
		    $this->data['text_support']  = $this->language->get('text_support');
		    $this->data['button_orders'] = $this->language->get('button_orders');
		    $this->data['link_contact']  = $this->url->link('information/contact');
		    $this->data['link_orders']  = $this->url->link('common/home');
		    $this->data['text_error'] = $this->ultimoErro; 
			$this->template = 'default/template/error/erede.tpl';
		}

	    $this->cart->clear();
	    //$this->template = 'default/template/payment/erede_redirect.tpl';
		$this->response->setOutput($this->render());
	}


	private function _addRedeLibrary()
	{
		include_once 'catalog/controller/payment/RedeLibrary/RedeLibrary.php';
	}

	public function load()
    {

        $orderId    = $this->order['order_id'];
        $servicos 	= $this->_getServicos();
        $order      = $this->setOrder();  

        //echo "<pre>";
        //print_r($order);
        //die();

        $token      = $this->getToken($order, $orderId);
        $_codeToken = $token->token;
        $_erroToken = $token->erro;

        if ( (is_null($_codeToken) || empty($_codeToken))) 
        {
        	$this->model_checkout_order->update(7, $orderId);
        	if ($_erroToken)
        	{
        	    $this->ultimoErro = 'ERRO: Pedido não processado - '.$_erroToken;
				$this->model_payment_erede->saveLog($orderId, 'Cancelado', 
                    'ERRO: Pedido não processado - '.$_erroToken);
        	}
        	else
        	{
        	    $this->ultimoErro = 'ERRO: Pedido não processado - Não foi possível recuperar o token de acesso ao webservice da Rede. Verifique as configurações do módulo.';
				$this->model_payment_erede->saveLog($orderId, 'Cancelado', 
                    'ERRO: Pedido não processado - Não foi possível recuperar o token de acesso ao webservice da Rede. Verifique as configurações do módulo.');
        	}
        }

        return $_codeToken;
    }

    public function getToken($order, $orderId)
    {
    	$retorno = null;

        try
        {
            $client = new SoapClient($this->config->get('url_webservice'), 
            	array(
			        'trace'        => 1,
			        'exceptions'   => 1,
			        'style'        => SOAP_DOCUMENT,
			        'use'          => SOAP_LITERAL,
			        'soap_version' => SOAP_1_1,
			        'encoding'     => 'UTF-8',
			        'connection_timeout' => 25,
		        )
		    );

            $webService = $client->setupPlugin($order);
            $wsResult = $webService->setupPluginResult;

            $retorno = new TokenRetorno($wsResult);
        }    
        catch (Exception $e)
        {
        	$this->model_checkout_order->update($orderId, 7);
	            
            $exception = 'Caught exception: '.$e->getMessage();
			$this->model_payment_erede->saveLog($orderId, 'Cancelado', 'ERRO: Pedido não processado - '.mysql_real_escape_string($exception));
			$this->redirect($this->url->link('payment/erede_retorno'));

        }        
        return $retorno;
    }

    private function _getEnderecoPrincipal()
	{
		$enderecoPrincipal              = new Endereco();

		$enderecoPrincipal->TipoEndrCli = 'P';
		$enderecoPrincipal->EndrCli     = html_entity_decode($this->order['shipping_address_1'], ENT_QUOTES, 'UTF-8');
		$enderecoPrincipal->ComplEndr   = html_entity_decode($this->order['shipping_address_2'], ENT_QUOTES, 'UTF-8');   
		$enderecoPrincipal->Cep         = $this->_trataCep(html_entity_decode($this->order['shipping_postcode'], ENT_QUOTES, 'UTF-8')); 
		$enderecoPrincipal->Cidade      = html_entity_decode($this->order['shipping_zone'], ENT_QUOTES, 'UTF-8');
		$enderecoPrincipal->Estado 	 	= html_entity_decode($this->order['shipping_zone_code'], ENT_QUOTES, 'UTF-8');
		$enderecoPrincipal->Pais 		= html_entity_decode($this->order['shipping_iso_code_2'], ENT_QUOTES, 'UTF-8');

		return $enderecoPrincipal;
	}

	private function _getEnderecoEntrega()
	{
		$enderecoEntrega              = new Endereco();

		$enderecoEntrega->TipoEndrCli = 'E';
		$enderecoEntrega->EndrCli     = html_entity_decode($this->order['shipping_address_1'], ENT_QUOTES, 'UTF-8');
		$enderecoEntrega->ComplEndr   = html_entity_decode($this->order['shipping_address_2'], ENT_QUOTES, 'UTF-8');   
		$enderecoEntrega->Cep         = $this->_trataCep(html_entity_decode($this->order['shipping_postcode'], ENT_QUOTES, 'UTF-8')); 
		$enderecoEntrega->Cidade      = html_entity_decode($this->order['shipping_zone'], ENT_QUOTES, 'UTF-8');
		$enderecoEntrega->Estado 	  = html_entity_decode($this->order['shipping_zone_code'], ENT_QUOTES, 'UTF-8');
		$enderecoEntrega->Pais 		  = html_entity_decode($this->order['shipping_iso_code_2'], ENT_QUOTES, 'UTF-8');

		return $enderecoEntrega;
	}


	private function _getEnderecoCobranca()
	{
		$enderecoCobranca              = new Endereco();

		$enderecoCobranca->TipoEndrCli = 'C';
		$enderecoCobranca->EndrCli     = html_entity_decode($this->order['payment_address_1'], ENT_QUOTES, 'UTF-8');
		$enderecoCobranca->ComplEndr   = html_entity_decode($this->order['payment_address_2'], ENT_QUOTES, 'UTF-8');   
		$enderecoCobranca->Cep         = $this->_trataCep(html_entity_decode($this->order['payment_postcode'], ENT_QUOTES, 'UTF-8')); 
		$enderecoCobranca->Cidade      = html_entity_decode($this->order['payment_zone'], ENT_QUOTES, 'UTF-8');
		$enderecoCobranca->Estado 	   = html_entity_decode($this->order['payment_zone_code'], ENT_QUOTES, 'UTF-8');
		$enderecoCobranca->Pais 	   = html_entity_decode($this->order['payment_iso_code_2'], ENT_QUOTES, 'UTF-8');

		return $enderecoCobranca;
	}

	private function _getEnderecoBoleto()
	{
		$enderecoBoleto              = new Endereco();

		$enderecoBoleto->TipoEndrCli = 'B';
		$enderecoBoleto->EndrCli     = html_entity_decode($this->order['payment_address_1'], ENT_QUOTES, 'UTF-8');
		$enderecoBoleto->ComplEndr   = html_entity_decode($this->order['payment_address_2'], ENT_QUOTES, 'UTF-8');   
		$enderecoBoleto->Cep         = $this->_trataCep(html_entity_decode($this->order['payment_postcode'], ENT_QUOTES, 'UTF-8')); 
		$enderecoBoleto->Cidade      = html_entity_decode($this->order['payment_zone'], ENT_QUOTES, 'UTF-8');
		$enderecoBoleto->Estado 	 = html_entity_decode($this->order['payment_zone_code'], ENT_QUOTES, 'UTF-8');
		$enderecoBoleto->Pais 		 = html_entity_decode($this->order['payment_iso_code_2'], ENT_QUOTES, 'UTF-8');

		return $enderecoBoleto;
	}

    private function _getServicos()
    {
    	if ($this->config->get('servicos_Credito') == 'on')
		{
			$servico1 = new Servico();
			$servico1->codTipoServicoConf = 1;
			$this->_servicos[] = $servico1;
		}

		if ($this->config->get('servicos_Debito') == 'on')
		{
			$servico2 = new Servico();
			$servico2->codTipoServicoConf = 2;
			$this->_servicos[] = $servico2;
		}

		if ($this->config->get('servicos_Boleto') == 'on')
		{
			$servico3 = new Servico();
			$servico3->codTipoServicoConf = 601;
			$this->_servicos[] = $servico3;
		}

		if ($this->config->get('servicos_Analise') == 'on')
		{
			$servico4 = new Servico();
			$servico4->codTipoServicoConf = 602;
			$this->_servicos[] = $servico4;
		}

		return $this->_servicos;
    }

    private function _getProdutos()
	{
		$itens = array();
		$this->load->model('catalog/category');

		foreach ($this->cart->getProducts() as $product) 
		{
		    $produto                      		  = new ProdutoRisco();
            $produto->CodProdEstabRisco           = trim(substr($product['product_id'], 0, 20));
            $produto->DesProdEstabRisco           = trim(substr($product['name'], 0, 50));
            $produto->QuantidadeProdEstabRisco    = $product['quantity'];
            $produto->ValorUnitarioProdEstabRisco = number_format($product['price'], 2, '.', '');

            $categories = $this->model_payment_erede->getProductCategories($product['product_id']);
            foreach ($categories as $category_id) {
				$category_info = $this->model_catalog_category->getCategory($category_id);
				
				if ($category_info) 
				{
					$produto->CategoriaProdEstabRisco = $category_info['name'];
				}
			}

            if ($this->model_payment_erede->getRiscoProduto((int)$product['product_id']) != '')
            {
            	$produto->CodTipoProdRisco = ucfirst($this->model_payment_erede->getRiscoProduto((int)$product['product_id']));
            }
            else
            {
            	$produto->CodTipoProdRisco = 'Low';
            }

        	array_push($itens, $produto);
		}

		return $itens;
	}


    public function setOrder()
    {
    	$setup = new TokenSetup();
        $this->_tokenEnvio = $setup->load($this->_enderecos, $this->_produtos, $this->_servicos);

        $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
 
		if ($this->order)
        {
            $this->_tokenEnvio->NumPdv           = $this->config->get('numero_estabelecimento');
            $this->_tokenEnvio->ValorTransacao   = $this->currency->format($this->order['total'], $this->order['currency_code'] , false, false);
            $this->_tokenEnvio->NumPedido        = str_pad((string)$this->session->data['order_id'], 6, "0", STR_PAD_LEFT);
            $this->_tokenEnvio->UrlRetorno       = HTTPS_SERVER.htmlentities($this->config->get('url_retorno'));
            $this->_tokenEnvio->IpCliente        = $_SERVER['REMOTE_ADDR'];
            $this->_tokenEnvio->CidadeEstab      = $this->config->get('cidade_estabelecimento');
            
            /*if ($this->config->get('servicos_Credito') == 'on')
            {
            	if(intval($this->config->get('parcela_minima')) > 0)
            	{
	                $quantidadeParcelas = floor($this->_tokenEnvio->ValorTransacao / $this->config->get('parcela_minima'));
	                if ($quantidadeParcelas > 12)
	                	$quantidadeParcelas = 12;
	                $this->_tokenEnvio->QtdParcela = min($quantidadeParcelas, $this->config->get('qtd_parcelas'));
            	}
                else
                {
                	$this->_tokenEnvio->QtdParcela = $this->config->get('qtd_parcelas');
                }
            }
			  Comentado por matheus para carregar conforme valor. (a pedido da nipocenter)
			*/
			
			$quantidadeParcelas = 1;
			
			if ($this->order['total'] > 700){
			  $quantidadeParcelas = 2;
			}
			
			if ($this->order['total'] > 1200){
			  $quantidadeParcelas = 3;
			}
					
			$this->_tokenEnvio->QtdParcela = $quantidadeParcelas;
           
            if ($this->config->get('servicos_Boleto') == 'on')
            {
            	$end = $this->_getEnderecoBoleto();

                $this->_tokenEnvio->NomeCliente      = html_entity_decode($this->order['payment_firstname'], ENT_QUOTES, 'UTF-8');
                $this->_tokenEnvio->SobrenomeCliente = html_entity_decode($this->order['payment_lastname'], ENT_QUOTES, 'UTF-8');
                $this->_tokenEnvio->Tel1Cliente 	 = html_entity_decode($this->order['telephone'], ENT_QUOTES, 'UTF-8');
                $this->_tokenEnvio->PercJuroDia      = str_replace(',', '.', $this->config->get('juros_por_dia')) / 100;
                $this->_tokenEnvio->Multa            = str_replace(',', '.', $this->config->get('multa_atraso'));
                $this->_tokenEnvio->DatVctoBoleto    = date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $this->config->get('qtd_dias_vencimento') . 'days'));
                $this->_tokenEnvio->BancoCedente     = $this->config->get('banco_cedente');
                $this->_tokenEnvio->InstrPgmnBoleto  = $this->config->get('instrucoes_pagamento');
                $this->_tokenEnvio->NotaPgmnBoleto   = str_replace("\n", '<br />', $this->config->get('notas_pagamento'));
                $this->_enderecos[] = $end;
            }

            if ($this->config->get('servicos_Analise') == 'on')
            {
                $this->_tokenEnvio->NomeCliente      = html_entity_decode($this->order['payment_firstname'], ENT_QUOTES, 'UTF-8');
                $this->_tokenEnvio->SobrenomeCliente = html_entity_decode($this->order['payment_lastname'], ENT_QUOTES, 'UTF-8');
                //$this->_tokenEnvio->DatNascCliente   = date('Y-m-d');
                //$this->_tokenEnvio->NumDocCliente    = '12345678912';
                if(strpos($this->config->get('url_webservice'), "scommerce") === false){
				   $this->_tokenEnvio->EmailCliente = $this->order['email'];
				}
                $this->_enderecos[] = $this->_getEnderecoPrincipal();
                $this->_enderecos[] = $this->_getEnderecoEntrega();
                $this->_enderecos[] = $this->_getEnderecoCobranca();
                $this->_tokenEnvio->lstProdutoRisco = $this->_getProdutos();
            }

            $this->_tokenEnvio->lstEndereco = $this->_enderecos;
            $this->_tokenEnvio->lstServico = $this->_servicos;
        }
        return array('setupFe' => $this->_tokenEnvio);
    }

    private function _trataCep($cep)
    {
    	if ($cep)
    	{
    		$cep = str_replace('-', '', $cep);
    		return $cep;
    	}
    }

}
?>