<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2014 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

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

class OwlRightSidebar extends Module
{
	private $_html = '';
	public $fields_form;
	public function __construct()
	{
		$this->name = 'owlrightsidebar';
		$this->tab = 'front_office_features';
		$this->version = '1.0.0';
		$this->author = 'owltheme';
		$this->need_instance = 0;
		parent::__construct();
		$this->displayName   = $this->l('OWL Right SideBar');
		$this->description   = $this->l('Show Cart and Compare on Right SideBar , Ajax add to compare.');
	}

	public function install()
	{
		if (!parent::install() || !$this->registerHook('displayRightSideBar') || !$this->registerHook('header') || !$this->registerHook('productActions'))
			return false;
		return true;
	}
	
	public function prev_next_product($id_product, $nav)
	{
		$product = new Product($id_product, false, (int)$this->context->language->id);
		if (!Validate::isLoadedObject($product))
			return false;
		$id_lang = $this->context->language->id;
		if (!isset($this->context->cookie->last_visited_category) || !Product::idIsOnCategoryId($id_product, array('0' => array('id_category' => $this->context->cookie->last_visited_category))))
		$this->context->cookie->last_visited_category = (int)($product->id_category_default);
		$curr_position = $this->getWsPositionInCategory($id_product, $this->context->cookie->last_visited_category);
		if (!Validate::isUnsignedInt($curr_position))
			return false;
		$sql = 'SELECT p.`id_product`,p.`ean13`,
			pl.`link_rewrite`,pl.`name`,
			product_shop.`id_category_default`, 
			MAX(image_shop.`id_image`) id_image
		FROM `'._DB_PREFIX_.'category_product` cp
		LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product`
		'.Shop::addSqlAssociation('product', 'p').'
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl
			ON (p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').')
		LEFT JOIN `'._DB_PREFIX_.'image` i
			ON (i.`id_product` = p.`id_product`)'.
		Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover=1').'
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il
			ON (image_shop.`id_image` = il.`id_image`
			AND il.`id_lang` = '.(int)$id_lang.')
		WHERE product_shop.`id_shop` = '.(int)$this->context->shop->id.'
		AND cp.`id_category` = '.(int)$this->context->cookie->last_visited_category.'
		AND product_shop.`active` = 1
		AND product_shop.`visibility` IN ("both", "catalog") 
		AND cp.`position` '.($nav == 'next' ? '>' : '<').$curr_position.'
		GROUP BY product_shop.id_product
		ORDER BY cp.`position` '.($nav == 'next' ? 'ASC' : 'DESC');
		if ($product = Db::getInstance()->getRow($sql))
		{
			$product['category'] = Category::getLinkRewrite((int)$product['id_category_default'], (int)$id_lang);
			return $product;
		}
		else
			return false;
	}
	
	public function getWsPositionInCategory($id_product = 0, $id_category = 0)
	{
		$result = Db::getInstance()->executeS('SELECT position
			FROM `'._DB_PREFIX_.'category_product`
			WHERE id_category = '.(int)$id_category.'
			AND id_product = '.(int)$id_product);
		if (count($result) > 0)
			return $result[0]['position'];
		return '';
	}
	
	public function hookDisplayRightSideBar($params)
	{
		if (!isset($params['caller']) || $params['caller'] != $this->name)
			return false;
		if (!Configuration::get('PS_COMPARATOR_MAX_ITEM'))
			return false;
		if (isset($params['cookie']->id_compare))
		{
			$ids = CompareProduct::getCompareProducts($params['cookie']->id_compare);
			if (!empty($ids))
			{
				$listProducts = array();
				foreach ($ids as $k => $id)
				{
					$curProduct = new Product((int)$id, true, $this->context->language->id);
					if (!Validate::isLoadedObject($curProduct) || !$curProduct->active || !$curProduct->isAssociatedToShop())
					{
						if (isset($this->context->cookie->id_compare))
							CompareProduct::removeCompareProduct($this->context->cookie->id_compare, $id);
						unset($ids[$k]);
						continue;
					}
					$listProducts[] = $curProduct;
				}  
				$this->smarty->assign(array(
					'compare_nbr' => count($listProducts),
					'listProducts'=>$listProducts,
				));  
			}
		}
		
		/*prev next product*/
		$id_product = (int)Tools::getValue('id_product');
		if (!$id_product)
			$show_pn_prod = 0;
		else
			$show_pn_prod = 1;
		
		$next_prod = $this->prev_next_product($id_product, 'next');
		$prev_prod = $this->prev_next_product($id_product, 'prev');
		
		$this->smarty->assign(array(
			'show_pn_prod' => $show_pn_prod,
			'next_prod' => $next_prod,
			'prev_prod' => $prev_prod
		)); 
		return $this->display(__FILE__, 'owlrightsidebar.tpl');
	}
	public function hookHeader()
	{	
		$this->context->controller->addCSS(($this->_path).'views/css/owlrightsidebar.css');
		return false;
	}
	public function hookProductActions($params)
	{
		$comparator_max_item = Configuration::get('PS_COMPARATOR_MAX_ITEM');
		if (!$comparator_max_item)
			return false;
		$id_product = (int)Tools::getValue('id_product');
		if (!$id_product)
			return false;
		$product = new Product((int)$id_product, false, $this->context->language->id);
		if (!Validate::isLoadedObject($product) || !$product->active || !$product->isAssociatedToShop())
			return false;
		
		$image = Product::getCover((int)$product->id);
		$this->smarty->assign(array(
			'product' => $product,
			'product_cover' => (int)$image['id_image'],
			'product_link' => $product->getLink(),
			'comparator_max_item' => $comparator_max_item,
		));
		return $this->display(__FILE__, 'owlrightsidebar-extra.tpl');
	}

	public function hookDisplayLeftColumnProduct($params)
	{
		return $this->hookProductActions($params);
	}
	
	public function hookDisplayProductSecondaryColumn($params)
	{
		return $this->hookProductActions($params);
	}
}