<?php
/**
* LayerSlider v5.1.2 - Responsive Slideshow Module http://layerslider.webshopworks.com
*
*  @author    WebshopWorks <info@webshopworks.com>
*  @copyright 2015 WebshopWorks
*  @license   One Domain Licence
*/

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

class LayerSlider extends Module
{
	private $init = false;
	private $tabs = array(
		'LayerSlider' => array('class' => 'AdminLayerSlider', 'active' => 1),
		'Sliders' => array('class' => 'AdminLayerSlider', 'active' => 1),
		'Edit Slider' => array('class' => 'AdminLayerSliderEdit', 'active' => 0),
		'Media Manager' => array('class' => 'AdminLayerSliderMedia', 'active' => 0),
		'Transition Builder' => array('class' => 'AdminLayerSliderTransition', 'active' => 1),
		'Skin Editor' => array('class' => 'AdminLayerSliderSkin', 'active' => 1),
		'CSS Editor' => array('class' => 'AdminLayerSliderStyle', 'active' => 1));

	public function __construct()
	{
		$this->name = 'layerslider';
		$this->tab = 'slideshows';
		$this->version = '5.1.2';
		$this->author = 'WebshopWorks';
		$this->module_key = 'b92dd49b8609431aeb010cb8db905a3f';
		$this->need_instance = 0;
		$this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6');
		$this->bootstrap = false;
		$this->displayName = $this->l('LayerSlider');
		$this->description = $this->l('Responsive Slideshow Module');
		$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
		parent::__construct();
	}

	private function installDb()
	{
		$db = Db::getInstance();
		$result = (bool)$db->execute('
			CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'layerslider` (
				`id` int(10) NOT NULL AUTO_INCREMENT,
				`author` int(10) NOT NULL DEFAULT 0,
				`name` varchar(100) NOT NULL,
				`slug` varchar(100) NOT NULL,
				`data` mediumtext NOT NULL,
				`date_c` int(10) NOT NULL,
				`date_m` int(11) NOT NULL,
				`flag_hidden` tinyint(1) NOT NULL DEFAULT 0,
				`flag_deleted` tinyint(1) NOT NULL DEFAULT 0,
				PRIMARY KEY (`id`)
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
		');
		$result &= (bool)$db->execute('
			CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'layerslider_module` (
				`id_slider` int(10) NOT NULL,
				`id_shop` int(11) NOT NULL DEFAULT 0,
				`id_lang` int(10) NOT NULL DEFAULT 0,
				`hook` varchar(64) NOT NULL DEFAULT \'\',
				`position` tinyint(2) NOT NULL DEFAULT 0,
				`pages` text NOT NULL
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
		');
		$modules = $db->executeS('SELECT DISTINCT hook FROM '._DB_PREFIX_.'layerslider_module WHERE hook NOT LIKE \'\'');
		foreach ($modules as $mod)
			$this->registerHook($mod['hook']);

		return $result;
	}

	private function installTab()
	{
		$result = 1;
		$parent = 0;
		foreach ($this->tabs as $name => $t)
		{
			$tab = new Tab();
			$tab->active = $t['active'];
			$tab->name = array();
			$tab->class_name = $t['class'];
			foreach (Language::getLanguages(true) as $lang)
				$tab->name[$lang['id_lang']] = $name;

			$tab->module = $this->name;
			$tab->id_parent = $parent;
			$result = $tab->add();
			if (!$parent)
				$parent = (int)Tab::getIdFromClassName('AdminLayerSlider');

		}
		return $result;
	}

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

		if (!Configuration::hasKey('LAYERSLIDER_LS_GOOGLE_FONTS'))
		{
			Configuration::updateValue('LAYERSLIDER_LS_GOOGLE_FONTS', '[{"param":"Lato:100,300,regular,700,900","admin":false},'.
				'{"param":"Open+Sans:300","admin":false},{"param":"Indie+Flower:regular","admin":false},{"param":"Oswald:300,regular,700","admin":false}]');
		}
		$result = parent::install();
		$result &= $this->installDb();
		$result &= $this->installTab();
		$result &= $this->registerHook('displayHeader');
		$result &= $this->registerHook('displayBackOfficeHeader');
		return $result;
	}

	private function uninstallTab()
	{
		$result = 1;
		foreach ($this->tabs as $t)
		{
			$id_tab = (int)Tab::getIdFromClassName($t['class']);
			if ($id_tab)
			{
				$tab = new Tab($id_tab);
				$result &= $tab->delete();
			}
		}
		return $result;
	}

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

	public function getContent()
	{
		Tools::redirectAdmin($this->context->link->getAdminLink('AdminLayerSlider'));
	}

	public function insertSlider($data)
	{
		return Sdb::insert('layerslider_module', $data);
	}

	public function updateSlider($id, $data)
	{
		return Sdb::update('layerslider_module', $data, 'id_slider = '.$id);
	}

	public function deleteSlider($id)
	{
		$this->removeHook($id);
		return Db::getInstance()->delete('layerslider_module', 'id_slider = '.$id);
	}

	private function getPages()
	{
		$obj = array(
			'cat' => array(),
			'prod' => array(),
			'cms' => array(),
			'page' => array());
		$slides = Tools::getValue('layerslider-slides');
		$cats = Tools::jsonDecode($slides['properties']['cats']);
		if (in_array('all', $cats))
			$obj['cat'] = $obj['prod'] = 'all';
		else
			foreach ($cats as $val)
			{
				if (preg_match('/^[cp]-\d+$/', $val))
				{
					$v = explode('-', $val);
					$obj[$v[0] == 'c' ? 'cat' : 'prod'][] = $v[1];
				}
				else
					$obj[$val] = 1;
			}
		$pages = Tools::jsonDecode($slides['properties']['pages']);
		if (in_array('all', $pages))
			$obj['cms'] = $obj['page'] = 'all';
		else
			foreach ($pages as $val)
			{
				if (preg_match('/^[cp]-\d+$/', $val))
				{
					$v = explode('-', $val);
					$obj[$v[0] == 'c' ? 'cms' : 'page'][] = $v[1];
				}
				else
					$obj[$val] = 1;
			}
		return Tools::jsonEncode($obj);
	}

	public function addHook($id = 0, $hook = '')
	{
		$id = Tools::getIsset('slider_id') ? (int)Tools::getValue('slider_id') : $id;
		$slides = Tools::getValue('layerslider-slides');
		$hook = Tools::getIsset('layerslider-slides') ? @$slides['properties']['hook'] : $hook;

		if ($hook)
		{
			$hook_count = (int)Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_."layerslider_module WHERE hook LIKE '$hook'");
			if ($hook_count == 0)
				$this->registerHook($hook);

		}
		$data = array('hook' => $hook);
		if (Tools::getIsset('layerslider-slides'))
		{
			$data['id_shop'] = @$slides['properties']['shop'];
			$data['id_lang'] = @$slides['properties']['lang'];
			$data['pages'] = $this->getPages();
		}
		$this->updateSlider($id, $data);
	}

	public function removeHook($id = 0, $hook = '')
	{
		$id = Tools::getIsset('slider_id') ? (int)Tools::getValue('slider_id') : $id;
		$slides = Tools::getValue('layerslider-slides');
		$hook = Tools::getIsset('layerslider-slides') ? @$slides['properties']['hook'] : $hook;

		$db = Db::getInstance();
		$old = $db->getRow('SELECT h.id_hook, m.hook FROM '._DB_PREFIX_.'layerslider_module AS m '.'LEFT JOIN '._DB_PREFIX_.
			"hook AS h ON m.hook LIKE h.name WHERE id_slider = $id");
		if ($old && $old['hook'] && $old['hook'] != $hook)
		{
			$old_hook_count = (int)$db->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_."layerslider_module WHERE hook LIKE '{$old['hook']}'");
			if ($old_hook_count == 1)
				$this->unregisterHook($old['id_hook']);

		}
	}

	private function initSlider()
	{
		if (!$this->init)
		{
			$this->init = true;

			require_once dirname(__file__).'/helper.php';
			require_once LS_ROOT_PATH.'/wp/hooks.php';
			require_once LS_ROOT_PATH.'/classes/class.ls.sliders.php';

			if (!class_exists('phpQuery'))
			{
				libxml_use_internal_errors(true);
				include LS_ROOT_PATH.'/helpers/phpQuery.php';
			}
		}
	}

	public function generateSlider($id)
	{
		$data = array();
		$this->initSlider();
		if ($slider = LSSliders::find($id))
		{
			$slides = $slider['data'];
			if (is_array($slides))
			{
				include LS_ROOT_PATH.'/config/defaults.php';
				include LS_ROOT_PATH.'/includes/slider_markup_init.php';
				include LS_ROOT_PATH.'/includes/slider_markup_html.php';
				return implode('', $data);
			}
		}
		else
			return "[LayerSlider id=$id] ".__('Slider not found', 'LayerSlider');
	}

	private function isOnPage(&$mod)
	{
		if (($mod['id_shop'] == 0 || $mod['id_shop'] == $this->context->shop->id) && ($mod['id_lang'] == 0 || $mod['id_lang'] == $this->context->language->id))
		{
			if (!isset($mod['pages']) || !$mod['pages'])
				$mod['pages'] = '{"cat":"all","prod":"all","cms":"all","page":"all"}';
			$pages = Tools::jsonDecode($mod['pages'], true);
			$class = str_replace('controller', '', Tools::strtolower(get_class($this->context->controller)));
			switch ($class)
			{
				case 'index':
					if ($pages['cat'] === 'all')
						return true;
					return isset($pages['index']);
				case 'category':
					if ($pages['cat'] === 'all')
						return true;
					$id = Tools::getValue('id_category');
					return in_array("$id", $pages['cat']);
				case 'product':
					if ($pages['prod'] === 'all')
						return true;
					$id = Tools::getValue('id_product');
					return in_array("$id", $pages['prod']);
				case 'cms':
					if ($pages['cms'] === 'all')
						return true;
					if (isset($this->context->controller->cms->id))
						return in_array("{$this->context->controller->cms->id}", $pages['page']);
					else
						return in_array("{$this->context->controller->cms_category->id}", $pages['cms']);
				default:
					if ($pages['cms'] === 'all')
						return true;
					return isset($pages[$class]);
			}
		}
		return false;
	}

	private function displaySliders($hook)
	{
		$content = '<div style="clear:both"></div>';
		$db = Db::getInstance();
		$modules = $db->executeS('SELECT * FROM '._DB_PREFIX_."layerslider_module WHERE hook LIKE '$hook' ORDER BY position");
		foreach ($modules as &$mod)
		{
			if ($this->isOnPage($mod))
				$content .= $this->generateSlider($mod['id_slider']);
		}

		$this->context->smarty->assign(array('content' => $content));
		return $this->display(__file__, 'content.tpl');
	}

	public function display($file, $template, $cache_id = null, $compile_id = null)
	{
		@list($tpl_dir) = glob(_PS_ROOT_DIR_.'/*/themes/');
		$tpl_dir .= 'default/template/';
		if (!Tools::file_exists_cache($tpl_dir.$template))
			return Tools::displayError('No template found for module').' '.basename($file, '.php');

		$this->smarty->assign(array(
			'module_dir' =>	__PS_BASE_URI__.'modules/'.basename($file, '.php').'/',
			'module_template_dir' => $tpl_dir,
			'allow_push' => @$this->allow_push
		));

		return $this->context->smarty->createTemplate($tpl_dir.$template, $cache_id, $compile_id, $this->smarty)->fetch();
	}

	public function __call($method, $args)
	{
		if (stripos($method, 'hookdisplay') === 0)
		{
			$hook = 'display'.Tools::substr($method, 11);
			return $this->displaySliders($hook);
		}
	}

	public function hookDisplayHeader()
	{
		require_once dirname(__FILE__).'/helper.php';
		$content = '<link rel="stylesheet" href="'.ls_load_google_fonts().'" type="text/css" id="ls-google-fonts-css" />';
		$content .= '<link rel="stylesheet" href="'.$this->_path.'views/css/base/layerslider.css" type="text/css" />';
		$content .= '<link rel="stylesheet" href="'.$this->_path.'views/css/base/layerslider.transitiongallery.css" type="text/css" />';
		//$content .= '<link rel="stylesheet" href="'.$this->_path.'views/css/imagelightbox.css" type="text/css" />';
		if (version_compare(_PS_JQUERY_VERSION_, '1.8.3', '<'))
		{
			$content .= '<script type="text/javascript" src="'.$this->_path.'views/js/jquery-1.8.3.min.js"></script>';
			$content .= '<script type="text/javascript" src="'.$this->_path.'views/js/jquery.noConflictTrue.js"></script>';
		}
		$content .= '<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.2/TweenMax.min.js"></script>';
		$content .= '<script type="text/javascript" src="'.$this->_path.'views/js/base/layerslider.kreaturamedia.js"></script>';
		$content .= '<script type="text/javascript" src="'.$this->_path.'views/js/base/layerslider.transitions.js"></script>';
		//$content .= '<script type="text/javascript" src="'.$this->_path.'views/js/imagelightbox.js"></script>';
		return $content;
	}

	public function hookDisplayBackOfficeHeader()
	{
		return '<style>.icon-AdminLayerSlider:before { content: "\f03e"; }</style>';
	}
}

?>