<?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 LSSliders
{
	/**
	 * @var array $results Array containing the result of the last DB query
	 * @access public
	 */
	public static $results = array();

	/**
	 * @var int $count Count of found sliders in the last DB query
	 * @access public
	 */
	public static $count = null;

	/**
	 * Returns the count of found sliders in the last DB query
	 *
	 * @since 5.0.0
	 * @access public
	 * @return int Count of found sliders in the last DB query
	 */
	public static function count()
	{
		return self::$count;
	}

	/**
	 * Find sliders with the provided filters
	 *
	 * @since 5.0.0
	 * @access public
	 * @param mixed $args Find any slider with the provided filters
	 * @return mixed Array on success, false otherwise
	 */
	public static function find($args)
	{
		if (is_numeric($args) && (int)($args) == $args)
			return self::getById((int)$args);

		elseif (is_string($args))
			return self::getBySlug($args);

		elseif (is_array($args) && isset($args[0]) && is_numeric($args[0]))
			return self::getByIds($args);

		else
		{
			$defaults = array(
				'columns' => '*',
				'where' => '',
				'exclude' => array('hidden', 'removed'),
				'orderby' => 'date_c',
				'order' => 'DESC',
				'limit' => 10,
				'page' => 1,
				'data' => true);

			foreach ($defaults as $key => $val)

				if (!isset($args[$key]))
					$args[$key] = $val;

			foreach ($args as $key => $val)
				$args[$key] = $val;

			if (!empty($args['exclude']))
			{
				$exclude = array();
				if (in_array('hidden', $args['exclude']))
					$exclude[] = 'flag_hidden = \'0\'';

				if (in_array('removed', $args['exclude']))
					$exclude[] = 'flag_deleted = \'0\'';

				$args['exclude'] = implode(' AND ', $exclude);
			}

			$where = '';
			if (!empty($args['where']) && !empty($args['exclude']))
				$where = "({$args['exclude']}) AND ({$args['where']}) ";

			elseif (!empty($args['where']))
				$where = "{$args['where']} ";

			elseif (!empty($args['exclude']))
				$where = "{$args['exclude']} ";

			$args['limit'] = ($args['limit'] * $args['page'] - $args['limit']).', '.$args['limit'];

			$db = Db::getInstance();
			$q = "SELECT SQL_CALC_FOUND_ROWS {$args['columns']} FROM "._DB_PREFIX_."layerslider WHERE $where";
			$q .= "ORDER BY {$args['orderby']} {$args['order']} LIMIT {$args['limit']}";
			$sliders = $db->executeS($q);

			self::$count = (int)$db->getValue('SELECT FOUND_ROWS()');

			if (!is_array($sliders))
				return $sliders;

			if ($args['data'])
				foreach ($sliders as $key => $val)
					$sliders[$key]['data'] = Tools::jsonDecode($val['data'], true);

			return $sliders;
		}
	}

	/**
	 * Add slider with the provided name and optional slider data
	 *
	 * @since 5.0.0
	 * @access public
	 * @param string $title The title of the slider to create
	 * @param array $data The settings of the slider to create
	 * @return int The slider database ID inserted
	 */
	public static function add($title = 'Untitled', $data = array())
	{
		$db = Db::getInstance();

		$data = !empty($data) ? $data : array(
			'properties' => array('title' => $title),
			'layers' => array(array()),
			);

		$datas = new stdClass();
		$datas->author = Context::getContext()->employee->id;
		$datas->name = pSQL($title);
		$datas->slug = '';
		$datas->data = pSQL(Tools::jsonEncode($data), true);
		$datas->date_c = time();
		$datas->date_m = time();

		$result = Sdb::insert('layerslider', $datas);
		return $result ? $db->insert_id() : false;
	}

	public static function saveHook($id, $hook)
	{
		$slider = LSSliders::find($id);
		$slider['data']['properties']['hook'] = $hook;

		return Sdb::update('layerslider', array('data' => pSQL(Tools::jsonEncode($slider['data']), true), 'date_m' => time()), 'id = '.$id);
	}

	public static function save()
	{
		$db = Db::getInstance();

		$id = (int)Tools::getValue('slider_id', 0);
		$layerkey = (int)Tools::getValue('layerkey');

		if ($layerkey == 0 && $id > 0)
			$data = array();
		else
		{
			$slider = LSSliders::find($id);
			$id = $slider['id'];
			$data = $slider['data'];
		}

		$slides = Tools::getValue('layerslider-slides');

		if (!get_magic_quotes_gpc())
		{
			foreach ($slides['layers'][$layerkey]['sublayers'] as &$sublayer)
			{
				$sublayer['transition'] = addslashes($sublayer['transition']);
				$sublayer['styles'] = addslashes($sublayer['styles']);
			}
		}

		if (isset($slides['properties']['relativeurls']))
		{
			$data['properties'] = $slides['properties'];
			$data['layers'][$layerkey] = layerslider_convert_urls($slides['layers'][$layerkey]);
		}
		else
		{
			$data['properties'] = $slides['properties'];
			$data['layers'][$layerkey] = $slides['layers'][$layerkey];
		}

		$datas = new stdClass();
		$datas->author = Context::getContext()->employee->id;
		$datas->name = isset($data['properties']['title']) ? pSQL($data['properties']['title']) : 'Untitled';
		$datas->slug = isset($data['properties']['slug']) ? pSQL($data['properties']['slug']) : '';
		$datas->data = pSQL(Tools::jsonEncode($data), true);
		$datas->date_m = time();

		$result = Sdb::update('layerslider', $datas, 'id = '.$id);

		return $result ? $db->insert_id() : false;
	}

	/**
	 * Marking a slider as removed without deleting it
	 * with its database ID.
	 *
	 * @since 5.0.0
	 * @access public
	 * @param int $id The database ID if the slider to remove
	 * @return bool Returns true on success, false otherwise
	 */
	public static function remove($id = null)
	{
		if (!is_int($id))
			return false;

		$db = Db::getInstance();
		$slides = Tools::getValue('layerslider-slides');

		$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['hook'] && $old['hook'] != $slides['properties']['hook'])
		{
			$old_hook_count = (int)$db->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_."layerslider_module WHERE hook LIKE '{$old['hook']}'");
			if ($old_hook_count == 1)
				Module::getInstanceByName('layerslider')->unregisterHook($old['id_hook']);

		}

		$datas = new stdClass();
		$datas->flag_deleted = 1;

		return Sdb::update('layerslider', $datas, 'id = '.$id);
	}

	/**
	 * Delete a slider by its database ID
	 *
	 * @since 5.0.0
	 * @access public
	 * @param int $id The database ID if the slider to delete
	 * @return bool Returns true on success, false otherwise
	 */
	public static function delete($id = null)
	{
		if (!is_int($id))
			return false;

		$db = Db::getInstance();
		return $db->delete('layerslider', 'id = '.$id);
	}

	/**
	 * Restore a slider marked as removed previously by its database ID.
	 *
	 * @since 5.0.0
	 * @access public
	 * @param int $id The database ID if the slider to restore
	 * @return bool Returns true on success, false otherwise
	 */
	public static function restore($id = null)
	{
		if (!is_int($id))
			return false;

		$datas = new stdClass();
		$datas->flag_deleted = 0;

		return Sdb::update('layerslider', $datas, 'id = '.$id);
	}

	private static function getById($id = null)
	{
		if (!is_int($id))
			return false;

		$db = Db::getInstance();
		$result = $db->getRow('SELECT * FROM '._DB_PREFIX_.'layerslider WHERE id = '.$id);

		if (!is_array($result))
			return false;

		$result['data'] = Tools::jsonDecode($result['data'], true);
		return $result;
	}

	private static function getByIds($ids = null)
	{
		if (!is_array($ids))
			return false;

		$db = Db::getInstance();
		$limit = count($ids);

		if (is_array($ids) && !empty($ids))
		{
			$tmp = array();
			foreach ($ids as $id)
				$tmp[] = 'id = '.(int)($id);

			$ids = implode(' OR ', $tmp);
			unset($tmp);
		}
		$result = $db->executeS('SELECT * FROM '._DB_PREFIX_.'layerslider WHERE $ids ORDER BY id DESC LIMIT '.$limit);

		if (is_array($result) && !empty($result))
		{
			foreach ($result as $key => $slider)
				$result[$key]['data'] = Tools::jsonDecode($slider['data'], true);

			return $result;
		}
		else
			return false;
	}

	private static function getBySlug($slug)
	{
		if (empty($slug))
			return false;

		$table = _DB_PREFIX_.'layerslider';
		$db = Db::getInstance();

		$result = $db->getRow("SELECT * FROM $table WHERE slug = '$slug'");

		if (!is_array($result))
			return false;

		$result['data'] = Tools::jsonDecode($result['data'], true);
		return $result;
	}
}
