<?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-2016 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

include_once(dirname(__FILE__).'/classes/OwlExtraTabsClass.php');
include_once(dirname(__FILE__).'/sql/SampleDataExtratab.php');
class OwlExtraTabs extends Module
{
	protected $error = false;
	protected $user_groups;
	private $_html;
	public function __construct()
	{
		$this->name = 'owlextratabs';
		$this->tab = 'front_office_features';
		$this->version = '1.0.0';
		$this->author = 'owltheme';
		$this->bootstrap = true;
		parent::__construct();
		$this->displayName = $this->l('OWL Product Extra Tabs');
		$this->description = $this->l('Add Product Extra Tabs');
		$this->confirmUninstall = $this->l('Are you sure that you want to delete?');
	}
	
	public function install()
	{	
		if (parent::install() == false || !$this->registerHook('actionShopDataDuplication') || !$this->registerHook('actionObjectLanguageAddAfter') || !$this->registerHook('displayBackOfficeHeader') || !$this->registerHook('productTab') || !$this->registerHook('productTabContent'))
			return false;
		include(dirname(__FILE__).'/sql/install.php');
		$sample_data = new SampleDataExtratab();
		$sample_data->initData();
		return true;
	}
	public function uninstall()
	{
		include(dirname(__FILE__).'/sql/uninstall.php');
		if (parent::uninstall() == false)
			return false;
		return true;
	}
	public function hookDisplayBackOfficeHeader()
	{
		$this->context->controller->addJS($this->_path.'views/js/admin.js');
	}
	public function getContent()
	{
		if (Tools::isSubmit('changeStatus') || Tools::isSubmit('delete_cat_block'))
		{
			$this->_postProcess();
			$this->_html .= $this->renderList();
		}
		elseif (Tools::isSubmit('addblock') || Tools::isSubmit('id_owlextratabs') || Tools::isSubmit('saveBlock'))
		{
			$this->_postProcess();
			$this->renderAddForm();
		}
		else
		{
			$this->_postProcess();
			$this->_html .= $this->renderList();
		}
		return $this->_html;
	}
	private function _postProcess()
	{
		$errors = array();
		if (Tools::isSubmit('saveBlock'))
		{
			$block = new OwlExtraTabsClass(Tools::getValue('id_owlextratabs'));
			$block->copyFromPost();
			$errors = $block->validateController();		
			if (count($errors))
				$this->_html .= $this->displayError(implode('. ', $errors));
			else
			{
				Tools::getValue('id_owlextratabs') ? $block->update() : $block->add();
				$this->clearCacheBlock();
				Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules').'&saveBlockConfirmation');
			}
		}
		elseif (Tools::isSubmit('changeStatus') && Tools::getValue('id_owlextratabs'))
		{
			$block = new OwlExtraTabsClass(Tools::getValue('id_owlextratabs'));
			if ($block->active == 0)
				$block->active = 1;
			else
				$block->active = 0;
			$res = $block->update();
			$this->clearCacheBlock();
			$this->html .= ($res ? $this->displayConfirmation($this->l('Configuration updated')) : $this->displayError($this->l('The configuration could not be updated.')));
			Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
		}
		elseif (Tools::isSubmit('delete_id_block'))
		{
			$block = new OwlExtraTabsClass(Tools::getValue('delete_id_block'));
			$block->delete();
			$this->clearCacheBlock();
			Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules').'&deleteBlockConfirmation');
		}
		elseif (Tools::isSubmit('saveBlockConfirmation'))
			$this->_html = $this->displayConfirmation($this->l('Static block has been saved successfully'));
		elseif (Tools::isSubmit('deleteBlockConfirmation'))
			$this->_html = $this->displayConfirmation($this->l('Static block deleted successfully'));
	}
	private function clearCacheBlock()
	{
		$this->_clearCache('extratabs.tpl');
		$this->_clearCache('extratabs_content.tpl');
	}
	
	private function getBlocks()
	{
		$this->context = Context::getContext();
		$id_lang = $this->context->language->id;
		$id_shop = $this->context->shop->id;
		if (!$result = Db::getInstance()->ExecuteS(
			'SELECT b.*, bs.*, bl.* 
			FROM `'._DB_PREFIX_.'owlextratabs` b 
			LEFT JOIN `'._DB_PREFIX_.'owlextratabs_shop` bs ON (b.`id_owlextratabs` = bs.`id_owlextratabs` )
			LEFT JOIN `'._DB_PREFIX_.'owlextratabs_lang` bl ON (b.`id_owlextratabs` = bl.`id_owlextratabs`'.( $id_shop ? 'AND bl.`id_shop` = '.$id_shop : ' ' ).') 
			WHERE bl.id_lang = '.(int)$id_lang.
			( $id_shop ? ' AND bs.`id_shop` = '.$id_shop : ' ' )))
			return false;
		return $result;
	}
	
	public function renderList()
	{
		$blocks = array();
		$id_lang = $this->context->language->id;
		
		if ($this->getBlocks() && count($this->getBlocks()) > 0)
		{
			$blocks = $this->getBlocks();
			foreach ($blocks as $key => $block)
			{
				if ($block['id_cat'] != 0)
				{
					$category = new Category($block['id_cat'], $id_lang);
					$blocks[$key]['cat_name'] = $category->name;
				}
				else
					$blocks[$key]['cat_name'] = 'All';
				
				$blocks[$key]['status'] = $this->displayStatus($block['id_owlextratabs'], $block['active']);
			}	
		}
		$this->context->smarty->assign(
			array(
				'link' => $this->context->link,
				'blocks' => $blocks
			)
		);
		return $this->display(__FILE__, 'views/templates/admin/list.tpl');
	}
	
	public function renderAddForm()
	{
		$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
		$this->fields_form[0]['form'] = array(
					'tinymce' => true,
					'legend' => array(
					'title' => $this->l('Block item'),
			),
			'input' => array(
				array(
					'type' => 'category_list',
					'label' => $this->l('Cat ID'),
					'name' => 'id_cat'
				),
				array(
					'type' => 'select_product',
					'label' => $this->l('Product'),
					'name' => 'product'
				),
				array(
					'type' => 'text',
					'label' => $this->l('Title'),
					'lang' => true,
					'name' => 'title',
					'cols' => 40,
					'rows' => 10	
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('HTML'),
					'name' => 'content',
					'lang' => true,
					'autoload_rte' => true,
					'cols' => 40,
					'rows' => 10
				),
				array(
						'type' => 'switch',
						'label' => $this->l('Displayed'),
						'name' => 'active',
						'values' => array(
									array(
										'id' => 'active_on',
										'value' => 1,
										'label' => $this->l('Enabled')
									),
									array(
										'id' => 'active_off',
										'value' => 0,
										'label' => $this->l('Disabled')
									)
						),
				)
			),
			'submit' => array(
				'title' => $this->l('Save'),
			)
		);
		
		$helper = new HelperForm();
		$helper->module = $this;
		$helper->name_controller = 'owlextratabs';
		$helper->identifier = $this->identifier;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->show_cancel_button = true;
		$helper->back_url = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules');
		foreach (Language::getLanguages(false) as $lang)
			$helper->languages[] = array(
				'id_lang' => $lang['id_lang'],
				'iso_code' => $lang['iso_code'],
				'name' => $lang['name'],
				'is_default' => ($default_lang == $lang['id_lang'] ? 1 : 0)
			);

		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name;
		$helper->default_form_language = $default_lang;
		$helper->allow_employee_form_lang = $default_lang;
		$helper->toolbar_scroll = true;
		$helper->title = $this->displayName;
		$helper->submit_action = 'saveBlock';
		$helper->toolbar_btn = array(
			'save' =>
			array(
				'desc' => $this->l('Save'),
				'href' => $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&save'.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
			),
			'back' =>
			array(
				'href' => $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
				'desc' => $this->l('Back to list')
			)
		);
		
		$id_owlextratabs = (int)Tools::getValue('id_owlextratabs');
		$cat_value = 0;
		$product_id = 0;
		if (Tools::isSubmit('id_owlextratabs') && $id_owlextratabs)
		{
			$block = new OwlExtraTabsClass($id_owlextratabs);
			$this->fields_form[0]['form']['input'][] = array('type' => 'hidden', 'name' => 'id_owlextratabs');
			$helper->fields_value['id_owlextratabs'] = (int)Tools::getValue('id_owlextratabs', $block->id_owlextratabs);
			$helper->fields_value['active'] = Tools::getValue('active', $block->active);
			$helper->fields_value['product'] = Tools::getValue('product', $block->product);
			$helper->fields_value['id_cat'] = Tools::getValue('id_cat', $block->id_cat);
			$cat_value = Tools::getValue('id_cat', $block->id_cat);
			$product_id = Tools::getValue('product', $block->product);
		}
		else
		{
			$block = new OwlExtraTabsClass();
			$helper->fields_value['active'] = Tools::getValue('active', 1);
			$helper->fields_value['product'] = Tools::getValue('product', 0);
		}
		foreach (Language::getLanguages(false) as $lang)
		{
			$helper->fields_value['title'][(int)$lang['id_lang']] = Tools::getValue('title_'.(int)$lang['id_lang'], $block->title[(int)$lang['id_lang']]);
			$helper->fields_value['content'][(int)$lang['id_lang']] = Tools::getValue('content_'.(int)$lang['id_lang'], $block->content[(int)$lang['id_lang']]);
		}
		if ($product_id != 0)
			$product_select = new Product($product_id, false, $default_lang);
		else
			$product_select = array();
		
		$cat_options = $this->getRespCategories();
		$language = $this->context->controller->getLanguages();
		
		$helper->tpl_vars = array(
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id,
			'image_baseurl' => $this->_path.'views/img/',
			'link' => $this->context->link,
			'cat_options' => $cat_options,
			'cat_value' => $cat_value,
			'product_select' => $product_select,
			'ajax_url' => $this->_path.'ajax.php'
		);
		$this->_html .= $helper->generateForm($this->fields_form);
	}
	public function displayStatus($id, $active)
	{
		$status_arr = array();
		if ($active == 0)
		{
			$status_arr['title'] = $this->l('Disabled');
			$status_arr['icon'] = 'icon-remove';
			$status_arr['class'] = 'btn-danger';
		}
		else
		{
			$status_arr['title'] = $this->l('Enabled');
			$status_arr['icon'] = 'icon-check';
			$status_arr['class'] = 'btn-success';
		}
		$status_arr['s_href'] = AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules').'&changeStatus&id_owlextratabs='.$id;
		return $status_arr;
	}
	
	public function getRespCategories($id_category = 2, $id_lang = false, $id_shop = false, $level_root = 1, $sub_title = '', $type_icon = 1, $icon = '', $sub_align = '', $spec_class = '')
	{
		$id_lang = $id_lang ? (int)$id_lang : (int)Context::getContext()->language->id;
		$categories = Category::getNestedCategories($id_category, $id_lang, false, $this->user_groups);
		$menu = $this->generateCategoriesMenu($categories);
		return $menu;
	}
	
	public function generateCategoriesMenu($categories, $is_children = 0)
	{
		$nodes = [];

		foreach ($categories as $key => $category)
		{
			$node = $this->makeNode([]);

			if ($category['level_depth'] > 1)
			{
				$cat = new Category($category['id_category']);
				$link = $cat->getLink();
			}
			else
				$link = $this->context->link->getPageLink('index');

			$node['id'] = $category['id_category'];
			$node['url'] = $link;
			$node['type'] = 'category';
			$node['page_identifier'] = 'category-'.$category['id_category'];

			if ((bool)$category['active'] === false)
				continue;
		
			if (isset($this->context->smarty->tpl_vars['page_name']))
			{
				$page_name = $this->context->smarty->tpl_vars['page_name']->value;
				$current = $page_name == 'category' && (int)Tools::getValue('id_category') == (int)$category['id_category'];
				$node['current'] = $current;
			}
			
			$node['label']   = $category['name'];
			$node['image_urls']  = [];

			if (isset($category['children']) && !empty($category['children']))
			{
				$node['children'] = $this->generateCategoriesMenu($category['children'], 1);

				$files = scandir(_PS_CAT_IMG_DIR_);

				if (count(preg_grep('/^'.$category['id_category'].'-([0-9])?_thumb.jpg/i', $files)) > 0)
				{
					foreach ($files as $file)
					{
						if (preg_match('/^'.$category['id_category'].'-([0-9])?_thumb.jpg/i', $file) === 1)
						{
							$image_url = $this->context->link->getMediaLink(_THEME_CAT_DIR_.$file);
							$node['image_urls'][] = $image_url;
						}
					}
				}
			}

			$nodes[] = $node;
		}

		return $nodes;
	}

	protected function makeNode(array $fields)
	{
		$defaults = [
			'type' => '',
			'label' => '',
			'url' => '',
			'children' => [],
			'open_in_new_window' => false,
			'image_urls' => [],
			'page_identifier' => null,
			'id' => 2
		];

		return array_merge($defaults, $fields);
	}

	public function getProductsByIdCategory($id_category = 0)
	{
		$id_shop = $this->context->shop->id;
		if (!$id_category || $id_category == 0)
			return false;
		
		return DB::getInstance()->ExecuteS('SELECT pl.id_product, pl.name
		FROM '._DB_PREFIX_.'category_product AS cp, '._DB_PREFIX_.'product_lang AS pl
		WHERE
			cp.id_product = pl.id_product AND
			cp.id_category = '.$id_category.' AND
			pl.id_shop = '.$id_shop.' AND
			pl.id_lang = '.(int)(Configuration::get('PS_LANG_DEFAULT')));
	}

	private function getBlockExtraTabs()
	{
		$results = array();
		$this->context = Context::getContext();
		$id_shop = (int)$this->context->shop->id;
		$id_lang = (int)$this->context->language->id;
		
		$results = Db::getInstance()->ExecuteS('SELECT b.*, bs.*, bl.* FROM `'._DB_PREFIX_.'owlextratabs` b
		LEFT JOIN `'._DB_PREFIX_.'owlextratabs_shop` bs ON (b.id_owlextratabs = bs.id_owlextratabs)
		LEFT JOIN `'._DB_PREFIX_.'owlextratabs_lang` bl ON (bs.id_owlextratabs = bl.id_owlextratabs)
		WHERE bs.active = 1 AND (bs.id_shop = '.$id_shop.') AND bl.`id_lang` = "'.$id_lang.'"');
		
		return $results;
	}

	public function getTabsByIdProduct($id_product = null)
	{
		if (!$id_product)
			return;
		$product = new Product($id_product);
		$tabs = $this->getBlockExtraTabs();
		$result = array();
		foreach ($tabs as $tab)
		{
			if (($tab['id_cat'] == 0) || ($tab['id_cat'] == $product->id_category_default && $tab['product'] == 0) || ($tab['id_cat'] == $product->id_category_default && (int)$tab['product'] == $id_product))
				$result[] = $tab;
		}
		return $result;

	}
	public function hookProductTabContent()
	{
		$id_product = (int)Tools::getValue('id_product');
		if (!$this->isCached('extratabs_content.tpl', $this->getCacheId('extratabs_content')))
		{
			$tabs = $this->getTabsByIdProduct('id_product');
			if (count($tabs) > 0)
				$this->context->smarty->assign(array(
					'tabs' => $tabs
				));
		}
		return $this->display(__FILE__, 'extratabs_content.tpl', $this->getCacheId('extratabs_content'));
	}
	public function hookProductTab()
	{
		$id_product = (int)Tools::getValue('id_product');
		$tabs = $this->getTabsByIdProduct($id_product);
		
		if (count($tabs) > 0)
		{
			$this->smarty->assign('tabs', $tabs);
			return $this->display(__FILE__, 'extratabs.tpl');
		}
	}
	
	public function hookActionShopDataDuplication($params)
	{
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owlextratabs_shop (id_owlextratabs, id_shop, id_cat, product, active)
		SELECT id_owlextratabs, '.(int)$params['new_id_shop'].', id_cat, product, active
		FROM '._DB_PREFIX_.'owlextratabs_shop
		WHERE id_shop = '.(int)$params['old_id_shop']);
		
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owlextratabs_lang (id_owlextratabs, id_shop, id_lang, title, content)
		SELECT id_owlextratabs, '.(int)$params['new_id_shop'].', id_lang, title, content
		FROM '._DB_PREFIX_.'owlextratabs_lang
		WHERE id_shop = '.(int)$params['old_id_shop']);
	}
	public function hookActionObjectLanguageAddAfter($params)
	{
		Db::getInstance()->execute('
		INSERT IGNORE INTO '._DB_PREFIX_.'owlextratabs_lang (id_owlextratabs, id_shop, id_lang, title, content)
		SELECT id_owlextratabs,id_shop, '.(int)$params['object']->id.', title, content
		FROM '._DB_PREFIX_.'owlextratabs_lang
		WHERE id_lang = '.(int)Configuration::get('PS_LANG_DEFAULT'));	
	}
}
?>