<?php
/**
 * AM Message Info Clients
 *
 * @author    Arnaud Merigeau <contact@arnaud-merigeau.fr> - https://www.arnaud-merigeau.fr
 * @copyright Arnaud Merigeau 2020 - https://www.arnaud-merigeau.fr
 * @license   Free
 * @version   1.0.0
 *
 */

if (!defined( '_PS_VERSION_' ))
	exit;



class AMMESSAGEINFOCLIENTS extends Module
{
	public function __construct()
	{
		$this->name = 'ammessageinfoclients';
		$this->description = 'Afficher un message pour vos clients';
		$this->tab = 'front_office_features';
		$this->version = '1.1.0';
		$this->author = 'Arnaud Merigeau';
		$this->need_instance = 0;
		$this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.7');
		$this->monolanguage_content = 'Ammessageinfoclients_MONOLANGUAGE';
		$this->text_editor_content = 'Ammessageinfoclients_TEXTEDITOR';
		$this->module_position = 'Ammessageinfoclients_MODULEPOSITION';
		$this->content_wrapper_class = 'Ammessageinfoclients_CONTENTWRAPPER_CLASS';
		$this->content_wrapper_id = 'Ammessageinfoclients_CONTENTWRAPPER_ID';
		$this->bootstrap = true;
		$this->_html = '';
		$this->complete_content_files_location = dirname(__FILE__).'/content/';
		$this->simple_content_files_location = $this->_path.'content/';
		$this->ignore_changes_content_changes = false;

		parent::__construct();

		$this->displayName = $this->l('(AM) Message info clients');
		$this->description = $this->l('Afficher un message pour vos clients');

		$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');

		//store selection
		$this->selected_store_id = (!$this->emptyTest( Tools::getValue('contentbox_shop_select') ) )
								? (int)Tools::getValue('contentbox_shop_select')
								: $this->context->shop->id;
		//language selection
		$posted_mono_language = (Tools::getValue('monolanguage') != false)? (int)Tools::getValue('monolanguage') : null;

		if (Configuration::get( $this->monolanguage_content ) || !empty( $posted_mono_language ))
			$this->selected_language_id = (int)Configuration::get('PS_LANG_DEFAULT');
		else
		{
			$this->selected_language_id = ( !$this->emptyTest( Tools::getValue('contentbox_language_select') ))
									? (int)Tools::getValue('contentbox_language_select')
									: $this->context->language->id;
		}

		if (Tools::getValue('contentbox_language_select') != false && $this->selected_language_id != Tools::getValue('contentbox_language_select'))
			$this->ignore_changes_content_changes = true;
	}

	public function install()
	{
		if (Shop::isFeatureActive())
			Shop::setContext(Shop::CONTEXT_ALL);

		if (!parent::install() || !$this->registerHook('header') || !$this->registerHook('footer') || !AMMESSAGEINFOCLIENTSModel::createTables())
			return false;

		Configuration::updateValue($this->monolanguage_content, 0);
		Configuration::updateValue($this->text_editor_content, 1);

		Configuration::updateValue($this->module_position, 0);
		Configuration::updateValue($this->content_wrapper_class, '');
		Configuration::updateValue($this->content_wrapper_id, '');

		$this->_clearCache('template.tpl');

		return true;
	}

	public function uninstall()
	{
		$this->_clearCache('template.tpl');
		if (!parent::uninstall()
			|| !AMMESSAGEINFOCLIENTSModel::DropTables())
		{

			Configuration::deleteByName($this->monolanguage_content);
			Configuration::deleteByName($this->text_editor_content);

			Configuration::deleteByName($this->module_position);
			Configuration::deleteByName($this->content_wrapper_class);
			Configuration::deleteByName($this->content_wrapper_id);

			return false;
		}
		return true;
	}

	public function __call($method, $args)
	{
		//if method exists
		if (function_exists($method))
			return call_user_func_array($method, $args);

		//if head hook: add the css and js files
		if ($method == 'hookdisplayHeader')
			return $this->hookHeader( $args[0] );

		//check for a call to an hook
		if (strpos($method, 'hook') !== false)
			return $this->genericHookMethod( $args[0] );

	}

	public function addFilesToTemplate($path = null)
	{
		$result = true;
		//list the active files to add
		$files_data = AMMESSAGEINFOCLIENTSModel::getFilesInUse( $this->selected_store_id, $this->selected_language_id );
		if (empty( $files_data ) || gettype( $files_data['files'] ) == null)
			return $result;

		$files = Tools::jsonDecode( $files_data['files'] );

		if (empty( $files ))
			return $result;

		if (empty( $path ))
			$path = $this->simple_content_files_location;

		foreach ($files as $file)
		{
			switch ($file->extension)
			{
				case 'js':
					$this->context->controller->addJs($path.'/'.$file->name, 'all');
				break;
				case 'css':
					$this->context->controller->addCss($path.'/'.$file->name, 'all');
				break;
			}
		}

	}
	public function genericHookMethod()
	{
		$content_query = AMMESSAGEINFOCLIENTSModel::getContent( $this->selected_store_id, $this->selected_language_id );
		$pre_content = '';
		$pos_content = '';

		$module_position = Configuration::get($this->module_position);

		if (!empty( $module_position ) && !is_numeric( $module_position ))
		{
			$content_wrapper_class = Configuration::get($this->content_wrapper_class);
			$content_wrapper_id = Configuration::get($this->content_wrapper_id);

			$pre_content = '<'.$module_position.' ';
			$pre_content .= ( !empty( $content_wrapper_class ) )?' class="'.$content_wrapper_class.'" ' : '';
			$pre_content .= ( !empty( $content_wrapper_id ) )?' id="'.$content_wrapper_id.'" ' : '';
			$pre_content .= '>';
			$pos_content = '</'.$module_position.'>';
		}

		if (!isset($_COOKIE['message_info_clients']))
		{
			$this->context->smarty->assign(
				array(
					'content' => $pre_content.$content_query['content_text'].$pos_content,
					'ammic_color' => Configuration::get('Ammessageinfoclients_CONTENTWRAPPER_CLASS'),
					'ammic_bgcolor' => Configuration::get('Ammessageinfoclients_CONTENTWRAPPER_ID'),
					'ammic_position' => Configuration::get('Ammessageinfoclients_MODULEPOSITION'),
				)
			);
			return $this->display(__FILE__, 'views/templates/front/template.tpl');
		}
		return false;
	}

	public function hookHeader()
	{
		$this->context->controller->addCSS(($this->_path).'views/css/ammessageinfoclients.css', 'all');
		$this->context->controller->addJs(($this->_path).'views/js/ammessageinfoclients.js');
		$this->addFilesToTemplate( $this->_path.'content/' );
	}

	public function getContent()
	{
		if (!is_writable( $this->complete_content_files_location ))
			$this->_html .= $this->displayError( 'FOLDER PERMISSIONS ERROR: <br/>writing access denied on '.$this->simple_content_files_location.' <br/> ' );

		$this->processSubmit();
		return $this->displayForm() . $this->stayInTouch();
	}

	public function processSubmit()
	{
		if (Tools::isSubmit('submit'.$this->name))
		{
			//remove file
			if (!$this->emptyTest( Tools::getValue('delete_file') ))
			{
				$tmp_file = strip_tags(Tools::getValue('delete_file'));
				unlink($this->complete_content_files_location.$tmp_file);
				$this->_html .= $this->displayConfirmation( 'File Deleted' );
			}

			//if change shop or change language submit
			if (!$this->emptyTest( Tools::getValue('ignore_changes') ))
				return true;

			//upload file
			if ($this->hasFile())
				$this->processFileUpload();

			//if the posted language different from the current language -> ignore content changes
			if ((Tools::getValue('contentbox_language_select') != false && (int)Tools::getValue('contentbox_language_select') == $this->selected_language_id )
				|| (Tools::getValue('contentbox_language_select') == false
				&& (int)Configuration::get('PS_LANG_DEFAULT') == $this->selected_language_id ))
			{
				//store the content
				if (Tools::getValue('content_text') !== false && $this->ignore_changes_content_changes == false)
					AMMESSAGEINFOCLIENTSModel::setContent( Tools::getValue('content_text'), $this->selected_store_id, $this->selected_language_id );

				//store the files to be used
				if (Tools::getValue('headerFiles') !== false)
					AMMESSAGEINFOCLIENTSModel::setFiles(
							$this->processFilesList( Tools::getValue('headerFiles'), true ),
							$this->selected_store_id,
							$this->selected_language_id );
			}

			//store the developer configurations
			if (Tools::getIsset( 'monolanguage' ))
				Configuration::updateValue($this->monolanguage_content, (int)Tools::getValue('monolanguage'));

			if (Tools::getIsset( 'use_editor' ))
				Configuration::updateValue($this->text_editor_content, (int)Tools::getValue('use_editor'));

			if (Tools::getIsset( 'module_position' ))
				Configuration::updateValue($this->module_position, Tools::getValue('module_position'));

			if (Tools::getIsset( 'content_wrapper_class' ))
				Configuration::updateValue($this->content_wrapper_class, Tools::getValue('content_wrapper_class'));

			if (Tools::getIsset( 'content_wrapper_id' ))
				Configuration::updateValue($this->content_wrapper_id, Tools::getValue('content_wrapper_id'));

		}
	}

	private function processFileUpload()
	{
		//test files folder permissions
		if (!is_writable( $this->complete_content_files_location ))
			return false;

		if (file_exists($this->complete_content_files_location.$_FILES['upload_file']['name']))
		{
			$tmp_name = explode('.', $_FILES['upload_file']['name']);
			$tmp_ext = end($tmp_name);
			array_pop($tmp_name);
			$tmp_name = implode('.', $tmp_name);
			$tmp_new_img_name = $this->complete_content_files_location.$tmp_name;

			$control_loop = false;
			$tmp_i = 1;
			while ($control_loop == false)
			{
				if (file_exists($tmp_new_img_name.'('.$tmp_i.').'.$tmp_ext ))
					++ $tmp_i;
				else
				{
					$_FILES['upload_file']['name'] = $tmp_name.'('.$tmp_i.').'.$tmp_ext;
					$control_loop = true;
				}
			}
		}

		$move_result = move_uploaded_file($_FILES['upload_file']['tmp_name'], $this->complete_content_files_location.$_FILES['upload_file']['name']);

		if (empty( $move_result ))
			$this->_html .= $this->displayError( 'UPLOAD ERROR: <br/> There was an unknown error. Please try again.<br/> ' );
		else
			$this->_html .= $this->displayConfirmation( 'File Uploaded' );
	}

	public function displayForm()
	{
		$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');

		//use text editor
		$use_text_editor = (int)Configuration::get($this->text_editor_content);

		$module_position = Configuration::get($this->module_position);
		$content_wrapper_class = Configuration::get($this->content_wrapper_class);
		$content_wrapper_id = Configuration::get($this->content_wrapper_id);

		$shops_list = $this->getShopsList();
		$languages_list = $this->getLanguagesList();
		$files_list = $this->getFiles();
		$fields_form = array();
		$fields_form[]['form'] = array(
				'input' => array(
					array(
						'name' => 'topform',
						'type' => 'topform',
						'shops' => $shops_list,
						'current_shop_id' => $this->selected_store_id,
						'languages' => $languages_list,
						'current_language_id' => $this->selected_language_id,
						'monolanguage' => Configuration::get($this->monolanguage_content),
						'label' => ';)',
						'logoImg' => $this->_path.'img/logo.png',
						'moduleName' => $this->displayName,
						'moduleDescription' => $this->description,
						'moduleVersion' => $this->version,
					),
				),
			);
		$fields_form[]['form'] = array(
				'tinymce' => true,
				'legend' => array(
					'title' => $this->l('Contenu du message affiché'),
				),
				'input' => array(
					array(
						'type' => 'textarea',
						'name' => 'content_text',
						'label' => $this->l("Message"),
						'cols' => 50,
						'rows' => 5,
						'class' => '',
						'desc' => $this->l('Exemple de message : La boutique XXXX reste ouverte. Suite aux évènements actuels, nous continuons actuellement à assurer l\'envoi de vos colis à domicile via XXXX. Merci pour votre compréhension. L\'équipe XXXX.'),
						'autoload_rte' => false,
					),
					array(
						'type' => 'free',
						'name' => 'cookie',
						'label' => $this->l("Cookies"),
						'desc' => $this->l('Ce module affiche un message à vos clients tous les jours pour informer en temps réel. Le cookie est stocké pour 1 jour par vos clients.'),
					),
					// array(
					// 	'name' => 'files_area',
					// 	'type' => 'files_area',
					// 	'label' => $this->l("Module's Files"),
					// 	'files' =>  $files_list,
					// 	'path' => $this->_path,
					// 	'imagesExtensions' => array( 'jpg','gif','png' ),
					// ),
					// array(
					// 	'type' => 'file',
					// 	'name' => 'upload_file',
					// 	'path' => $this->_path,
					// 	'imagesExtensions' => array( 'jpg','gif','png' ),
					// ),

				),
				'submit' => array(
					'title' => $this->l('Save'),
				),
			);

		$fields_form[]['form'] = array(
				'legend' => array(
					'title' => $this->l('Options'),
				),
				'input' => array(
					// array(
					// 	'type' => 'select',
					// 	'name' => 'monolanguage',
					// 	'label' => $this->l('Utiliser seulement les options de la langue principale'),
					// 	'options' => array(
					// 		'query' => array(
					// 			array(
					// 				'value' => 0,
					// 				'text' => $this->l('Non'),
					// 			),
					// 			array(
					// 				'value' => '1',
					// 				'text' => $this->l('Oui'),
					// 			),
					// 		),
					// 		'id' => 'value',
					// 		'name' => 'text'
					// 	)
					// ),
					// array(
					// 	'type' => 'select',
					// 	'name' => 'use_editor',
					// 	'label' => $this->l('Use Text Editor'),
					// 	'options' => array(
					// 		'query' => array(
					// 			array(
					// 				'value' => 0,
					// 				'text' => $this->l('No'),
					// 			),
					// 			array(
					// 				'value' => '1',
					// 				'text' => $this->l('Yes'),
					// 			),
					// 		),
					// 		'id' => 'value',
					// 		'name' => 'text'
					// 	)
					// ),
					// array(
					// 	'type' => 'select',
					// 	'name' => 'headerFiles[]',
					// 	'label' => $this->l('Load Files on HTML Header'),
					// 	'desc' => $this->l('Please select above the files to be used.'),
					// 	'multiple' => true,
					// 	'options' => array(
					// 		'query' => $this->filterFiles( $files_list ),
					// 		'id' => 'name',
					// 		'name' => 'name'
					// 	)
					// ),
					array(
						'type' => 'select',
						'name' => 'module_position',
						'label' => $this->l('Position du message'),
						'options' => array(
							'query' => array(
								array(
									'value' => 0,
									'text' => $this->l('Bas'),
								),
								array(
									'value' => '1',
									'text' => $this->l('Haut'),
								),
								array(
									'value' => '2',
									'text' => $this->l('Gauche'),
								),
								array(
									'value' => '3',
									'text' => $this->l('Droite'),
								),
							),
							'id' => 'value',
							'name' => 'text'
						)
					),
					array(
						'type' => 'color',
						'class' => 'content_wrapper_class',
						'name' => 'content_wrapper_class',
						// 'disabled' => ( (empty( $content_wrapper ))? true:false ),
						'label' => $this->l('Couleur du texte'),
						// 'desc' => $this->l('Place the Content Wrapper .class here.'),
					),
					array(
						'type' => 'color',
						'class' => 'content_wrapper_id',
						'name' => 'content_wrapper_id',
						// 'disabled' => ( (empty( $content_wrapper ))? true:false ),
						'label' => $this->l('Couleur de fond'),
						// 'desc' => $this->l('Place the Content Wrapper #id here.'),
					),
				),
				'submit' => array(
					'title' => $this->l('Save'),
				),
			);
		$helper = new HelperForm();

		// Module, t    oken and currentIndex
		$helper->module = $this;
		$helper->name_controller = $this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;

		// Language
		$helper->default_form_language = $default_lang;
		$helper->allow_employee_form_lang = $default_lang;

		// Title and toolbar
		$helper->title = $this->displayName;
		$helper->show_toolbar = true;	 // false -> remove toolbar
		$helper->toolbar_scroll = true;	 // yes - > Toolbar is always visible on the top of the screen.
		$helper->submit_action = 'submit'.$this->name;
		$helper->toolbar_btn = array(
			'save' =>
				array(
					'desc' => $this->l('Save'),
					'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
					'&token='.Tools::getAdminTokenLite('AdminModules'),
				),
			'back' => array(
				'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
				'desc' => $this->l('Back to list')
			)
		);
		// Load current value
		$content_query = AMMESSAGEINFOCLIENTSModel::getContent( $this->selected_store_id, $this->selected_language_id );

		$content_field = ( !empty( $content_query ) )? $content_query['content_text'] : '';

		$helper->fields_value['content_text'] = $content_field;

		$helper->fields_value['monolanguage'] = Configuration::get($this->monolanguage_content);
		$helper->fields_value['use_editor'] = $use_text_editor;

		$helper->fields_value['headerFiles[]'] = $this->processSelectFilesForMultiselect(
																AMMESSAGEINFOCLIENTSModel::getFilesInUse( $this->selected_store_id, $this->selected_language_id )
																);

		$helper->fields_value['module_position'] = $module_position;
		$helper->fields_value['content_wrapper_class'] = $content_wrapper_class;
		$helper->fields_value['content_wrapper_id'] = $content_wrapper_id;

		if (isset( $this->context ) && isset( $this->context->controller ))
		{
			$this->context->controller->addJs($this->_path.'/js/ammessageinfoclients.js');
			$this->context->controller->addCss($this->_path.'/css/ammessageinfoclients.css');

		}
		else
		{
			Tools::addJs($this->_path.'/js/ammessageinfoclients.js');
			Tools::addCss($this->_path.'/css/ammessageinfoclients.css');

		}
		return $this->_html.$helper->generateForm($fields_form);
	}

	private function filterFiles($files = array(), $accepted_files = array( 'css', 'js' ))
	{
		$result = array();

		$result[] = array( 'name' => 'none' );

		foreach ($files as $file)
		{
			if (in_array( $file['extension'], $accepted_files ))
				$result[] = $file;
		}
		return $result;
	}

	private function processSelectFilesForMultiselect($files_data = array())
	{
		if (gettype( $files_data['files'] ) != null)
			$files_data = $files_data['files'];

		$files_type = gettype( $files_data );

		$files = ( $files_type == 'string' )? Tools::jsonDecode($files_data) : $files_data;

		$result = array();

		if (!empty( $files ))
		{
			foreach ($files as $file)
				$result[] = ( is_object( $file ) )? $file->name : $file['name'];
		}

		if (empty( $result ))
			$result[] = 'none';

		return $result;
	}
	private function getLanguagesList()
	{
		$languages_list = array();
		$langs = Language::getLanguages(false);

		foreach ($langs as $lang)
			$languages_list[] = array( 'id_lang' => $lang['id_lang'], 'name' => $lang['name'] );

		return $languages_list;
	}

	private function getShopsList()
	{
		$shops_list = array();
		$shops = Shop::getShops();
		foreach ($shops as $shop)
			$shops_list[] = array( 'id_shop' => $shop['id_shop'], 'name' => $shop['name'] );

		return $shops_list;
	}

	private function getFiles()
	{
		$tmp_files_info = array();

		$handle = opendir($this->complete_content_files_location);

		while (false !== ($file = readdir($handle)))
		{
			if ($file == '.' || $file == '..')
				continue;

			$tmp_files_info[] = $this->extractFileInfo( $file );
		}
		closedir($handle);
		sort($tmp_files_info);

		return $tmp_files_info;
	}

	private function processFilesList($files_list, $join_by_extension = false)
	{
		if (!is_array( $files_list ))
			return array();

		$data_out = array();
		foreach ($files_list as $file)
			$data_out[] = $this->extractFileInfo( $file );

		if (!empty( $join_by_extension ))
		{
			$temp_container = array();

			//group by extension
			foreach ($data_out as $file)
			{
				if (empty( $file['extension'] ))
					continue;

				if (!array_key_exists( $file['extension'], $temp_container ))
					$temp_container[$file['extension']] = array();

				$temp_container[$file['extension']][$file['name']] = $file;
			}
			//create new dataOut
			$data_out = array();
			foreach ($temp_container as $files_array)
				$data_out = array_merge( $data_out, $files_array );
		}

		return $data_out;
	}

	private function extractFileInfo($fileName = null)
	{
		if (empty( $fileName ))
			return $fileName;

		$extension = pathinfo( $fileName, PATHINFO_EXTENSION );
		return array( 'name'=> $fileName, 'extension'=> $extension);
	}


	/**
	* methods bellow: Added to comply with the prestashop module validation 
	*/
	private function emptyTest($value_in)
	{
		return empty( $value_in )?true:false;
	}

	private function hasFile()
	{
		if (count($_FILES) <= 0)
			return false;
		else
		{
			$check_for_file = 'upload_file';

			foreach ($_FILES as $key => $file)
			{
				if ($check_for_file == $key && !empty( $file ) && !empty( $file['name'] ) && !empty( $file['type'] ))
					return true;
			}

			return false;
		}
	}
}


/**
* The model in the same file because of the module generator
*/

class AMMESSAGEINFOCLIENTSModel extends ObjectModel
{

	public static $definition = array(
		'table' => 'ammessageinfoclients',
		'primary' => 'file_id',
		'multishop' => true,
		'multilang' => true,
		'fields' => array(
			'file_id' =>       array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true),
			'file_name' =>    		array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true,'size' => 255),
			'file_type' =>		    array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true),
			'id_store' =>      array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true)
		),
	);

	public static function createTables()
	{
		//main table for the files
		return ( AMMESSAGEINFOCLIENTSModel::createFilesTable()
				&& AMMESSAGEINFOCLIENTSModel::createContentTable());
	}

	public static function dropTables()
	{
		$sql = 'DROP TABLE
			`'._DB_PREFIX_.self::$definition['table'].'_files`,
			`'._DB_PREFIX_.self::$definition['table'].'`
		';
		$result = Db::getInstance()->execute($sql);
		return $result;
	}

	public static function createContentTable()
	{
		$sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.self::$definition['table'].'`(
			`content_id` int(10) unsigned NOT NULL auto_increment,
			`content_text` text NOT NULL,
			`id_lang` int(10) unsigned NOT NULL,
			`id_store` int(10) unsigned NOT NULL default \'1\',
			PRIMARY KEY (`content_id`),
			UNIQUE KEY `id_lang_id_store` (`id_lang`,`id_store`)
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';

		return Db::getInstance()->execute($sql);
	}

	public static function setContent($content_text = null, $id_store = 1, $id_lang = null)
	{
		//special thanks to MarkOG (http://www.prestashop.com/forums/user/817367-markog/)
		$content_text = pSQL( $content_text, true );
		$id_lang = (int)$id_lang;
		$id_store = (int)$id_store;
		$sql = 'INSERT INTO `'._DB_PREFIX_.self::$definition['table'].'` (`content_text`,`id_lang`,`id_store`)
					VALUES ("'.$content_text.'","'.$id_lang.'","'.$id_store.'")
					ON DUPLICATE KEY UPDATE `content_text` = "'.$content_text.'"
				';

		return Db::getInstance()->execute( $sql );
	}

	public static function getContent($shop, $language)
	{
		$sql = 'SELECT * FROM '._DB_PREFIX_.self::$definition['table'].' WHERE `id_lang` = "'.(int)$language.'" and `id_store`="'.(int)$shop.'"';
		return Db::getInstance()->getRow($sql);
	}

	public static function createFilesTable()
	{
		//file_type 0 =>css, 1=> js, 2=>html
		$sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.self::$definition['table'].'_files`(
			`id` int(10) unsigned NOT NULL auto_increment,
			`id_store` int(10) unsigned NOT NULL ,
			`id_lang` int(10) unsigned NOT NULL,
			`files` text NOT NULL,
			PRIMARY KEY (`id`),
			UNIQUE KEY `id_lang_id_store` (`id_lang`,`id_store`)
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';

		return Db::getInstance()->execute($sql);
	}

	public static function getFilesInUse($id_store = 1, $id_lang = 1)
	{
		$sql = 'SELECT * FROM `'._DB_PREFIX_.self::$definition['table'].'_files` where `id_store`='.(int)$id_store.' and `id_lang`='.(int)$id_lang;
		return Db::getInstance()->getRow($sql);
	}

	public static function setFiles($files_list = null, $id_store = 1, $id_lang = null)
	{
		$files_list = Tools::jsonEncode( $files_list );
		$files = pSQL( $files_list );
		$id_lang = (int)$id_lang;
		$id_store = (int)$id_store;

		$sql = 'INSERT INTO `'._DB_PREFIX_.self::$definition['table'].'_files` (`files`,`id_lang`,`id_store`)
					VALUES ("'.$files.'","'.$id_lang.'","'.$id_store.'")
					ON DUPLICATE KEY UPDATE `files` = "'.$files.'"
				';

		return Db::getInstance()->execute( $sql );
	}

	public function stayInTouch()
    {
        if (version_compare(_PS_VERSION_, '1.6.0', '<')) {

            $html = '';
            $html .=
            '<br />
            <fieldset>
                <legend>'.$this->l('Plus de tutos PrestaShop ?').'</legend>
                <p>'.$this->l('Vous pouvez lire des articles et des tutos sur mon blog').' : <a target="_blank" href="https://www.arnaud-merigeau.fr/blog?utm_source=module&utm_medium=liens">www.arnaud-merigeau.fr/blog</a></p>
                <p>'.$this->l('Si ce module vous a été utile, laissez-moi un avis en cliquant sur l\'image :').'</p>
                <p><a target="_blank" href="https://www.google.fr/search?q=Freelance+PrestaShop+%26+WordPress,+20+Rue+de+Betnoms,+B%C3%A2timent+Digit+Halles,+33185+Le+Haillan&ludocid=11545508322336072769#lrd=0xd5528a606097133:0xa039e2a600286441,3"><img alt="avis google" src="https://www.arnaud-merigeau.fr/wp-content/uploads/2018/06/bloc_avis_google_freelance_prestashop.jpg" /></a></p>
            </fieldset>
            <br />
            <fieldset>
                <legend>'.$this->l('Restons en contact').'</legend>
                <table class="social" style="width:100%">
                <tr>
                    <td style="width:33.33%; text-align:center;">
                        <div id="fb-root"></div>
                        <script>(function(d, s, id) {
                          var js, fjs = d.getElementsByTagName(s)[0];
                          if (d.getElementById(id)) return;
                          js = d.createElement(s); js.id = id;
                          js.src = "https://connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v3.2&appId=118397404931307&autoLogAppEvents=1";
                          fjs.parentNode.insertBefore(js, fjs);
                        }(document, "script", "facebook-jssdk"));</script>
                        <div class="fb-page" data-href="https://www.facebook.com/freelance.prestashop.wordpress/" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/freelance.prestashop.wordpress/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/freelance.prestashop.wordpress/">Freelance PrestaShop &amp; WordPress Arnaud Merigeau</a></blockquote></div>
                    </td>
                    <td style="width:33.33%; text-align:center;">
                        <a href="https://twitter.com/arnaudmerigeau?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Suivre @arnaudmerigeau</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
                    </td>
                    <td style="width:33.33%; text-align:center;">
                        <script src="https://apis.google.com/js/platform.js"></script>
                        <div class="g-ytsubscribe" data-channelid="UCKfHcvvjMdStwZhuIhyvtEA" data-layout="full" data-count="default"></div>
                    </td>
                </tr>
                </table>
            </fieldset>
            <br />
            <style>
                @media screen and (max-width: 991px){
                    table.social,table.social tr, table.social td{display:block;width:100%!important;padding:10px 0;}
                }
            </style>
            <iframe src="https://feed.mikle.com/widget/v2/72825/" height="337px" width="100%" class="fw-iframe" scrolling="no" frameborder="0"></iframe>';

            return $html;

        }else{

            $this->_html = '';
            $this->_html .=
            '<div class="panel">
                <legend>'.$this->l('Plus de tutos PrestaShop ?').'</legend>
                <p>'.$this->l('Vous pouvez lire des articles et des tutos sur mon blog').' : <a target="_blank" href="https://www.arnaud-merigeau.fr/blog?utm_source=module&utm_medium=liens">www.arnaud-merigeau.fr/blog</a></p>
                <p>'.$this->l('Si ce module vous a été utile, laissez-moi un avis en cliquant sur l\'image :').'</p>
                <p><a target="_blank" href="https://www.google.fr/search?q=Freelance+PrestaShop+%26+WordPress,+20+Rue+de+Betnoms,+B%C3%A2timent+Digit+Halles,+33185+Le+Haillan&ludocid=11545508322336072769#lrd=0xd5528a606097133:0xa039e2a600286441,3"><img alt="avis google" src="https://www.arnaud-merigeau.fr/wp-content/uploads/2018/06/bloc_avis_google_freelance_prestashop.jpg" /></a></p>
            </div>
            <div class="panel">
                <legend>'.$this->l('Restons en contact').'</legend>
                <table class="social" style="width:100%">
                <tr>
                    <td style="width:33.33%; text-align:center;">
                        <div id="fb-root"></div>
                        <script>(function(d, s, id) {
                          var js, fjs = d.getElementsByTagName(s)[0];
                          if (d.getElementById(id)) return;
                          js = d.createElement(s); js.id = id;
                          js.src = "https://connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v3.2&appId=118397404931307&autoLogAppEvents=1";
                          fjs.parentNode.insertBefore(js, fjs);
                        }(document, "script", "facebook-jssdk"));</script>
                        <div class="fb-page" data-href="https://www.facebook.com/freelance.prestashop.wordpress/" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/freelance.prestashop.wordpress/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/freelance.prestashop.wordpress/">Freelance PrestaShop &amp; WordPress Arnaud Merigeau</a></blockquote></div>
                    </td>
                    <td style="width:33.33%; text-align:center;">
                        <a href="https://twitter.com/arnaudmerigeau?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Suivre @arnaudmerigeau</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
                    </td>
                    <td style="width:33.33%; text-align:center;">
                        <script src="https://apis.google.com/js/platform.js"></script>
                        <div class="g-ytsubscribe" data-channelid="UCKfHcvvjMdStwZhuIhyvtEA" data-layout="full" data-count="default"></div>
                    </td>
                </tr>
                </table>
            </div>
            <style>
                @media screen and (max-width: 991px){
                    table.social,table.social tr, table.social td{display:block;width:100%!important;padding:10px 0;}
                }
            </style>
            <iframe src="https://feed.mikle.com/widget/v2/72825/" height="337px" width="100%" class="fw-iframe" scrolling="no" frameborder="0"></iframe>';

            return $this->_html;

        }
    }
}