<?php

/** MODULO CRIADO POR ODLANIER
 * @author Odlanier de Souza Mendes
 * @baseado PagSeguro by Fernando Agência Pró
 * @colaboradores GCCSystem, Ehinnar
 * @copyright Dlani
 * @email master_odlanier@hotmail.com
 * @email mends@prestashopbr.com
 * @version 1.4 BETA
 **/

class MoIP extends PaymentModule
{
	private $_html = '';
    private $_postErrors = array();
    public $currencies;
    
    public $_botoes 		= array(
		'default',
		'bt_pagar_c01_e01.png',
		'bt_pagar_c02_e01.png',
		'bt_pagar_c03_e01.png',
		'bt_pagar_c04_e01.png',
		'bt_pagar_c05_e01.png',
		'bt_pagar_c06_e01.png',
		'bt_pagar_c07_e01.png',
		'bt_pagar_c08_e01.png',
		'bt_pagar_c09_e01.png',

		'bt_pagar_c01_e04.png',
		'bt_pagar_c02_e04.png',
		'bt_pagar_c03_e04.png',
		'bt_pagar_c04_e04.png',
		'bt_pagar_c05_e04.png',
		'bt_pagar_c06_e04.png',
		'bt_pagar_c07_e04.png',
		'bt_pagar_c08_e04.png',
		'bt_pagar_c09_e04.png'
		
	);
    
    public $banners = array(
		"formas_pagamento.png",
		"formas_pagamento_6x.png",
		"formas_pagamento_bancos.png",
		"formas_pagamento_bancos_boleto.png",
		"formas_pagamento_boleto.png",
		"formas_pagamento_cartoes.png",
		"formas_pagamento_cartoes_bancos.png",
		"formas_pagamento_cartoes_boleto.png"
	);
	
	public function __construct()
    {
    	
        $this->name 			= 'MoIP';
        $this->tab 				= 'Payment';
        $this->version 			= '1.3 BETA';

        $this->currencies 		= true;
        $this->currencies_mode 	= 'radio';

        parent::__construct();

        $this->page 			= basename(__file__, '.php');
        $this->displayName 		= $this->l('MoIP');
        $this->description 		= $this->l('Aceitar pagamentos via MoIP');
		$this->confirmUninstall = $this->l('Tem certeza de que pretende eliminar os seus dados?');
		$this->textButton		= $this->l('Efetuar Pagamento');
	}
	
	public function install()
	{
	
		if ( !Configuration::get('MoIP_STATUS_1') )
			$this->create_states();
	
		if 
		(
			!parent::install()
			OR 	!Configuration::updateValue('MoIP_BUSINESS', 'euviajaspion@evocetambem.jp') 
			OR 	!Configuration::updateValue('MoIP_BANNER', 0)
			OR 	!Configuration::updateValue('MoIP_BUTTON', 0)
			OR 	!$this->registerHook('payment') 
			OR 	!$this->registerHook('paymentReturn')
			OR 	!$this->registerHook('home')
		)
					return false;
		return true;
	
	}
	
	public function create_states()
	{
		
		$this->order_state = array(
		array( 'ffffff', '10100', 'MoIP - Autorizado',				 ''	),
		array( 'ccfbff', '00100', 'MoIP - Iniciado', 				 ''	),
		array( 'ffccf7', '00100', 'MoIP - Boleto Impresso',			 ''	),
		array( 'c9fecd', '11110', 'MoIP - Concluido',		  'payment' ),
		array( 'fec9c9', '11110', 'MoIP - Cancelado',  'order_canceled'	),
		array( 'fcffcf', '00100', 'MoIP - Em análise',				 ''	),
		array( 'ffe0bb', '11100', 'MoIP - Estornado', 		   'refund'	),
		array( 'd6d6d6', '00100', 'MoIP - Em Aberto', 		   		 ''	)
		);
		
		/** OBTENDO UMA LISTA DOS IDIOMAS  **/
		$languages = Db::getInstance()->ExecuteS('
		SELECT `id_lang`, `iso_code`
		FROM `'._DB_PREFIX_.'lang`
		');
		/** /OBTENDO UMA LISTA DOS IDIOMAS  **/
		
		/** INSTALANDO STATUS MOIP **/		
		foreach ($this->order_state as $key => $value)
		{
			/** CRIANDO OS STATUS NA TABELA order_state **/
			Db::getInstance()->Execute
			('
				INSERT INTO `' . _DB_PREFIX_ . 'order_state` 
			( `invoice`, `send_email`, `color`, `unremovable`, `logable`, `delivery`) 
				VALUES
			('.$value[1][0].', '.$value[1][1].', \'#'.$value[0].'\', '.$value[1][2].', '.$value[1][3].', '.$value[1][4].');
			');
			/** /CRIANDO OS STATUS NA TABELA order_state **/
			
			$this->figura 	= mysql_insert_id();
			
			foreach ( $languages as $language_atual )
			{
				/** CRIANDO AS DESCRIÇÕES DOS STATUS NA TABELA order_state_lang  **/
				Db::getInstance()->Execute
				('
					INSERT INTO `' . _DB_PREFIX_ . 'order_state_lang` 
				(`id_order_state`, `id_lang`, `name`, `template`)
					VALUES
				('.$this->figura .', '.$language_atual['id_lang'].', \''.$value[2].'\', \''.$value[3].'\');
				');
				/** /CRIANDO AS DESCRIÇÕES DOS STATUS NA TABELA order_state_lang  **/	
			}
			
			
				/** COPIANDO O ICONE ATUAL **/
				$file 		= (dirname(__file__) . "/icons/$key.gif");
				$newfile 	= (dirname( dirname (dirname(__file__) ) ) . "/img/os/$this->figura.gif");
				if (!copy($file, $newfile)) {
    			return false;
    			}
    			/** /COPIANDO O ICONE ATUAL **/
			   		
    		/** GRAVA AS CONFIGURAÇÕES  **/
    		Configuration::updateValue("MoIP_STATUS_$key", 	$this->figura);
    		   				
		}
		
		return true;
		
	}

	public function uninstall()
	{
		
		if (
			!Configuration::deleteByName('MoIP_BUSINESS') 
		OR 	!Configuration::deleteByName('MoIP_BANNER')
		OR 	!Configuration::deleteByName('MoIP_BUTTON')
		OR 	!parent::uninstall()) return false;
		return true;
	}

	public function getContent()
	{
		
		$this->_html = '<h2>MoIP</h2>';
		if (isset($_POST['submitMoIP']))
		{
			if (empty($_POST['business'])) 
			$this->_postErrors[] = $this->l('Digite um e-mail para a cobrança');
	
			elseif (!Validate::isEmail($_POST['business'])) 
			$this->_postErrors[] = $this->l('Digite um e-mail válido para a cobrança');
			
			if (!sizeof($this->_postErrors)) {
				Configuration::updateValue('MoIP_BUSINESS', $_POST['business']);
				
				$this->displayConf();
			}
			else $this->displayErrors();
		}
			elseif (isset($_POST['submitMoIP_Banner']))
		{
			Configuration::updateValue('MoIP_BANNER', 	$_POST['banner']);
			$this->displayConf();
		}
			elseif (isset($_POST['submitMoIP_Button']))
		{
			Configuration::updateValue('MoIP_BUTTON', 	$_POST['button']);
			$this->displayConf();
		}

		$this->displayMoIP();
		$this->displayFormSettingsMoIP();
		return $this->_html;
	}
	
	public function displayConf()
	{
		
		$this->_html .= '
		<div class="conf confirm">
			<img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />
			'.$this->l('Configurações atualizadas').'
		</div>';
	}
	
	public function displayErrors()
	{
		
		$nbErrors = sizeof($this->_postErrors);
		$this->_html .= '
		<div class="alert error">
			<h3>'.($nbErrors > 1 ? $this->l('There are') : $this->l('There is')).' '.$nbErrors.' '.($nbErrors > 1 ? $this->l('errors') : $this->l('error')).'</h3>
			<ol>';
		foreach ($this->_postErrors AS $error)
			$this->_html .= '<li>'.$error.'</li>';
		$this->_html .= '
			</ol>
		</div>';
	}

	public function displayMoIP()
	{
		
		
		
		$this->_html .= '
		<img src="https://www.moip.com.br/imgs/logo_moip.gif" style="float:left; margin-right:15px;" />
		<b>'.$this->l('Este módulo permite aceitar pagamentos via MoIP.').'</b><br /><br />
		'.$this->l('Se o cliente escolher o módulo de pagamento, a conta do MoIP sera automaticamente creditado.').'<br />
		'.$this->l('Você precisa configurar o seu e-mail do MoIP, para depois usar este módulo.').'
		<br /><br /><br />';
	}

	public function displayFormSettingsMoIP()
	{
		
		$conf 			= Configuration::getMultiple(array('MoIP_BUSINESS', 'MoIP_BANNER', 'MoIP_BUTTON'));
		$businessPag 	= array_key_exists('business', $_POST) ? $_POST['business'] : (array_key_exists('MoIP_BUSINESS', $conf) ? $conf['MoIP_BUSINESS'] : '');
		$banner 		= array_key_exists('banner', $_POST) ? $_POST['banner'] : (array_key_exists('MoIP_BANNER', $conf) ? $conf['MoIP_BANNER'] : '');
		$button 		= array_key_exists('button', $_POST) ? $_POST['button'] : (array_key_exists('MoIP_BUTTON', $conf) ? $conf['MoIP_BUTTON'] : '');
		
		/** CONFIGURAÇÕES **/
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
		<fieldset>
			<legend><img src="../img/admin/contact.gif" />'.$this->l('Configurações').'</legend>
			<label>'.$this->l('E-mail para cobrança').':</label>
			<div class="margin-form"><input type="text" size="33" name="business" value="'.htmlentities($businessPag, ENT_COMPAT, 'UTF-8').'" /></div>
			<br /><center><input type="submit" name="submitMoIP" value="'.$this->l('Atualizar').'" class="button" /></center>
		</fieldset>
		</form>';
		
		/** BANNER **/
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
		<fieldset>
			<legend><img src="../img/admin/themes.gif" />'.$this->l('Banner').'</legend>';
			
		foreach ( $this->banners as $id => $value )
		{
			if ($banner ==  $id){
				$check = 'checked="checked"'; 
			}else{
				$check = '';
			}
			
			$this->_html .=  '
			<div>
			<input type="radio" name="banner" value="'.$id.'" '.$check.' >
			<img src="http://www.moip.com.br/imgs/'.$value.'" />
			</div>
			<br />';
			
		}

		$this->_html .= '<br /><center><input type="submit" name="submitMoIP_Banner" value="'.$this->l('Salvar').'" 
			class="button" />
		</center>
		</fieldset>
		</form>';
	
		/** BUTTON **/
				$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
		<fieldset>
			<legend><img src="../img/admin/themes.gif" />'.$this->l('Botão').'</legend>';
			
		foreach ( $this->_botoes as $id => $value )
		{
			if ($button ==  $id){
				$check = 'checked="checked"'; 
			}else{
				$check = '';
			}
			
			$this->_html .=  '
			<div>
			<input type="radio" name="button" value="'.$id.'" '.$check.' >';
			
			if( $value == 'default' )
			$this->_html .=  '<input type="submit" value="Pague com o MoIP" class="exclusive_large" />';
			else
			$this->_html .=  '<img src="http://www.moip.com.br/imgs/buttons/'.$value.'" />';
			
			$this->_html .=  '</div>
			<br />';
			
		}

		$this->_html .= '<br /><center><input type="submit" name="submitMoIP_Button" value="'.$this->l('Salvar').'" 
			class="button" />
		</center>
		</fieldset>
		</form>';
	
	}

    public function execPayment($cart)
    {
        global $cookie, $smarty;
        $invoiceAddress 	= new Address(intval($cart->id_address_invoice));
        $customerPag 		= new Customer(intval($params['cart']->id_customer));
        $currencies 		= Currency::getCurrencies();
        $currencies_used 	= array();
        
        $conf 				= Configuration::getMultiple(array('MoIP_BUSINESS', 'MoIP_BANNER'));
		$banner 			= array_key_exists('banner', $_POST) ? $_POST['banner'] : (array_key_exists('MoIP_BANNER', $conf) ? $conf['MoIP_BANNER'] : '');

        $currencies = Currency::getCurrencies();
        foreach ($currencies as $key => $currency)
            $smarty->assign(array(
			'currency_default'	=> new Currency(Configuration::get('PS_CURRENCY_DEFAULT')),
            'currencies' 		=> $currencies_used, 
			'imgBtn' 			=> "https://www.moip.com.br/imgs/logo_moip.gif",
			'imgBanner'			=> "http://www.moip.com.br/imgs/" . $this->banners[$banner],
            'currency_default' 	=> new Currency(Configuration::get('PS_CURRENCY_DEFAULT')),
            'currencies' 		=> $currencies_used, 
			'total'				=> number_format($cart->getOrderTotal(true, 3), 2, '.', ''), 
			'this_path_ssl' 	=> (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT,'UTF-8') . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));

        return $this->display(__file__, 'payment_execution.tpl');
    }
	
	public function hookPayment($params)
	{
		global $smarty;
		
		$smarty->assign(array(
			'imgBtn' 	=> "https://www.moip.com.br/imgs/logo_moip.gif",
			'this_path' => $this->_path, 'this_path_ssl' => (Configuration::get('PS_SSL_ENABLED') ?	'https://' : 'http://') . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT,'UTF-8') . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
		return $this->display(__file__, 'payment.tpl');
		
	}
	
	public function hookPaymentReturn($params)
    {
        global $smarty;
		include(dirname(__FILE__).'/includes/moip.php');
		
		$MoIP 				= new Moip_Form(array('id_carteira' => Configuration::get('MoIP_BUSINESS')));
		$formMoIP 			= $MoIP->_constroi_form($params);
		
        $state 				= $params['objOrder']->getCurrentState();  
        $order 				= new Order($MoIP->currentOrder);
		$DadosOrder 		= new Order($params['objOrder']->id);
		$DadosCart 			= new Cart($DadosOrder->id_cart);
		$currency 			= new Currency($DadosOrder->id_currency);
		$frete 				= number_format( Tools::convertPrice( $DadosOrder->total_shipping, $currency), 2, '.', '');
		$ArrayListaProdutos = $DadosOrder->getProducts();
		
		$smarty->assign(array(
			'totalApagar' 	=> Tools::displayPrice($params['total_to_pay'],$params['currencyObj'], false, false), 
			'status' 		=> 'ok', 
			'id_order' 		=> $params['objOrder']->id,
			'secure_key' 	=> $params['objOrder']->secure_key,
			'id_module' 	=> $this->id,
			'formMoIP' 		=> $formMoIP
		));

		return $this->display(__file__, 'payment_return.tpl');
    }
    
    function hookHome($params)
	{
    	include(dirname(__FILE__).'/includes/retorno.php');
    }
    
    function getStatus($param)
    {
    	global $cookie;
    		
    		$sql_status = Db::getInstance()->Execute
		('
			SELECT `name`
			FROM `'._DB_PREFIX_.'order_state_lang`
			WHERE `id_order_state` = '.$param.'
			AND `id_lang` = '.$cookie->id_lang.'
			
		');
		
		return mysql_result($sql_status, 0);
    }
    
    public function enviar($mailVars, $template, $assunto, $DisplayName, $idCustomer, $idLang, $CustMail, $TplDir)
	{
		
		Mail::Send
			( intval($idLang), $template, $assunto, $mailVars, $CustMail, null, null, null, null, null, $TplDir);
		
	}
	
	public function getUrlByMyOrder( $myOrder )
	{

			$module				= Module::getInstanceByName($myOrder->module);			
			$pagina_qstring		= __PS_BASE_URI__."order-confirmation.php?id_cart="
								  .$myOrder->id_cart."&id_module=".$module->id."&id_order="
								  .$myOrder->id."&key=".$myOrder->secure_key;			
			
			if	(	$_SERVER['HTTPS']	!=	"on"	)
			$protocolo			=	"http";
			
			else
			$protocolo			=	"https";
			
			$retorno 			= $protocolo . "://" . $_SERVER['SERVER_NAME'] . $pagina_qstring;			
			return $retorno;
	
	}
    
}
?>