<?php
/**
* ---------------------------------------------------------------------------------
*
* This file is part of the 'giftonordermodule' module feature (main || related module)
* Developped for Prestashop platform.
* You are not allowed to use it on several site
* You are not allowed to redistribute this module
* This header must not be removed
*
* @category  giftonordermodule
* @author    OleaCorner <contact@oleacorner.com> <www.oleacorner.com>
* @copyright OleaCorner
* @version   4.3
* @license   XXX
*
* ---------------------------------------------------------------------------------
*/

class GiftonorderModule extends Module
{

	public $gift_type_name;

	public $is_before_14;

	public function __construct()
	{
		$this->bootstrap = true;
		$this->name = 'giftonordermodule';
		$this->tab = 'pricing_promotion';
		$this->is_before_14 = false;
		$this->ps_versions_compliancy['min'] = '1.6.0.0';
		$this->version = '5.0.7';

		$this->author = 'Oleacorner';
		$this->module_key = '341e08743bda923bd1f60b4ba2d1f7fc';

		$this->_logfilename = '/modules/'.$this->name.'/logs/historic.log';
		$this->_logfilehdl = false;

		parent::__construct ();
		$this->warning = '';

		$this->displayName = 'GiftOnOrder';
		$this->description = $this->l('Allow to offer gift to customer when they order');
		$this->confirmUninstall = $this->l('Are you sure you want to uninstall, all your gifts configuration will be lost ?');

		if (isset (Context::getContext ()->employee) && Context::getContext ()->employee->isLoggedBack ())
		{
			$fname = _PS_ROOT_DIR_.'/override/controllers/front/CartController.php';
			$handle = @fopen ($fname, 'r');
			if (!$handle)
				$this->warning = $this->l('You need to update file \'/override/controllers/front/CartController.php\' : see documentation');
			else
			{
				$content = fread ($handle, filesize ($fname));

				$pos = strpos ($content, 'cartRefreshForGift');
				if ($pos === false)
					$this->warning = $this->l('You need to update file \'/override/controllers/front/CartController.php\' : see documentation');
				fclose ($handle);
			}

			$fname = _PS_ROOT_DIR_.'/override/controllers/front/ParentOrderController.php';
			$handle = @fopen ($fname, 'r');
			if (!$handle)
				$this->warning = $this->l('You need to update file \'/override/controllers/front/ParentOrderController.php\' : see documentation');
			else
			{
				$content = fread ($handle, filesize ($fname));

				$pos = strpos ($content, 'cartRefreshForGift');
				if ($pos === false)
					$this->warning = $this->l('You need to update file \'/override/controllers/front/ParentOrderController.php\' : see documentation');
				fclose ($handle);
			}

			$fname = _PS_ROOT_DIR_.'/override/controllers/front/ProductController.php';
			$handle = @fopen ($fname, 'r');
			if (!$handle)
				$this->warning = $this->l('You need to update file \'/override/controllers/front/ProductController.php\' : see documentation');
			else
			{
				$content = fread ($handle, filesize ($fname));

				$pos = strpos ($content, 'OLEA_GIFTONORDER_GIFT_CATEGORY');
				if ($pos === false)
					$this->warning = $this->l('You need to update file \'/override/controllers/front/ProductController.php\' : see documentation');
				fclose ($handle);
			}

			if (version_compare(_PS_VERSION_, '1.5.3') < 0)
			{
				$fname = _PS_ROOT_DIR_.'/override/classes/shop/Shop.php';
						$handle = @fopen ($fname, 'r');
				if (!$handle)
					$this->warning = $this->l('You need to update file \'/override/classes/shop/Shop.php\' : see documentation');
				else
				{
					$content = fread ($handle, filesize ($fname));

					$pos = strpos ($content, 'giftonorder');
					if ($pos === false)
						$this->warning = $this->l('You need to update file \'/override/classes/shop/Shop.php\' : see documentation');
					fclose ($handle);
				}
			}
		}

		$this->id_category_gift = (int)(Configuration::get ('OLEA_GIFTONORDER_GIFT_CATEGORY'));
		if (0 && (int)(Configuration::get ('OLEA_GIFTONORDER_LOGS')))
		{
			$this->_logfilehdl = @fopen (_PS_ROOT_DIR_.$this->_logfilename, 'a');
			if (!isset ($this->warning) && !$this->_logfilehdl)
				$this->warning = $this->l("Can't access in write mode to file").' : '.$this->_logfilename;
		}

		if ($this->warning == '' && in_array ($this->id_category_gift, array(
			0,
			(int)Configuration::get ('PS_ROOT_CATEGORY'),
			(int)Configuration::get ('PS_HOME_CATEGORY')
		)))
			$this->warning = $this->l('Gift category must be defined');
	}

	public function is_version_ok()
	{
		if (version_compare ('1.5', _PS_VERSION_) <= 0)
			return true;
		$db_version = Configuration::get ('OLEA_GIFTONORDER_VERSION');
		if (version_compare ($db_version, $this->version, '<'))
			return false;
		else
			return true;
	}

	public function install()
	{
		if (!defined ('_MYSQL_ENGINE_'))
			define ('_MYSQL_ENGINE_', 'InnoDB');

			// $this->version = '0.0'; // to force usage of upgrade files, see PSCFV-5314
		if (!parent::install ())
			return false;

			// $query = "INSERT INTO `"._DB_PREFIX_."hook`
			// (`id_hook`, `name`, `title`, `description`, `position`) VALUES
			// (null, 'cartRefreshForGift', 'After cart content modification', null, '0')";
			// if (!Db::getInstance()->Execute($query))
			// return false;

		if (!$this->registerHook ('cartRefreshForGift') ||
			!$this->registerHook ('newOrder') ||
			!$this->registerHook ('leftColumn') ||
			!$this->registerHook ('shoppingCart') ||
			!$this->registerHook ('header') ||
			!$this->registerHook ('displayBackOfficeFooter') ||
			!$this->registerHook ('displayAdminOptions')
			/*OR !$this->registerHook('shoppingCartExtra')*/
			/*fin if*/)
			return false;

		$tab = new Tab ();
		$tab->id_parent = (version_compare ('1.5', _PS_VERSION_) <= 0) ? Tab::getIdFromClassName ('AdminPriceRule') : 3; // adminOrder on V1.2/V2.0
		$languages = Language::getLanguages ();
		foreach ($languages as $lang)
			$tab->name[$lang['id_lang']] = ($lang['iso_code'] == 'fr') ? 'Cadeaux' : 'Gifts';
		$tab->class_name = 'AdminOleagiftonorder';
		$tab->module = $this->name;
		if (!$tab->add ())
			return false;

		$query = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'giftonorder` (
	  				`id_giftonorder` int(10) unsigned NOT null auto_increment,
	  				`gift_id_product` int(10) unsigned ,
	  				`gift_id_combination` int(10) unsigned ,
					`gift_id_product_list` text,
	  				`allow_other_gift` int(10) unsigned ,
	  				`fo_display` tinyint(1),
	  				`gift_discount_multiple` tinyint(1),
	  				`criteria_type` int(10) unsigned ,
	  				`criteria_cart_amount` decimal(13,6),
	  				`criteria_nb_products` int(10) unsigned ,
	  				`criteria_different_products` int(10) unsigned ,
	  				`criteria_categories` text,
	  				`criteria_suppliers` text,
	  				`criteria_manufacturers` text,
	  				`criteria_max_per_customer` int(10) unsigned ,
	  				`criteria_qty_multiple` tinyint(1),
	  				`criteria_attributes` text ,
	  				`criteria_discounts` text ,
	  				`criteria_date_from` date,
	  				`criteria_date_to` date,
	  				`active` int(10) unsigned ,
	  				`position` int(10) unsigned ,
	  				`date_add` datetime NOT null,
	  				`date_upd` datetime NOT null,
				  	PRIMARY KEY  (`id_giftonorder`)
				  	)
				ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8';

		if (!Db::getInstance ()->Execute ($query))
			return false;

		$query = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'giftonorder_lang` (
	  				`id_giftonorder` int(10) unsigned NOT null ,
	  				`id_lang` int(10) unsigned NOT null ,
	  				`name` varchar(255) ,
	  				`description` varchar(1024),
	  				`message_fo` varchar(1024),
	  				`gift_selector_message` varchar(128),
	  				PRIMARY KEY  (`id_giftonorder`, `id_lang`)
				  	)
				ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8';

		if (!Db::getInstance ()->Execute ($query))
			return false;

		if (version_compare (_PS_VERSION_, '1.2', '>='))
		{
			$query = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'giftonorder_group` (
	  				`id_giftonorder` int(10) unsigned NOT null ,
	  				`id_group` int(10) unsigned NOT null ,
				  	INDEX giftonorder_group (`id_giftonorder`, `id_group`)
				  	)
				ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8';

			if (!Db::getInstance ()->Execute ($query))
				return false;
		}

		$query = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'giftonorder_order` (
	  				`id_giftonorder` int(10) unsigned NOT null ,
	  				`id_cart` int(10) unsigned NOT null ,
	  				`id_product` int(10) unsigned NOT null ,
	  				`id_combination` int(10) unsigned NOT null ,
	  				`id_order` int(10) unsigned NOT null ,
	  				`id_customer` int(10) unsigned NOT null ,
	  				INDEX giftonorder_order   (`id_giftonorder`, `id_cart`, `id_product`, `id_combination`)
				  	)
				ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8';

		if (!Db::getInstance ()->Execute ($query))
			return false;

		$query = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'giftonorder_shop` (
  					`id_giftonorder` int(10) unsigned NOT null,
  					`id_shop` int(10) unsigned NOT null,
  					PRIMARY KEY (`id_giftonorder`,`id_shop`)
				) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';

		if (!Db::getInstance ()->Execute ($query))
			return false;

		$this->doUpgrade ();

		Configuration::updateValue ('OLEA_GIFTONORDER_VERSION', $this->version);
		Configuration::updateValue ('OLEA_GIFTONORDER_AMOUNT_REDUC', true);

		return true;
	}

	public function uninstall()
	{
		if (!parent::uninstall ())
			return false;
		if (!$this->unregisterHook ('cartRefreshForGift') ||
			!$this->unregisterHook ('newOrder') ||
			!$this->unregisterHook ('leftColumn') ||
			!$this->unregisterHook ('shoppingCart') ||
			!$this->unregisterHook ('productActions')
			/*OR !$this->unregisterHook('shoppingCartExtra')*/
			/*fin if */)
			return false;

		if (!Db::getInstance ()->Execute ('DELETE FROM '._DB_PREFIX_.'hook WHERE `name`=\'cartRefreshForGift\' '))
			return false;

		$tab = new Tab (Tab::getIdFromClassName ('AdminOleagiftonorder'));
		if (!$tab->delete ())
			return false;

		if (!Db::getInstance ()->Execute ('DROP TABLE IF EXISTS '._DB_PREFIX_.'giftonorder'))
			return false;

		if (!Db::getInstance ()->Execute ('DROP TABLE IF EXISTS '._DB_PREFIX_.'giftonorder_lang'))
			return false;

		if (version_compare (_PS_VERSION_, '1.2', '>='))
		{
			if (!Db::getInstance ()->Execute ('DROP TABLE IF EXISTS '._DB_PREFIX_.'giftonorder_group'))
				return false;
		}

		if (!Db::getInstance ()->Execute ('DROP TABLE IF EXISTS '._DB_PREFIX_.'giftonorder_order'))
			return false;

		if (!Db::getInstance ()->Execute ('DROP TABLE IF EXISTS '._DB_PREFIX_.'giftonorder_shop'))
			return false;

		Configuration::deleteByName ('OLEA_GIFTONORDER_GIFT_CATEGORY');
		Configuration::updateValue ('OLEA_GIFTONORDER_VERSION', 0);

		return true;
	}


	public function getContent()
	{
		if (version_compare ('1.6', _PS_VERSION_) <= 0)
		{
			$post = '';
			// $post .= '<pre>POST='.print_r($_POST, true).'</pre>';
			if (Tools::isSubmit ('submitGooConfig'))
				Configuration::updateValue ('OLEA_GIFTONORDER_GIFT_CATEGORY', Tools::getValue ('olea_giftonorder_gift_category'));

			return $post.$this->renderForm ().$this->hookDisplayBackOfficeFooter (array());
		}

		$output = '<h2>'.$this->displayName.'</h2>';
		if (Tools::isSubmit ('submitGiftCategory'))
		{
			if ($id_category = Tools::getValue ('id_gift_category'))
			{
				Configuration::updateValue ('OLEA_GIFTONORDER_GIFT_CATEGORY', (int)($id_category));
				$this->id_category_gift = $id_category;
			}
		}
		elseif (Tools::isSubmit ('submitDoUpgrade'))
		{
			$result_upgrade = $this->doUpgrade ();
			if ($result_upgrade != '')
				$output = $this->displayError ($result_upgrade).$output;
		}
		if (!$this->is_version_ok ())
			return $output.$this->displayFormForUpgrade ();
		else
			return $output.$this->displayForm ();
	}

	public function doUpgrade()
	{
		// $this->registerHook('top');
		$this->registerHook ('header');
		$this->registerHook ('extraRight');

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'gift_id_product_list\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `gift_id_product_list` text';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(1)';

			$query = 'UPDATE `'._DB_PREFIX_.'giftonorder`
		 				SET `gift_id_product_list` = `gift_id_product`
		 				WHERE `gift_id_product` <> 0';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(2)';
		}
		else
		{
			// ALTER TABLE t1 MODIFY b BIGINT NOT null;
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				MODIFY `gift_id_product_list` text';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(9)';
		}

		$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				MODIFY `criteria_categories` text';
		if (!Db::getInstance ()->Execute ($query))
			return $this->l('Error upgrading database').'(10)';

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder_lang` LIKE \'gift_selector_message\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder_lang`
		 				ADD COLUMN `gift_selector_message` varchar(128)';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(3)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_qty_multiple\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_qty_multiple` tinyint(1)';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(4)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_attributes\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_attributes` text';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(5)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_suppliers\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_suppliers` text';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'('.__LINE__.')';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_manufacturers\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_manufacturers` text';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'('.__LINE__.')';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_discounts\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_discounts` text';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(6)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'gift_discount_multiple\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `gift_discount_multiple` tinyint(1)';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(7)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'fo_display\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `fo_display` tinyint(1) DEFAULT 1';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(8)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_cumulative_with_voucher_type\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_cumulative_with_voucher_type` tinyint(1) DEFAULT 0'; // 0 = all vouchers
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(9)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_cumulable_reduced_products\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_cumulable_reduced_products` tinyint(1) DEFAULT 1'; // 1 : cumulable
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(10)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'gift_preselector_product_page\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `gift_preselector_product_page` tinyint(1) DEFAULT 0';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(11)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'cart` LIKE \'oleagoo_preselectedgifts\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'cart`
		 				ADD COLUMN `oleagoo_preselectedgifts` TEXT '; // 1 : cumulable
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(12)';
		}

		$query = 'SHOW COLUMNS FROM `'._DB_PREFIX_.'giftonorder` LIKE \'criteria_category_amount\'';
		$res = Db::getInstance ()->ExecuteS ($query);
		if (count ($res) == 0)
		{
			$query = 'ALTER TABLE `'._DB_PREFIX_.'giftonorder`
		 				ADD COLUMN `criteria_category_amount` DECIMAL(10,2) ';
			if (!Db::getInstance ()->Execute ($query))
				return $this->l('Error upgrading database').'(13)';
		}

		// if (version_compare(_PS_VERSION_, "1.5.3.1") == 0) {
		require_once dirname (__FILE__).'/upgrade/install-4.2.1.php';
		if (!upgrade_module_4_2_1 ($this))
			return $this->l('Unable to execute the 4.2.1 upgrade');
			// }

		$admin_translation = Tools::file_get_contents (_PS_ROOT_DIR_.'/translations/fr/admin.php');
		if (count ($admin_translation))
		{
			if ($fh = fopen (_PS_ROOT_DIR_.'/translations/fr/admin.php', 'wb'))
			{
				$modified_translation = str_replace ('Choisir l\'heure', 'Choisir l heure', $admin_translation);
				fwrite ($fh, $modified_translation);
				fclose ($fh);
			}
			else
				die ('fichier pas ouvert en ecriture');
		}
		else
			die ('Fichier pas lu');
		Configuration::updateValue ('OLEA_GIFTONORDER_VERSION', $this->version);
		Configuration::updateValue ('OLEA_GIFTONORDER_AMOUNT_REDUC', true);
		/* due to latency in DB access */
		Configuration::set ('OLEA_GIFTONORDER_VERSION', $this->version);
		Configuration::set ('OLEA_GIFTONORDER_AMOUNT_REDUC', true);
		return '';
	}

	public function displayFormForUpgrade()
	{
		$retour = '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
			<fieldset>
			<p>'.$this->l('Your database is not up to date').'<br />
			'.$this->l('You need to upgrade it to be able to use the module').'</p>
			<center><input type="submit" name="submitDoUpgrade" value="'.$this->l('Upgrade').'" class="button" /></center>
			</fieldset>
		</form>';

		return $retour;
	}

	public function getDescriptionText()
	{
		if ($this->context->language->iso_code == 'fr')
		{
			$retour = '<h4>Catégorie des cadeaux</h4>
				<p>Vous devez définir dans votre catalogue une catégorie destinée à contenir tous les produits cadeaux que le module est susceptible d\'offrir.<br/>
				Si vous ne disposez pas du champ "Visibilité:NullPart" dans les fiches produits du Back-Office, afin que les produits cadeaux de cette catégorie n\'apparaissent pas dans votre front-office, vous devez définir un groupe de client qui ne contiendra aucun client.<br/>
				La catégorie des cadeaux doit alors être désactivée et restreinte au seul groupe de client défini précédemment, puis déclarée dans le paramétrage ci-dessous.
				</p>';

			$retour .= '<p>&nbsp;</p>
				<h4>Produits-cadeaux</h4>
				<p>Les produits que le module offre en cadeau doivent avoir leur propre fiche en Back-Office, afin de leur fixer le prix à 0, soit par prix final, soit par remise de 100%.<br/>
				Vous devez leur fixer leur "Visibilité" à "Null Part" pour qu\'ils ne soient pas visibles en Front-Office<br/>
				Ils sont présents uniquement dans la catégorie Cadeaux<br/>
				Ces produits doivent être des produits simples (sans déclinaison).<br/>
				Les légendes des photos et description longue de ces produits sont utilisées dans le bloc Cadeau en colonne de gauche et dans la page "Tous les cadeaux" en mode étendue.<br/>
				La description courte et le prix barré en cas de remise sur le produit sont affichés en popup lors du choix de cadeau en page résumé de commande.<br />
				Remarque: le module supporte les cadeaux dont le prix n\'est pas à zéro, ce produit est placé au panier comme s\'il s\'agissait d\'un cadeau.<br/>
				</p>';

			$retour .= '<p>&nbsp;</p><h4>Configuration</h4>
						<p>La configuration se fait par l\'onglet <a class="btn btn-default" href="'.Context::getContext()->link->getAdminLink('AdminOleagiftonorder').'">Promotions >> Cadeaux</a>.</p>';

			$retour .= '<p>&nbsp;</p><h4>Documentation</h4><p>La documentation vous donne des explications plus détaillées</p>';
		}
		else
		{
			$retour = '<h4>Gift category</h4>
				<p>In your catalog, you have to define a new category to contain all the gifts products that the module has to manage.<br/>
				If your product page in back-office doesn\'t offer the "Visibility:Nowhere" option, to be sure these gift-products will not be visible in your front office, you have to create a customer group that will contain no customer.<br />
				You then have to desactivate the gift category, to restrict it to this customer group and to declare it in the following configuration.
				</p>';

			$retour .= '<p>&nbsp;</p>
				<h4>Gift product</h4>
				<p>The products the module offers as gift must have their own product page in back-offcie, so that their price can be set to 0, either through final price, either through a discount of 100%.<br/>
				You have to set their "Visibility" to "Nowhere" so that they aren\'t visible in front-office.<br/>
				They are present only in the gift category and must be simple products, withour combination<br/>
				The images legend and the long description of thses products are used in the Gift block of the left column in front-office and in the All Gift page in extended mode.<br/>
				The short description and a stroked price in case of discount are displayed in a popup in the cart summary, while choosing the gift<br/>
				Notice: the module supports gift products with non-zero prices. This product is then added to the cart as if it was a gift
				</p>';
			$retour .= '<p>&nbsp;</p><h4>Configuration</h4>
						<p>The configuration is done througth the <a class="btn btn-default" href="'.Context::getContext()->link->getAdminLink('AdminOleagiftonorder').'">Prices Rules >> Gifts</a> tab.</p>';

			$retour .= '<p>&nbsp;</p><h4>Documentation</h4><p>The documentation will give you more detailled explanations.</p>';
		}
		return $retour;
	}

	public function renderForm()
	{
		$fields_form = array(
			'form' => array(
				'description' => $this->getDescriptionText(),
				'legend' => array(
					'title' => $this->l('Settings'),
					'icon' => 'icon-cogs'
				),
				'input' => array(
					array(
						'type' => 'categories',
						'desc' => $this->l('Category containing the gift products'),
						'label' => $this->l('Gifts category:'),
						'name' => 'olea_giftonorder_gift_category',
						'tree' => array(
							'root_category' => (int)Configuration::get('PS_HOME_CATEGORY'),
							'id' => 'categories-tree',
							'name' => 'olea_giftonorder_gift_category_inside',
							'selected_categories' => array(
								Tools::getValue ('olea_giftonorder_gift_category', Configuration::get ('OLEA_GIFTONORDER_GIFT_CATEGORY'))
							),
							'disabled_categories' => null,
							'use_search' => true
						)
					),
				),
				'submit' => array(
					'title' => $this->l('Save'),
					'class' => 'btn btn-default pull-right'
				)
			)
		);

		$helper = new HelperForm ();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language ((int)Configuration::get ('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->allow_employee_form_lang = Configuration::get ('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get ('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$this->fields_form = array();

		$helper->identifier = $this->identifier;
		$helper->submit_action = 'submitGooConfig';
		$helper->currentIndex = $this->context->link->getAdminLink ('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
		$helper->token = Tools::getAdminTokenLite ('AdminModules');
		$helper->tpl_vars = array(
			'fields_value' => $this->getConfigFieldsValues (),
			'languages' => $this->context->controller->getLanguages (),
			'id_language' => $this->context->language->id
		);

		$patch_click_160 = (version_compare (_PS_VERSION_, '1.6.2')) ? '<script type="text/javascript">
	    								$(document).ready(function () {
	    										console.log("Changing");
	    										$("#categories-tree").find(":input[type=radio]").unbind("click");
	    								});
	    							</script>' : '';

		return $helper->generateForm (array(
			$fields_form
		)).$patch_click_160;
	}

	public function getConfigFieldsValues()
	{
		return array();
		// 'olea_giftonorder_gift_category' => Tools::getValue('olea_giftonorder_gift_category', Configuration::get('OLEA_GIFTONORDER_GIFT_CATEGORY')),

	}

	public function displayForm()
	{
		$id_category = $this->id_category_gift;

		$retour = '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
			<fieldset>
				<legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Settings').'</legend>';
		$retour .= '<label>'.$this->l('Gift category').'</label>
				<div class="margin-form">';
		$helper = new Helper ();
		$retour .= $helper->renderCategoryTree (null, array(
			(int)$id_category
		), 'id_gift_category', true, false, array(), false, true);

		$retour .= '
				</div>

				<center><input type="submit" name="submitGiftCategory" value="'.$this->l('Save').'" class="button" /></center>
				';

		if (version_compare (_PS_VERSION_, '1.2', '<'))
		{
			if ($this->context->cookie->id_lang == 2)
				$retour .= "<p>N'oubliez pas de copier : <br />
				- le fichier AdminGiftonorder.php dans le répertoire 'adminXXX/tabs' de votre installation,<br />
				- le fichier Giftonorder.php dans le répertoire 'classes' de votre installation
				</p>";
			else
				$retour .= "<p>Don't forget to copy <br />
				- file AdminGiftonorder.php into the 'adminXXX/tabs' directory of your installation,<br />
				- file Giftonorder.php into the 'classes' directory of your installation
				</p>";
		}

		$retour .= '
				</fieldset>
			<p class="clear"></p>
			<fieldset class="width3"><legend>'.$this->l('Information').'</legend>
			<p>'.$this->l('Configuration done through tab ORDER>>GIFTS').'</p>
			<p>'.$this->l('Module version').' '.$this->version.' '.$this->l('developped by').' <b><a href="http://www.oleacorner.com" target="_blank">OleaCorner</a></b></p>
			</fieldset>

		</form>';

		return $retour;
	}

	public function recurseCategory($categories, $current, $id_category = 1, $id_selected = 1)
	{
		$retour = '<option value="'.$id_category.'"'.(($id_selected == $id_category) ? ' selected="selected"' : '').'>';
		if (version_compare (_PS_VERSION_, '1.4') < 0)
			$catName = Category::hideCategoryPosition (Tools::stripslashes ($current['infos']['name']));
		else
			$catName = Tools::stripslashes ($current['infos']['name']);
		$retour .= str_repeat ('&nbsp;', $current['infos']['level_depth'] * 5).$catName.'&nbsp;</option>';
		if (isset ($categories[$id_category]))
			foreach ($categories[$id_category] as $key => $row)
				$retour .= $this->recurseCategory ($categories, $categories[$id_category][$key], $key, $id_selected);
		return $retour;
	}

	public function hookCartRefreshForGift()
	{
		if (!$this->is_version_ok ())
			return '';
		if (version_compare (_PS_VERSION_, '1.2', '>='))
			include_once (dirname (__FILE__).'/Giftonorder.php');

		if (version_compare ('1.5', _PS_VERSION_) <= 0)
		{
			$cart = Context::getContext ()->cart;
			if (!isset ($cart) || $cart->id == 0)
				return;
		}
		else
		{
			$id_cart = (int)($this->context->cookie->id_cart);
			if ($id_cart == 0)
				return;
			$cart = new Cart ($id_cart);
		}

		$initial_products = array();
		foreach ($cart->getProducts () as $pinfo)
			$initial_products[] = $pinfo['id_product'];

			/* Delete all products from cart that are gift */
		$productsInCart = Giftonorder::splitCartContent ($cart);
		$todel = array();
		$product_of_gift = array();
		foreach ($productsInCart as $prod)
		{
			if ($prod['is_gift'])
			{
				$cart->deleteProduct ($prod['id_product'], 0, 0);
				$todel[$prod['id_product']] = $prod['id_product'];
				$product_of_gift[(int)($prod['id_giftonorder'])] = $prod['id_product'];
			}
		}

		if (count ($todel))
		{
			$sqlReq = 'DELETE FROM `'._DB_PREFIX_.'giftonorder_order`
						WHERE `id_cart`='.(int)($this->context->cookie->id_cart);
			$res = Db::getInstance ()->Execute ($sqlReq);
		}

		/* In case some gift were added directly to the cart */
		$all_unexpected = Giftonorder::getAllGiftProducts ($this->context->cookie->id_lang);
		if (is_array ($all_unexpected))
			foreach ($all_unexpected as $p)
				$cart->deleteProduct ($p['id_product'], 0, 0);

			/* No gift if empty cart */
		if (count ($productsInCart) - count ($todel) <= 0)
			return;

		/**
		 * Case of gift choice in step 1 of order.php *
		 */
		$submitted_giftonorder = (int)(Tools::getValue ('id_giftonorder'));
		$submitted_id_product = (int)(Tools::getValue ('gift_id_product'));
		if ($submitted_giftonorder != 0 && $submitted_id_product != 0)
		{
			$giftonorder = new Giftonorder ($submitted_giftonorder);
			if ($submitted_id_product == $giftonorder->gift_id_product || in_array ($submitted_id_product, explode (',', $giftonorder->gift_id_product_list)))
				$product_of_gift[$submitted_giftonorder] = $submitted_id_product;
		}
		/* re-add gift depending on cart content */
		$potentialGifts = Giftonorder::getPotentialGift ((int)($this->context->cookie->id_customer), (int)($this->context->cookie->id_lang));
		if ((int)(Configuration::get ('OLEA_GIFTONORDER_AMOUNT_REDUC')) == 0)
			$total_amount = $cart->getOrderTotal (true, 1);
		else
			$total_amount = $cart->getOrderTotal (true, 4);

		if (!$this->is_before_14)
		{	// 04/5/05/2012 : behavior on 1.3 not tested
			// $total_amount = Tools::convertPrice($total_amount, Currency::getDefaultCurrency(), true);
			$currency = Context::getContext ()->currency;
			if ($currency->conversion_rate != 0)
				$total_amount = $total_amount / $currency->conversion_rate;
		}

		/*
		 * $discounts = array();
		 * foreach ($cart->getDiscounts() as $d)
		 * if (array_key_exists($d['name'], $discounts))
		 * $discounts[$d['name']] += 1;
		 * else
		 * $discounts[$d['name']] = 1;
		 */
		if (version_compare ('1.5', _PS_VERSION_) < 0)
		{
			// error_log('Method '.__METHOD__.', discounts to be reviewed, line '.__LINE__.', file '.__FILE__);
			$discounts = array();
		}
		else
			$discounts = $cart->getDiscounts ();

		$products_to_add = array();
		foreach ($potentialGifts as $potential)
		{
			$isToAdd = Giftonorder::giftIsToAdd ($potential, $total_amount, (int)($this->context->cookie->id_customer), $productsInCart, $discounts);
			if ($isToAdd['value'] == 'OK')
			{
				if (array_key_exists ($potential['id_giftonorder'], $product_of_gift))
					$id_product_to_add = (int)($product_of_gift[$potential['id_giftonorder']]);
				else
					$id_product_to_add = $potential['gift_id_product'];
				if (!array_key_exists ($id_product_to_add, $products_to_add))
					$products_to_add[$id_product_to_add] = array(
						'qty' => 0,
						'giftonorder' => array(),
						'allow_other_gift' => false
					);
				$products_to_add[$id_product_to_add]['qty'] += (int)($isToAdd['qty']);
				$products_to_add[$id_product_to_add]['giftonorder'][$potential['id_giftonorder']] = $potential['id_giftonorder'];
				$products_to_add[$id_product_to_add]['allow_other_gift'] = $potential['allow_other_gift'];
				if (!$potential['allow_other_gift'])
					break;
			}
			else
			{
				if ($isToAdd['value'] == 'amount')
					$txt = $isToAdd['value'].'(cart='.$cart->id.'/missing='.$isToAdd['missing_amount'].')';
				else
					$txt = '';
				$this->loghistory ((int)($this->context->cookie->id_cart), (int)($this->context->cookie->id_customer), $potential['id_giftonorder'], $txt);
			}
		}

		$preselectedgifts = Giftonorder::get_preselected_gifts ($cart);
		$p = array();
		foreach ($potentialGifts as $potential)
		{
			$isToAdd = Giftonorder::giftIsToAdd ($potential, $total_amount, (int)($this->context->cookie->id_customer), $productsInCart, $discounts);
			if ($isToAdd['value'] == 'OK')
			{
				if (array_key_exists ($potential['id_giftonorder'], $product_of_gift))
					$product_to_add = (int)($product_of_gift[$potential['id_giftonorder']]);
				else
					$product_to_add = (isset ($preselectedgifts[$potential['id_giftonorder']])) ? $preselectedgifts[$potential['id_giftonorder']] : $potential['gift_id_product'];
				$updateOK = $cart->updateQty ((int)($isToAdd['qty']), $product_to_add, 0, 0, 'up');
				if ($updateOK)
				{
					$p[] = '('.$potential['id_giftonorder'].','.(int)($this->context->cookie->id_cart).','.$product_to_add.', 0, 0, 0)';
					$txt = 'Added prod_id='.$product_to_add.(($potential['allow_other_gift']) ? ' - checking next' : ' - no next');
					$this->loghistory ((int)($this->context->cookie->id_cart), (int)($this->context->cookie->id_customer), $potential['id_giftonorder'], $txt);
					if (!$potential['allow_other_gift'])
						break;
				}
				else
					$this->loghistory ((int)($this->context->cookie->id_cart), (int)($this->context->cookie->id_customer), $potential['id_giftonorder'], 'error adding to cart');
			}
			else
				$this->loghistory ((int)($this->context->cookie->id_cart), (int)($this->context->cookie->id_customer), $potential['id_giftonorder'], $isToAdd['value']);
		}

		if (count ($p))
		{
			$sqlReq = 'INSERT INTO `'._DB_PREFIX_.'giftonorder_order` (id_giftonorder, id_cart, id_product, id_combination,  id_order, id_customer) VALUES '.implode (',', $p);
			$res = Db::getInstance ()->Execute ($sqlReq);
		}

		// $tmp_prods = $cart->getProducts(false); // Without refresh
		$final_products = array();
		foreach ($cart->getProducts () as $pinfo)
			$final_products[] = $pinfo['id_product'];
		if ((count (array_intersect ($initial_products, $final_products)) != count ($initial_products) || count ($initial_products) != count ($final_products)) && (int)Tools::getValue ('allow_refresh') > 0)
			Context::getContext ()->controller->oleaSetAjaxrefresh (true);
	}

	/* ----------------------------------------------------------------------- */
	public function hookNewOrder($params /*$cart, $order, $customer, $currency, $orderStatus*/)
	{
		if (!$this->is_version_ok ())
			return '';

		$sqlReq = 'UPDATE `'._DB_PREFIX_.'giftonorder_order`
					SET id_order =  '.$params['order']->id.',
						id_customer = '.$params['customer']->id.'
					WHERE id_cart = '.$params['cart']->id;
		return Db::getInstance ()->Execute ($sqlReq);
	}

	/* ----------------------------------------------------------------------- */
	public function hookRightColumn($params)
	{
		if (!$this->is_version_ok ())
			return '';

		include_once (dirname (__FILE__).'/Giftonorder.php');

		$nextToAdd = Giftonorder::getNextGiftToAttribute ((int)($this->context->cart->id), (int)($this->context->customer->id), (int)($this->context->cookie->id_lang));
		if (count ($nextToAdd) == 0)
		{
			$potentialGifts = Giftonorder::getPotentialGift ((int)($this->context->customer->id), (int)($this->context->cookie->id_lang), true);
			if (count ($potentialGifts) != 0)
				$nextToAdd = $potentialGifts[0];
		}

		if (count ($nextToAdd) != 0)
		{
			if (array_key_exists ('missing_amount', $nextToAdd))
				$nextToAdd['missing_amount'] = Tools::convertPrice ($nextToAdd['missing_amount'], Context::getContext ()->currency, true);
			$this->smarty->assign (array(
				'gift' => $nextToAdd,
				'oleasmallSize' => Image::getSize ('small'),
				'oleamediumSize' => Image::getSize ('medium')
			));
		}
		/*
		// $allgifts = Giftonorder::getPotentialGift((int)($this->contect->cookie->id_customer), (int)($this->contect->cookie->id_lang));

		// $this->smarty->assign(array(
		// 'blockallgifts' => $allgifts
		// ));
		 *
		 */
		return $this->display (__FILE__, 'blockgiftonorder.tpl');
	}

	public function hookLeftColumn($params)
	{
		return $this->hookRightColumn ($params);
	}

	public function hookShoppingCart($params)
	{
		if (!$this->is_version_ok ())
			return '';

		if (version_compare (_PS_VERSION_, '1.2', '>='))
			include_once (dirname (__FILE__).'/Giftonorder.php');

		$potentialGifts = Giftonorder::getPotentialGift ((int)($this->context->cookie->id_customer), (int)($this->context->cookie->id_lang));
		if ((int)(Configuration::get ('OLEA_GIFTONORDER_AMOUNT_REDUC')) == 0)
			$total_amount = $params['cart']->getOrderTotal (true, 1);
		else
			$total_amount = $params['cart']->getOrderTotal (true, 4);

		if (!$this->is_before_14)
		{	// 04/5/05/2012 : behavior on 1.3 not tested
			// $total_amount = Tools::convertPrice($total_amount, Currency::getDefaultCurrency(), true);
			$currency = Context::getContext ()->currency;
			if ($currency->conversion_rate != 0)
				$total_amount = $total_amount / $currency->conversion_rate;
		}

		$productsInCart = Giftonorder::splitCartContent ($params['cart']);
		$selectedProducts = array();
		foreach ($productsInCart as $productincart)
			$selectedProducts[(int)($productincart['id_giftonorder'])] = (int)($productincart['id_product']);

			/*
		 * $discounts = array();
		 * foreach ($params['cart']->getDiscounts() as $d)
		 * if (array_key_exists($d['name'], $discounts))
		 * $discounts[$d['name']] += 1;
		 * else
		 * $discounts[$d['name']] = 1;
		 */
		if (version_compare ('1.5', _PS_VERSION_) <= 0)
		{
			// error_log('Method '.__METHOD__.'(), discounts to be reviewed at line '.__LINE__.', file '.__FILE__);
			$discounts = array();
		}
		else
			$discounts = $params['cart']->getDiscounts ();

		$gifts_attributed = array();
		foreach ($potentialGifts as $potential)
		{
			$isToAdd = Giftonorder::giftIsToAdd ($potential, $total_amount, (int)($this->context->cookie->id_customer), $productsInCart, $discounts);
			if ($isToAdd['value'] == 'OK')
			{
				$potential['gift_products_list'] = array();
				foreach (explode (',', $potential['gift_id_product_list']) as $p_id)
				{
					$p = new Product ($p_id, false, (int)($this->context->cookie->id_lang));
					$p->price_without_reduction_wtx = Product::getPriceStatic ($p->id, true, null, 2, null, false, false);
					$p->price_without_reduction_wotx = Product::getPriceStatic ($p->id, false, null, 2, null, false, false);
					$res_image = Image::getImages ((int)($this->context->cookie->id_lang), $p->id);
					$p->id_image = '';
					if (count ($res_image))
						foreach ($res_image as $img)
						{
							if ($img['cover'] == '1')
							{
								$p->id_image = $img['id_product'].'-'.$img['id_image'];
								$p->legend = (isset ($img['legend']) && $img['legend'] != '') ? $img['legend'] : $p->name;
							}
						}
					if ($p->id_image == '')
					{
						$p->id_image = Language::getIsoById ($this->context->cookie->id_lang).'-default';
						$p->legend = $p->name;
					}
					$p->is_selected = (isset ($selectedProducts[$potential['id_giftonorder']]) && ($selectedProducts[$potential['id_giftonorder']] == $p_id)) ? true : false;
					$potential['gift_products_list'][] = $p;
				}
				$gifts_attributed[] = $potential;
				if (!$potential['allow_other_gift'])
					break;
			}
		}

		$this->smarty->assign (array(
			'gifts_attributed' => $gifts_attributed
		));

		$nextToAdd = Giftonorder::getNextGiftToAttribute ($params['cart']->id, (int)($this->context->cookie->id_customer), (int)($this->context->cookie->id_lang));
		if (count ($nextToAdd) == 0)
		{
			$this->smarty->assign (array(
				'product' => '',
				'has_next' => false
			));
		}
		else
		{
			$product = new Product ($nextToAdd['gift_id_product'], false, (int)($this->context->cookie->id_lang));
			$product->legend = $product->name;
			$images = $product->getImages ((int)($this->context->cookie->id_lang));
			if (count ($images))
				foreach ($images as $image)
				{
					if ($image['cover'] == 1 && array_key_exists ('legend', $image))
						$product->legend = $image['legend'];
				}
			if (!array_key_exists ('missing_amount', $nextToAdd))
				$nextToAdd['missing_amount'] = 0;

			$this->smarty->assign (array(
				'next_gift' => $nextToAdd,
				'missing_amount' => (($this->is_before_14) ? $nextToAdd['missing_amount'] : Tools::convertPrice ($nextToAdd['missing_amount'], Context::getContext ()->currency, true)), // 04/04/2012 : not tested on 1.3
				'missing_otherproducts' => $nextToAdd['missing_otherproducts'],
				'product' => $product,
				'has_next' => true
			));
		}

		$this->smarty->assign (array(
			'is_v11' => version_compare (_PS_VERSION_, '1.2', '<'),
			'oleasmallSize' => Image::getSize ('small'),
			'oleamediumSize' => Image::getSize ('medium')
		));
		return $this->display (__FILE__, 'shoppingcart.tpl');
	}

	public function hookShoppingCartExtra($params)
	{
		return '';
	}

	public function hookDisplayBackOfficeFooter($params)
	{
		if ((isset (Context::getContext ()->controller->module) && Context::getContext ()->controller->module->name == $this->name) || (Tools::getValue ('controller') == 'AdminModules' && Tools::getValue ('configure') == $this->name))
		{
			$lang = new Language ($this->context->cookie->id_lang);
			$support_link = ($lang->iso_code == 'fr') ? 'https://addons.prestashop.com/fr/ecrire-au-developpeur?id_product=442'
														: 'https://addons.prestashop.com/en/write-to-developper?id_product=442';

			$cookie = Context::getContext()->cookie;
			$path = '../modules/'.$this->name.'/';
			$lang = new Language($cookie->id_lang);
			$filename = 'readme_'.$lang->iso_code.'.pdf';
			if (!file_exists(dirname(__FILE__).'/'.$filename))
			{
				$filename = 'readme_en.pdf';
				if (!file_exists(dirname(__FILE__).'/'.$filename))
					$filename = '';
			}

			$this->smarty->assign (array(
				'module_name_str' => sprintf ($this->l('Module %s, version %s'), $this->displayName, $this->version),
				'developped_str' => $this->l('Developped by'),
				'modules_str' => $this->l('Our modules'),
				'olea_support_link' => $support_link,
				'olea_readme_file' => $filename,
			));
			return $this->display (__FILE__, 'backofficefooter.tpl');
		}
		else
			return '';
	}

	public function hookDisplayAdminOptions($params)
	{
		return $this->hookDisplayBackOfficeFooter ($params);
	}

	public function hookHeader($params)
	{
		$this->context->controller->addCSS (($this->_path).'views/css/giftonorder.css', 'all');
		$this->context->controller->addJS ($this->_path.'views/js/giftonorder_preselection.js');
		$this->context->controller->addJqueryPlugin (array(
			'cluetip'
		));
	}

	public function hookTop($params)
	{
		if (!$this->is_version_ok ())
			return '';

		include_once (dirname (__FILE__).'/Giftonorder.php');

		$nextToAdd = Giftonorder::getNextGiftToAttribute ((int)($this->context->cart->id), (int)($this->context->customer->id), (int)($this->context->cookie->id_lang));

		if (array_key_exists ('missing_amount', $nextToAdd))
			$nextToAdd['missing_amount'] = Tools::convertPrice ($nextToAdd['missing_amount'], Context::getContext ()->currency, true);

		if (count ($nextToAdd) != 0)
		{
			$this->smarty->assign (array(
				'gift' => $nextToAdd
			));
		}

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

	public function hookGooExtraRight($params)
	{
		return $this->hookExtraRight ($params);
	}

	public function hookExtraRight($params)
	{
		if (version_compare (_PS_VERSION_, '1.4') < 0)
			return '';

		$id_product = (int)Tools::getValue ('id_product');
		if ($id_product == 0)
			return '';

		$submit_id_giftonorder = 0;
		$submit_id_gift = 0;
		$select_gift_submitted = Tools::getValue ('giftonorder_select_gift');
		if ($select_gift_submitted != '')
		{
			list ($submit_id_giftonorder, $submit_id_gift) = Tools::split ('_', $select_gift_submitted);
			$submit_id_giftonorder = (int)$submit_id_giftonorder;
			$submit_id_gift = (int)$submit_id_gift;
		}

		include_once (dirname (__FILE__).'/Giftonorder.php');
		$product = new Product ($id_product);
		// $gifts = Giftonorder::getFilteredGiftsOfProduct($id_product, $this->context->cookie->id_lang);
		$potentialGifts = Giftonorder::getPotentialGift ($this->context->cookie->id_customer, $this->context->cookie->id_lang);
		$gift_to_display = array();
		$preselectedgifts = Giftonorder::get_preselected_gifts ($this->context->cart);
		$save_preselected = false;
		$selectedgifts_default = array();
		// $selectedgifts_submitted = array(); // à récupérer du panier
		foreach ($potentialGifts as $potential)
		{
			// exclude giftonorder for which preselection is not to be displayed
			if (!$potential['gift_preselector_product_page'])
				continue;
				// exclude giftonorder for which categories are not OK
			$common_categories = array_intersect (Product::getProductCategories ($product->id), array_diff (explode (';', $potential['criteria_categories']), array(
				(int)(Configuration::get ('OLEA_GIFTONORDER_GIFT_CATEGORY'))
			)));
			if (isset ($common_categories) && count ($common_categories) == 0)
				continue;
				// exclude giftonorder for which product prices is lower then required cart amount
				// if ($product->getPrice() < (float)$potential['criteria_cart_amount'] && $cart->getOrderTotal() < (float)$potential['criteria_cart_amount'])
				// continue;

			$selectedgifts_default[$potential['id_giftonorder']] = $potential['gift_id_product'];
			$potential['gift_products_list'] = array();
			$potential['index_selected_gift'] = 0;
			$gift_list_for_loop = explode (',', $potential['gift_id_product_list']);
			if (!isset ($preselectedgifts[$potential['id_giftonorder']]))
				$preselectedgifts[$potential['id_giftonorder']] = $selectedgifts_default[$potential['id_giftonorder']];
			if ($submit_id_giftonorder == $potential['id_giftonorder'] && in_array ($submit_id_gift, $gift_list_for_loop))
			{
				$save_preselected = true;
				$preselectedgifts[$submit_id_giftonorder] = $submit_id_gift;
			}
			foreach ($gift_list_for_loop as $k => $p_id)
			{
				$p = new Product ($p_id, false, (int)($this->context->cookie->id_lang));
				$p->price_without_reduction_wtx = Product::getPriceStatic ($p->id, true, null, 2, null, false, false);
				$p->price_without_reduction_wotx = Product::getPriceStatic ($p->id, false, null, 2, null, false, false);
				$res_image = Image::getImages ((int)($this->context->cookie->id_lang), $p->id);
				$p->id_image = '';
				if (count ($res_image))
					foreach ($res_image as $img)
					{
						if ($img['cover'] == '1')
						{
							$p->id_image = $img['id_product'].'-'.$img['id_image'];
							$p->legend = (isset ($img['legend']) && $img['legend'] != '') ? $img['legend'] : $p->name;
						}
					}
				if ($p->id_image == '')
				{
					$p->id_image = Language::getIsoById ($this->context->cookie->id_lang).'-default';
					$p->legend = $p->name;
				}
				if ($p_id == $preselectedgifts[$potential['id_giftonorder']])
					$potential['index_selected_gift'] = $k;
				$potential['gift_products_list'][] = $p;
			}
			$gift_to_display[] = $potential;
			if (!$potential['allow_other_gift'])
				break;
		}

		if ($save_preselected)
			Giftonorder::save_preselected_gifts ($this->context->cart, $preselectedgifts);

			// error_log('to display = '.print_r($gift_to_display, true));
		$this->smarty->assign (array(
			'giftonorder_gifts_of_product' => $gift_to_display
		));

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

	/*
	 * *******************************************************************************
	 */
	public function reset_logs()
	{
		$hdl = @fopen (_PS_ROOT_DIR_.$this->_logfilename, 'w+');
		if ($hdl)
		{
			fclose ($hdl);
			return '';
		}
		else
			return $this->l("Can't access in write mode to file").' : '.$this->_logfilename;
	}

	public function get_logs()
	{
		Tools::redirectAdmin (_MODULE_DIR_.'/'.$this->name.'/getfile.php?file='.$this->_logfilename);
	}

	public function loghistory($id_cart, $id_customer, $id_giftonorder, $msg)
	{
		$txt = date ('d-m-Y H:i:s.u').' / cart='.$id_cart.' / cust='.$id_customer.' / gift='.$id_giftonorder.' / msg:'.$msg;
		if ($this->_logfilehdl)
			fwrite ($this->_logfilehdl, $txt."\n");
	}
}

