<?php
/**
 * Block Reinsurance Custom Prestashop module
 * 
 * @author    Prestaddons <contact@prestaddons.fr>
 * @copyright 2014 Prestaddons
 * @license
 * @link      http://www.prestaddons.fr
 */

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

include_once _PS_MODULE_DIR_.'blockreinsurancecustom/reinsurancecustomClass.php';

class BlockReinsuranceCustom extends Module
{
	public function __construct()
	{
		$this->name = 'blockreinsurancecustom';
		$this->tab = 'front_office_features';
		$this->version = '1.1.0';
		$this->need_instance = 0;
		$this->ps_versions_compliancy = array('min' => '1.6', 'max' => '1.6');
		$this->bootstrap = true;
		$this->module_key = '';

		parent::__construct();

		$this->displayName = $this->l('Reassurance block Custom');
		$this->description = $this->l('Adds an information block aimed at offering helpful information to reassure customers that your store is trustworthy.');
		$this->confirmUninstall = $this->l('Are you sure you want to uninstall the Block Reinsurance Custom module?');
		$this->author = $this->l('Prestaddons');
		$this->contact = 'contact@prestaddons.fr';
	}

	public function install()
	{
		if (!parent::install()
			|| !$this->_installDB()
			|| !$this->registerHook('header')
			|| !$this->_installFixtures())
				return false;

			if ($this->_checkPSVersion())
			{
				// Disable on mobiles and tablets
				if (!$this->registerHook('home') || !$this->disableDevice(Context::DEVICE_TABLET | Context::DEVICE_MOBILE))
					return false;
			}
			else
			{
				if (!$this->registerHook('footer'))
					return false;
			}

		return true;
	}

	private function _installDB()
	{
		$return = true;
		$return &= Db::getInstance()->execute('
			CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'reinsurance_custom` (
				`id_reinsurance_custom` INT UNSIGNED NOT NULL AUTO_INCREMENT,
				`id_shop` int(10) unsigned NOT NULL ,
				`icon_name` VARCHAR(100) NOT NULL,
				`new_window` BOOL NOT NULL DEFAULT 0,
				PRIMARY KEY (`id_reinsurance_custom`)
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 ;');

		$return &= Db::getInstance()->execute('
			CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'reinsurance_custom_lang` (
				`id_reinsurance_custom` INT UNSIGNED NOT NULL AUTO_INCREMENT,
				`id_lang` int(10) unsigned NOT NULL ,
				`text` VARCHAR(300) NOT NULL,
				`link` VARCHAR(255) NOT NULL,
				PRIMARY KEY (`id_reinsurance_custom`, `id_lang`)
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 ;');

		return $return;
	}

	private function _installFixtures()
	{
		$id_lang_en = Language::getIdByIso('en');
		$id_lang_fr = Language::getIdByIso('fr');

		$return = true;
		$tab_texts = array(
			array('text' => array($id_lang_en => 'Money back guarantee', $id_lang_fr => 'Satisfait ou remboursé'), 'icon_name' => 'f118'),
			array('text' => array($id_lang_en => 'In-store exchange' , $id_lang_fr => 'Echange en magasin'), 'icon_name' => 'f0e2'),
			array('text' => array($id_lang_en => 'Payment upon shipment', $id_lang_fr => 'Paiement à la livraison'), 'icon_name' => 'f09d'),
			array('text' => array($id_lang_en => 'Free Shipping', $id_lang_fr => 'Livraison gratuite'), 'icon_name' => 'f0d1'),
			array('text' => array($id_lang_en => '100% secure payment', $id_lang_fr => 'Paiement 100% sécurisé'), 'icon_name' => 'f13e')
		);

		foreach ($tab_texts as $tab)
		{
			$reinsurance = new ReinsuranceCustomClass();
			foreach (Language::getLanguages(false) as $lang)
				$reinsurance->text[$lang['id_lang']] = $tab['text'][$lang['id_lang']];
			$reinsurance->icon_name = $tab['icon_name'];
			$reinsurance->id_shop = $this->context->shop->id;
			$return &= $reinsurance->save();
		}
		return $return;
	}

	public function uninstall()
	{
		return $this->_uninstallDB() && parent::uninstall();
	}

	private function _uninstallDB()
	{
		return Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'reinsurance_custom`') && Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'reinsurance_custom_lang`');
	}

	/**
	 * Méthode _postProcess()
	 * 
	 * Traitement des informations saisies dans le backoffice
	 * Traitements divers, mise à jour la base de données, définition des messages d'erreur ou de confirmation...
	 * 
	 * @return string HTML du résultat du traitement (message d'erreur ou de confirmation)
	 */
	private function _postProcess($id_reinsurance_custom)
	{
		if (Tools::isSubmit('saveblockreinsurancecustom'))
		{
			if (isset($id_reinsurance_custom))
				$reinsurance = new ReinsuranceCustomClass((int)$id_reinsurance_custom);
			else
				$reinsurance = new ReinsuranceCustomClass();

			$reinsurance->copyFromPost();
			$reinsurance->id_shop = $this->context->shop->id;

			if ($reinsurance->validateFields(false) && $reinsurance->validateFieldsLang(false))
			{
				$reinsurance->save();
				$this->_clearCache('blockreinsurancecustom.tpl');
				$this->_html .= $this->displayConfirmation($this->l('The block configuration has been updated.'));
			}
			else
				$this->_html .= $this->displayError($this->l('An error occurred while attempting to save.'));
		}
	}

	/**
	 * Méthode getContent()
	 * 
	 * Gère l'administration du module dans le backoffice
	 * Dispatch vers les différentes méthodes en fonctions des cas (affichage des formulaires, des erreurs, des confirmations, ...)
	 * 
	 * @return string HTML de la partie backoffice du module
	 */
	public function getContent()
	{
		$id_reinsurance_custom = (int)Tools::getValue('id_reinsurance_custom');

		if (!isset($this->_postErrors) || !count($this->_postErrors))
			$this->_postProcess($id_reinsurance_custom);
		else
		{
			foreach ($this->_postErrors as $err)
				$this->_html .= $this->displayError($err);
		}
		if (Tools::isSubmit('updateblockreinsurancecustom') || Tools::isSubmit('addblockreinsurancecustom'))
			$this->_html .= $this->renderForm($id_reinsurance_custom);
		else if (Tools::isSubmit('deleteblockreinsurancecustom'))
			$this->_deleteBlock($id_reinsurance_custom);
		else if (Tools::isSubmit('supportblockreinsurancecustom'))
			$this->_html .= $this->renderSupportForm();
		else
			$this->_html .= $this->renderList();

		return $this->_html;
	}

	protected function getListContent($id_lang)
	{
		return Db::getInstance()->executeS('
			SELECT r.`id_reinsurance_custom`, r.`id_shop`, r.`icon_name`, r.`new_window`, rl.`text`, rl.`link`
			FROM `'._DB_PREFIX_.'reinsurance_custom` r
			LEFT JOIN `'._DB_PREFIX_.'reinsurance_custom_lang` rl ON (r.`id_reinsurance_custom` = rl.`id_reinsurance_custom`)
			WHERE `id_lang` = '.(int)$id_lang.' '.Shop::addSqlRestrictionOnLang());
	}

	public function renderForm($id_reinsurance_custom)
	{
		$this->context->controller->addjQueryUI('ui.dialog');

		$this->context->controller->addJS(_PS_JS_DIR_.'tiny_mce/tiny_mce.js');
		$this->context->controller->addJS(_PS_JS_DIR_.'tinymce.inc.js');

		if (!$this->_checkPSVersion())
			$this->context->controller->addCSS($this->_path.'views/css/font-awesome.css');
		$this->context->controller->addCSS($this->_path.'views/css/admin.css');

		if (Tools::isSubmit('add'.$this->name))
			$action_form = 'add';
		else if (Tools::isSubmit('update'.$this->name))
			$action_form = 'update';

		$fields_value = array();
		foreach (Language::getLanguages(false) as $lang)
		{
			if ($id_reinsurance_custom)
			{
				$reinsurance = new ReinsuranceCustomClass((int)$id_reinsurance_custom);
				$fields_value['icon_name'] = $reinsurance->icon_name;
				$fields_value['new_window'] = $reinsurance->new_window;
				$fields_value['text'][(int)$lang['id_lang']] = $reinsurance->text[(int)$lang['id_lang']];
				$fields_value['link'][(int)$lang['id_lang']] = $reinsurance->link[(int)$lang['id_lang']];
			}
			else
			{
				$fields_value['icon_name'] = Tools::getValue('icon_name', '');
				$fields_value['new_window'] = Tools::getValue('new_window', '');
				$fields_value['text'][(int)$lang['id_lang']] = Tools::getValue('text_'.(int)$lang['id_lang'], '');
				$fields_value['link'][(int)$lang['id_lang']] = Tools::getValue('link_'.(int)$lang['id_lang'], '');
			}
		}

		$icon_list = array();
		// Boucle gérant l'affichage de la liste d'icônes
		for ($i = 61440; $i <= 61922; $i++)
		{
			$h = dechex($i);
			$last = Tools::substr($h, 3, 1);
			if ($last != 'f')
				$icon_list[] = $h;
		}

		$psversion16 = $this->_checkPSVersion();

		// Envoi des paramètres au template
		$this->context->smarty->assign(
				array(
					'action_form' => $action_form,
					'back_link' => AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
					'path' => _MODULE_DIR_.$this->name.'/',
					'iso' => Language::getIsoById($this->context->cookie->id_lang),
					'languages' => Language::getLanguages(false),
					'defaultFormLanguage' => (int)Configuration::get('PS_LANG_DEFAULT'),
					'fields_value' => $fields_value,
					'id_reinsurance_custom' => $id_reinsurance_custom,
					'icon_list' => $icon_list,
					'module_name' => $this->name,
					'display_name' => $this->displayName,
					'version' => $this->version,
					'author' => $this->author,
					'contact' => $this->contact,
					'psversion16' => $psversion16
				)
		);

		if ($psversion16)
			$html = $this->display(__FILE__, 'views/templates/admin/edit_form.tpl');
		else
			$html = $this->display(__FILE__, 'views/templates/admin/edit_form15.tpl');

		return $html;
	}

	protected function initList()
	{
		$this->fields_list = array(
			'id_reinsurance_custom' => array(
				'title' => $this->l('ID'),
				'width' => 50,
				'type' => 'text',
				'search' => false,
				'orderby' => false
			),
			'text' => array(
				'title' => $this->l('Text'),
				'width' => 140,
				'type' => 'text',
				'search' => false,
				'orderby' => false
			),
			'link' => array(
				'title' => $this->l('Link'),
				'width' => 140,
				'type' => 'text',
				'search' => false,
				'orderby' => false
			),
			'new_window' => array(
				'title' => $this->l('New window'),
				'width' => 50,
				'active' => 'status',
				'align' => 'text-center',
				'type' => 'bool',
				'search' => false,
				'orderby' => false
			),
		);

		if (Shop::isFeatureActive())
			$this->fields_list['id_shop'] = array('title' => $this->l('ID Shop'), 'align' => 'center', 'width' => 25, 'type' => 'int');

		$helper = new HelperList();
		$helper->shopLinkType = '';
		$helper->simple_header = false;
		$helper->identifier = 'id_reinsurance_custom';
		$helper->actions = array('edit', 'delete');
		$helper->show_toolbar = true;
		$helper->toolbar_btn['new'] = array(
			'href' => AdminController::$currentIndex.'&configure='.$this->name.'&add'.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
			'desc' => $this->l('Add new')
		);
		$helper->toolbar_btn['help-new'] = array(
			'href' => AdminController::$currentIndex.'&configure='.$this->name.'&support'.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
			'desc' => $this->l('Support')
		);

		$helper->icon = 'icon-info-circle';
		$helper->title = $this->displayName;
		$helper->table = $this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
		$helper->listTotal = count($this->getListContent($this->context->cookie->id_lang));

		return $helper;
	}

	public function renderList()
	{
		$helper = $this->initList();
		return $helper->generateList($this->getListContent((int)Configuration::get('PS_LANG_DEFAULT')), $this->fields_list);
	}

	public function renderSupportForm()
	{
		// Envoi des paramètres au template
		$this->context->smarty->assign(
				array(
					'path' => _MODULE_DIR_.$this->name.'/',
					'iso' => Language::getIsoById($this->context->cookie->id_lang),
					'display_name' => $this->displayName,
					'version' => $this->version,
					'author' => $this->author,
					'contact' => $this->contact,
					'back_link' => AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
					'psversion16' => $this->_checkPSVersion()
				)
		);

		return $this->display(__FILE__, 'views/templates/admin/support.tpl');
	}

	private function _deleteBlock($id_reinsurance_custom)
	{
		$reinsurance = new ReinsuranceCustomClass((int)$id_reinsurance_custom);
		$reinsurance->delete();
		$this->_clearCache('blockreinsurancecustom.tpl');
		Tools::redirectAdmin(AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
	}

	/**
	 * Méthode _checkPSVersion()
	 * 
	 * Compare la version de Prestashop passée en paramètre avec la version courante
	 * 
	 * @param string $version Version à comparer
	 * @param string $compare Sens de la comparaison
	 * 
	 * @return boolean True si la comparaison est vérifiée
	 * 
	 */
	private function _checkPSVersion($version = '1.6.0.0', $compare = '>')
	{
		return version_compare(_PS_VERSION_, $version, $compare);
	}

	public function hookHeader()
	{
		if ($this->_checkPSVersion())
			$this->context->controller->addCSS($this->_path.'views/css/styles.css', 'all');
		else
		{
			$this->context->controller->addCSS($this->_path.'views/css/font-awesome.css', 'all');
			$this->context->controller->addCSS($this->_path.'views/css/styles15.css', 'all');
		}
	}

	public function hookFooter()
	{
		if ($this->_checkPSVersion('1.5.6'))
		{
			if (!$this->isCached('blockreinsurancecustom.tpl', $this->getCacheId()))
			{
				$infos = $this->getListContent($this->context->language->id);
				$this->context->smarty->assign(array('infos' => $infos, 'nbblocks' => count($infos)));
			}
			return $this->display(__FILE__, 'blockreinsurancecustom.tpl', $this->getCacheId());
		}
		else
		{
			$infos = $this->getListContent($this->context->language->id);
			$this->context->smarty->assign(array('infos' => $infos, 'nbblocks' => count($infos)));
			return $this->display(__FILE__, 'blockreinsurancecustom.tpl');
		}
	}

	public function hookDisplayHome()
	{
		return $this->hookFooter();
	}

	public function hookDisplayContentFooter()
	{
		return $this->hookFooter();
	}
}