<?php
class ControllerPaymentCieloIntegradoFutura extends Controller {
	public function index() {
		$this->load->dmodel('checkout/order');

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

		$data['merchant_id']          = trim($this->config->get('cielointegradofutura_id'));
		$data['soft']                 = $this->somente_letras_cielo(strtoupper($this->config->get('cielointegradofutura_soft')));
		$order_info                   = $this->dmodel_checkout_order->getOrder($this->session->data['order_id']);
		$data['email']                = $order_info['email'];
		$data['firstname']            = $order_info['payment_firstname'];
		$data['lastname']             = $order_info['payment_lastname'];
		$data['address']              = $order_info['payment_address_1'];
		$data['address2']             = $order_info['payment_address_2'];
		$data['phone_number']         = $order_info['telephone'];
		$data['postal_code']          = $order_info['payment_postcode'];
		$data['city']                 = $order_info['payment_city'];
		$data['state']                = $order_info['payment_zone'];
		$data['country']              = $order_info['payment_iso_code_3'];
		$data['total']                = $order_info['total'];
		$data['shipping_firstname']   = $order_info['shipping_firstname'];
		$data['shipping_lastname']    = $order_info['shipping_lastname'];
		$data['shipping_address_1']   = $order_info['shipping_address_1'];
		$data['shipping_address_2']   = $order_info['shipping_address_2'];
		$data['shipping_numero']      = $order_info['shipping_numero'];
		$data['shipping_complemento'] = $order_info['shipping_complemento'];
		$data['shipping_postcode']    = $order_info['shipping_postcode'];
		$data['shipping_city']        = $order_info['shipping_city'];
		$data['shipping_zone']        = $this->retornaSigla($order_info['shipping_zone']);

		if(strlen($order_info['shipping_postcode'])<8){
			$data['exibir_btn'] = false;
		}else{
			$data['exibir_btn'] = true;
		}

		//anti fraude
		$data['fraude'] = 'FALSE';
		$anti_fraude = $this->config->get('cielointegradofutura_fraude');
		$anti_fraude_total = $this->config->get('cielointegradofutura_total_fraude');
		if($anti_fraude && $order_info['total']>=$anti_fraude_total){
			$data['fraude'] = 'TRUE';
		}

		$fiscal = '';
		if(isset($order_info['cpf'])){
			$fiscal = preg_replace('/\D/', '', $order_info['cpf']);
		} else if(isset($order_info['cnpj'])){
			$fiscal = preg_replace('/\D/', '', $order_info['cnpj']);
		}
		$data['fiscal'] = $fiscal;

		$data['desconto']            = $this->getDescontos();
		$data['frete']               = $this->getFrete();
		$data['shipping_tipo_frete'] = ($data['frete']['value']>0)?2:5;
		$data['taxas']               = $this->getTaxas();
		$data['produtos']            = $this->cart->getProducts();
		$data['pedido']              = $this->session->data['order_id'];

		//session do pedido para o retorno
		$_SESSION['pedido_processar'] = $this->session->data['order_id'];

		//fix
		$this->data = $data;
		// Fix do Fix
		$this->app();

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/cielointegradofutura.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/payment/cielointegradofutura.tpl';
		} else {
			$this->template = 'default/template/payment/cielointegradofutura.tpl';
		}
		$this->render('payment/cielointegradofutura');
	}

	public function getDescontos(){
		$query = $this->db->query("SELECT SUM(value) AS desconto FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$this->session->data['order_id'] . "' AND value < 0");
		return abs($query->row['desconto']);
	}

	public function getFrete(){
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$this->session->data['order_id'] . "' AND code = 'shipping'");
		return $query->row;
	}

	public function getTaxas(){
		$query = $this->db->query("SELECT SUM(value) AS taxa FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$this->session->data['order_id'] . "' AND code = 'tax'");
		return abs($query->row['taxa']);
	}

	public function somente_letras_cielo($t){
		return preg_replace("/[^0-9a-zA-Z]+/", "", $t);
	}

	public function retorno(){
		$this->load->dmodel('checkout/order');
		$this->load->type('tipocielocheckout');
		$pedido_retorno = isset($this->session->data['order_id'])?$this->session->data['order_id']:$_SESSION['pedido_processar'];

		//pedido
		$data['pedido'] = $this->dmodel_checkout_order->getOrder($pedido_retorno);

        $payment_info = $this->db->query("SELECT
        CASE
            WHEN NOT cc.payment_credit_card_id IS null THEN 'CC'
            WHEN NOT bt.payment_bank_transfer_id IS null THEN 'TO'
            WHEN NOT bl.payment_billet_id IS null THEN 'BB'
        END AS tipo_pagamento,
        CASE
            WHEN NOT cc.payment_credit_card_id IS null THEN cc.status_pagamento
            WHEN NOT bt.payment_bank_transfer_id IS null THEN bt.status_pagamento
            WHEN NOT bl.payment_billet_id IS null THEN bl.status_pagamento
        END AS status_pagamento,
        cc.qtd_parcela,
        cc.cartao_mascara,
		cc.cartao_bandeira,
		cc.tid

        FROM oc_order o
        LEFT JOIN oc_payment_credit_card cc ON cc.order_id = o.order_id
        LEFT JOIN oc_payment_bank_transfer bt ON bt.order_id = o.order_id
        LEFT JOIN oc_payment_billet bl ON bl.order_id = o.order_id
		WHERE o.order_id = " . (int)$pedido_retorno . " limit 1")->row;

		//status pedido

		if ($payment_info['tipo_pagamento']=='CC'){
			$data['status'] = array(
				'tid'  => $payment_info['tid'],
				'meio' => Type_CieloCheckoutBandeira::getNickFromConstValue($payment_info['cartao_bandeira']),
				'bin'  => $payment_info['cartao_mascara'],
				'parcelas' => $payment_info['qtd_parcela'],
			);
		}

		$data['status']['tipo'] = $payment_info['tipo_pagamento'];
		$data['status']['tipo_description'] = Type_CieloCheckoutPagamento::getNickFromConstValue($payment_info['tipo_pagamento']);
		$data['status']['status_pagamento'] = Type_CieloCheckoutStatusPgto::getNickFromConstValue($payment_info['status_pagamento']);

		$data['status_nomes'] = Type_CieloCheckoutStatusPgto::getEnumList();
		$data['meios_cartao'] = Type_CieloCheckoutBandeira::getEnumList();
		$data['tipos']        = Type_CieloCheckoutPagamento::getEnumList();

		$data['link_pedido'] = $this->url->link('account/order/info','order_id='.$pedido_retorno.'');
		$data['link_pedidos'] = $this->url->link('account/order');
		$this->document->setTitle('Resultado da Transa&ccedil;&atilde;o Cielo');
		$this->document->setDescription('');
		$this->document->setKeywords('');
		$data['iframe'] = $this->url->link('checkout/success','','SSL');

		$data['mostra_pedido'] = false;
		if (isset($data['pedido']) && !empty($data['pedido']) && isset($data['pedido']['firstname'])) {
			$data['nome'] = $data['pedido']['firstname'];
			$data['mostra_pedido'] = $data['pedido']['order_status_id'] > 0;
		}

		//fix
		$this->data = $data;

		$this->template = 'default/template/payment/cielointegradofutura_cupom.tpl';
		$this->children = array(
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'
		);
		$this->response->setOutput($this->render('payment/cielointegradofutura_cupom'));
	}

	public function notificacao() {
		//checa o post
		$this->request->post['order_number'] = $_REQUEST['order_number'];
		$this->request->post['amount'] = $_REQUEST['amount'];
		$this->request->post['payment_status'] =  $_REQUEST['payment_status'];

		if (isset($this->request->post['order_number']) && isset($this->request->post['amount']) && isset($this->request->post['payment_status'])) {
			$order_id = $this->request->post['order_number'];
		} else {
			die('=(');
		}

		$this->load->dmodel('checkout/order');
		$this->load->dmodel('payment/payment_info');
		$this->load->type('tipocielocheckout');

		$order_info = $this->dmodel_checkout_order->getOrder($order_id);
		if ($order_info) {

			//checa o valor e o mesmo enviado no form
			$dif = abs($this->request->request['amount']-number_format($order_info['total'], 2, '', ''));
			if($dif<=10){
				$verified = true;
			}else{
				$verified = false;
			}

			//se verificado muda o status
			if ($verified) {

				//tid
				$tid = isset($_REQUEST['tid'])? $_REQUEST['tid'] : '' ;
				$dataSend = array();

				$dataSend['tid'] = $tid;
				$message_payment = $tid;

				$dataSend['fraude'] =  @$_REQUEST['payment_antifrauderesult'];

				$timestamp = strtotime(@$_REQUEST['created_date']); // Gera o timestamp de $data_mysql
				$created_date = date('Y-m-d', $timestamp); // Resultado: 12/03/2009
				$dataSend['data_pagamento'] = $created_date;
				$dataSend['status_pagamento'] =  $this->request->request['payment_status'];
				$dataSend['order_id'] = $order_id;
				$dataSend['valor_pagamento'] = number_format( ($this->request->request['amount']/100), 2, '.', '');

				switch ($_REQUEST['payment_method_type']) {
					case Type_CieloCheckoutPagamento::Tp_Cartao :
						$dataSend['tipo_cartao'] = Type_Card::Tp_Credito;
						$dataSend['cartao_bandeira'] = @$_REQUEST['payment_method_brand'];
						$dataSend['cartao_bandeira_text'] = Type_CieloCheckoutBandeira::getNickFromConstValue($dataSend['cartao_bandeira']);
						$dataSend['cartao_mascara'] = @$_REQUEST['payment_maskedcreditcard'];
						$dataSend['qtd_parcela'] = @$_REQUEST['payment_installments'];
						$message_payment = $tid . " ". Type_CieloCheckoutBandeira::getNickFromConstValue($dataSend['cartao_bandeira']) ." (".$dataSend['cartao_mascara'].") em ".$dataSend['qtd_parcela']."x";
						$this->dmodel_payment_payment_info->addPaymentCreditCard($dataSend);
					break;
					case Type_CieloCheckoutPagamento::Tp_Boleto :
						$dataSend['link_digitavel']  =  @$_REQUEST['payment_boletonumber'];
						$dataSend['banco_emissor']  =  @$_REQUEST['payment_method_bank'];
						$dataSend['data_expiracao'] =  @$_REQUEST['payment_boletoexpirationdate'];
						$this->dmodel_payment_payment_info->addPaymentBillit($dataSend);
					break;
					case Type_CieloCheckoutPagamento::Tp_Transferencia :
						$dataSend['banco_pagamento'] =  @$_REQUEST['payment_method_bank'];
						$this->dmodel_payment_payment_info->addPaymentBankTransfer($dataSend);
					break;
					case Type_CieloCheckoutPagamento::Tp_Debito :
						$dataSend['tipo_cartao']   = Type_Card::Tp_Debito;
						$dataSend['qtd_parcela']   = 1;
						$dataSend['banco_emissor'] =  @$_REQUEST['payment_method_bank'];
						$this->dmodel_payment_payment_info->addPaymentCreditCard($dataSend);
					break;
			
					// NEW
					// case Type_CieloCheckoutPagamento::Tp_Pix :
					// 	$dataSend['payment_pix_id']  =  @$_REQUEST['Paymentid'];
					// 	$dataSend['link_qrcodeurl']  =  @$_REQUEST['QrCodeString'];
					// 	$dataSend['data_expiracao'] =  @$_REQUEST['payment_boletoexpirationdate']
					// 	$this->dmodel_payment_payment_info->addPaymentPix($dataSend);
					// break;
				}

				$tipo_nome = Type_CieloCheckoutPagamento::getDescriptionFromConstValue($_REQUEST['payment_method_type']);

				switch($dataSend['status_pagamento']) {
					case Type_CieloCheckoutStatusPgto::Tp_Pendente :
					$message_payment = "Pedente ".$tipo_nome." - ".$message_payment;
					$this->dmodel_checkout_order->confirm($order_id, $this->config->get('cielointegradofutura_pe'), $message_payment);
					break;
					case Type_CieloCheckoutStatusPgto::Tp_Pago :
					$message_payment = "Pago ".$tipo_nome." - ".$message_payment;
					$this->dmodel_checkout_order->confirm($order_id, $this->config->get('cielointegradofutura_pg'), $message_payment);
					break;
					case Type_CieloCheckoutStatusPgto::Tp_Negado :
					$message_payment = "Negado ".$tipo_nome." - ".$message_payment;
					$this->dmodel_checkout_order->confirm($order_id, $this->config->get('cielointegradofutura_ne'), $message_payment);
					break;
					case Type_CieloCheckoutStatusPgto::Tp_Cancelado :
					$message_payment = "Cancelado ".$tipo_nome." - ".$message_payment;
					$this->dmodel_checkout_order->confirm($order_id, $this->config->get('cielointegradofutura_ca'), $message_payment);
					break;
					case Type_CieloCheckoutStatusPgto::Tp_Autorizado :
					$message_payment = "Autorizado ".$tipo_nome." - ".$message_payment;
					$this->dmodel_checkout_order->confirm($order_id, $this->config->get('cielointegradofutura_au'), $message_payment);
					break;
				}
				echo '<status>OK</status>';
			}else{
				$this->log->write("[Checkout Cielo] Total ".number_format(($this->request->request['amount']/100), 2, '.', '')." divergente do valor original ".number_format($order_info['total'], 2, '.', '')." no pedido ".$order_id."");
				echo '<status>NOK</status>';
			}
		}
	}


	public function status() {
		//checa o post
		if (isset($this->request->post['order_number']) && isset($this->request->post['amount']) && isset($this->request->post['payment_status'])) {
			$order_id = $this->request->post['order_number'];
		} else {
			die('=(');
		}


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

		if ($order_info) {

			//checa o valor e o mesmo enviado no form
			$dif = abs($this->request->post['amount']-number_format($order_info['total'], 2, '', ''));
			if($dif<=10){
				$verified = true;
			}else{
				$verified = false;
			}

			$dataSend['status_id'] =  $this->request->request['payment_status'];
			$dataSend['order_id'] = $order_id;

			switch ($_REQUEST['payment_method_type']) {
				case Type_CieloCheckoutPagamento::Tp_Cartao :
				case Type_CieloCheckoutPagamento::Tp_Debito :
					$this->dmodel_payment_payment_info->updatePaymentCreditCard($dataSend);
				break;
				case Type_CieloCheckoutPagamento::Tp_Boleto :
					$this->dmodel_payment_payment_info->updatePaymentBillet($dataSend);
				break;
				case Type_CieloCheckoutPagamento::Tp_Transferencia :
					$this->dmodel_payment_payment_info->updatePaymentBankTransfer($dataSend);
				break;
			}

			//se verificado muda o status
			$status_pedido_atual = $order_info['order_status_id'];
			$tid = isset($_REQUEST['tid'])?'TID: '.$_REQUEST['tid'].'':'';

			if ($verified) {
				switch($dataSend['status_id']) {

					case Type_CieloCheckoutStatusPgto::Tp_Pendente :
					if($status_pedido_atual!=$this->config->get('cielointegradofutura_pe')){
						$this->dmodel_checkout_order->update($order_id, $this->config->get('cielointegradofutura_pe'), $tid);
					}
					break;

					case Type_CieloCheckoutStatusPgto::Tp_Pago :
					if($status_pedido_atual!=$this->config->get('cielointegradofutura_pg')){
						$this->dmodel_checkout_order->update($order_id, $this->config->get('cielointegradofutura_pg'), $tid);
					}
					break;

					case Type_CieloCheckoutStatusPgto::Tp_Negado :
					if($status_pedido_atual!=$this->config->get('cielointegradofutura_ne')){
						$this->dmodel_checkout_order->update($order_id, $this->config->get('cielointegradofutura_ne'), $tid);
					}
					break;

					case Type_CieloCheckoutStatusPgto::Tp_Cancelado :
					if($status_pedido_atual!=$this->config->get('cielointegradofutura_ca')){
						$this->dmodel_checkout_order->update($order_id, $this->config->get('cielointegradofutura_ca'), $tid);
					}
					break;

					case Type_CieloCheckoutStatusPgto::Tp_Autorizado :
					if($status_pedido_atual!=$this->config->get('cielointegradofutura_au')){
						$this->dmodel_checkout_order->update($order_id, $this->config->get('cielointegradofutura_au'), $tid);
					}
					break;

				}
				echo '<status>OK</status>';
			}else{
				$this->log->write("[Checkout Cielo] Total ".number_format(($this->request->request['amount']/100), 2, '.', '')." divergente do valor original ".number_format($order_info['total'], 2, '.', '')." no pedido ".$order_id."");
				echo '<status>NOK</status>';
			}
		}
	}

	public function retornaSigla($estado){
		$sigla = array(
			'Acre'                => 'AC',
			'Alagoas'             => 'AL',
			'Amapá'               => 'AP',
			'Amazonas'            => 'AM',
			'Bahia'               => 'BA',
			'Ceará'               => 'CE',
			'Espírito Santo'      => 'ES',
			'Goiás'               => 'GO',
			'Maranhão'            => 'MA',
			'Mato Grosso'         => 'MT',
			'Mato Grosso do Sul'  => 'MS',
			'Minas Gerais'        => 'MG',
			'Pará'                => 'PA',
			'Paraíba'             => 'PB',
			'Paraná'              => 'PR',
			'Pernambuco'          => 'PE',
			'Piauí'               => 'PI',
			'Rio de Janeiro'      => 'RJ',
			'Rio Grande do Norte' => 'RN',
			'Rio Grande do Sul'   => 'RS',
			'Rondônia'            => 'RO',
			'Roraima'             => 'RR',
			'Santa Catarina'      => 'SC',
			'São Paulo'           => 'SP',
			'Sergipe'             => 'SE',
			'Tocantins'           => 'TO',
			'Distrito Federal'    => 'DF');

			return $sigla[$estado];
		}

		private function app() {
			$this->document->addScriptApp(array(
				'catalog/view/theme/appmobile/js/payment.cielointegradofutura.js'
			));
			$this->data['scriptsApp'] = json_encode($this->document->getScriptsApp());
		}
	}
