<?php

class Liaisonssl extends PaymentModule
{
	private	$_html = '';
        private $_apiConstructUrl = '';
	private $_postErrors = array();
        private $_temporaryKey = '';
        private $_urlapi = '';

	public function __construct()
	{
		$this->name = 'liaisonssl';
		$this->tab = 'Payment';
		$this->version = '1.0';
		
		$this->currencies = true;
		$this->currencies_mode = 'radio';

        parent::__construct();

		$this->page = basename(__FILE__, '.php');
                $this->displayName = 'Paiement CB';
                $this->description = $this->l('Accepts payments by Liaison-SSL');
		$this->confirmUninstall = $this->l('Are you sure you want to delete your details ?');
	}


	public function install()
	{
		if (!parent::install()
			OR !Configuration::updateValue('LIAISONSSL_MERCH_ID','0000000000000')
			OR !Configuration::updateValue('LIAISONSSL_ACTION_URL', 'https://www.liaison-ssl.com/paiement/encaisser?cle_temporaire=')
                        OR !Configuration::updateValue('LIAISONSSL_API_URL', 'https://www.liaison-ssl.com/api/new_commande_temporaire')
			OR !$this->registerHook('payment')
			OR !$this->registerHook('paymentReturn'))
			return false;

                        //Paiement 1 - commande validée - envoi de mail - pas de facture
                        $qi_p1 = 'INSERT INTO '. _DB_PREFIX_ .'order_state (id_order_state, invoice, send_email, color, unremovable, logable, delivery) VALUES (NULL, "0", "1", "#DDEEFF", "1", "1", "0")';
                        Db::getInstance()->Execute($qi_p1);
                        $qs_p1 = 'SELECT MAX(id_order_state) as id_order_state FROM '. _DB_PREFIX_.'order_state';
                        $rpos = Db::getInstance()->ExecuteS($qs_p1);
                        $qi_p1 = 'INSERT INTO '. _DB_PREFIX_ .'order_state_lang (id_order_state, id_lang, name, template) VALUES ("'.$rpos[0]['id_order_state'].'", "2", "Paiement en attente de validation", "paiementencoursvalid")';
                        Db::getInstance()->Execute($qi_p1);
                        Configuration::updateValue('LIAISONSSL_STATUS', $rpos[0]['id_order_state']);
                        $qi_p1 = 'INSERT INTO '. _DB_PREFIX_ .'order_state_lang (id_order_state, id_lang, name, template) VALUES ("'.$rpos[0]['id_order_state'].'", "1", "Awaiting Payment Validation", "paiementencoursvalid")';
                        Db::getInstance()->Execute($qi_p1);

		return true;
	}

	public function uninstall()
	{
		if (!Configuration::deleteByName('LIAISONSSL_MERCH_ID')
			OR !Configuration::deleteByName('LIAISONSSL_ACTION_URL')
                        OR !Configuration::deleteByName('LIAISONSSL_API_URL')
                        OR !Configuration::deleteByName('LIAISONSSL_STATUS')
			OR !parent::uninstall())
			return false;
		return true;
	}

        public function getTemporaryKey($amount, $ref, $customer)
        {

			$params = Array(
			"user_identifiant_commercant" => Configuration::get('LIAISONSSL_MERCH_ID'),
                        "montant" => $amount,
			"reference_interne" => $ref."-".$customer->email,
			"url_retour_ok" => 'http://'.htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/liaisonssl/validation.php?key='.$customer->secure_key.'&id_cart='.intval($ref).'&id_module='.intval($this->id).'&amount='.$amount,
			"url_retour_failed" => 'http://'.htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'history.php');

			$this->_apiConstructUrl = Configuration::get('LIAISONSSL_API_URL'). "?";

			foreach($params as $key => $val)
			{
				$this->_apiConstructUrl .= "commande_temporaire[" . $key . "]=" . urlencode($val) . "&";
			}
                        
			$url = substr($this->_apiConstructUrl, 0, strlen($this->_apiConstructUrl) - 1);

                        $this->_urlapi = $url;

			$fp = @fopen($url,"r");
                        
			if($fp)
			{
				$this->_temporaryKey = fread($fp,40960);
				fclose($fp);
                                return $this->_temporaryKey;
			}
			else
			{
				$ch = curl_init();

				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_NOBODY, false);
				curl_setopt($ch, CURLOPT_MUTE, true);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_FAILONERROR, true);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

				$this->_temporaryKey = curl_exec($ch);

				curl_close($ch);

                                return $this->_temporaryKey;
			}
			return false;
        }

	public function getContent()
	{
		$this->_html = '<h2>Liaison SSL</h2>';
		if (isset($_POST['submitLiaisonSsl']))
		{
			if (!isset($_POST['merchant_id']))
				$this->_postErrors[] = $this->l('Merchand ID is required.');
                  
			if (!sizeof($this->_postErrors))
			{
				Configuration::updateValue('LIAISONSSL_MERCH_ID', $_POST['merchant_id']);
                            
				$this->displayConf();
			}
			else
				$this->displayErrors();
		}

		$this->displayLiaisonSsl();
		$this->displayFormSettings();
		return $this->_html;
	}

	public function displayConf()
	{
		$this->_html .= '
		<div class="conf confirm">
			<img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />
			'.$this->l('Settings updated').'
		</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 displayLiaisonSsl()
	{
		$this->_html .= '
		<img src="../modules/liaisonssl/images/logoliaisonssl.jpg" style="float:left; margin-right:15px;margin-bottom:55px;" />
		<b>'.$this->l('This module allows you to accept payments by business cards.').'</b><br /><br />
		'.$this->l('If the client chooses this payment mode, you are going to receive your client informations by a ssl secure way.').'<br />
                '.$this->l('Then, you have to put this informations on your real TPE.').'<br />
		'.$this->l('You need to have informations from your provider first before using this module.').'<br /><br />
               	<div style="clear:both;">&nbsp;</div>';
	}

	public function displayFormSettings()
	{      
                $merchant_id = array_key_exists('merchant_id', $_POST) ? $_POST['merchant_id'] : Configuration::get('LIAISONSSL_MERCH_ID');
              
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post" style="clear: both;">
		<fieldset>
			<legend><img src="../img/admin/contact.gif" />'.$this->l('Settings').'</legend>
		        <label>'.$this->l('Merchant ID').'</label>
			<div class="margin-form"><input type="text" size="15" name="merchant_id" value="'.htmlentities($merchant_id, ENT_COMPAT, 'UTF-8').'" />
			<p class="hint clear" style="display: block; width: 501px;">'.$this->l('This ID is provided by your provider').'</p></div><br /><br /><br />
			<br /><center><input type="submit" name="submitLiaisonSsl" value="'.$this->l('Update settings').'" class="button" /></center>
		</fieldset>
		</form><br /><br />
                <br /><br />
                <div class="path_bar"><img src="../img/t/AdminModules.gif" />&nbsp;<a href="http://www.rioo.fr" target="_blank">Module développé par la société RIOO</a><br/>
                </div>';
	}

        public function getL($key)
	{
		$translations = array(
			'Cancellation' => $this->l('The transaction as been canceled.'),
                        'Transaction' => $this->l('CM-CIC transaction ID:'),
		);
		return $translations[$key];
	}

	public function hookPayment($params)
	{
		if (!$this->active)
			return ;

		global $smarty;

                //Recuperation des infos et initialisation variables
		$address = new Address(intval($params['cart']->id_address_invoice));
		$customer = new Customer(intval($params['cart']->id_customer));
		$currency = $this->getCurrency();
                $today = date("d/m/Y:H:i:s");
                // products + discounts + shipping cost
                $montant = number_format(Tools::convertPrice($params['cart']->getOrderTotal(true, 3), $currency), 2, '.', '');

                // Reference: unique, alphaNum (A-Z a-z 0-9), 12 characters max
                $reference = intval($params['cart']->id);

                // customer email
                $email = $customer->email;

		if (!Validate::isLoadedObject($address) OR !Validate::isLoadedObject($customer) OR !Validate::isLoadedObject($currency))
			return $this->l('(invalid address or customer)');

                $tkey = $this->getTemporaryKey($montant, $reference, $customer);
			
		$smarty->assign(array(
                        'urldebug' => $this->_urlapi,
                        'liaisonssl_url' => Configuration::get('LIAISONSSL_ACTION_URL').$tkey,
		));

		return $this->display(__FILE__, 'liaisonssl.tpl');
	}

	public function hookPaymentReturn($params)
	{
		if (!$this->active)
			return ;
     
                   return $this->display(__FILE__, 'confirmation.tpl');
            
		
	}
	
}
