<?php
/**
* Man Carousel v1.0
* @author kik-off.com <info@kik-off.com>
**/

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

class ManCarousel extends Module
{
    private $_html = '';
	private $user_groups;
	private $hide_form;

	public function __construct()
    {
        $this->name = 'mancarousel';
        $this->tab = 'front_office_features';
        $this->version = '1.0';
        $this->author = 'kik-off.com';
        $this->need_instance = 0;

        parent::__construct();

        $this->displayName = $this->l('Man Carousel');
        $this->description = $this->l('Smooth manufacturer carousel.');
    }

    public function install()
    {
        Configuration::updateValue('MAN_CAROUSEL', serialize(array(2, 'medium', 8, 8, 'false', 5000, 'true', 'true', 'true', 'true', 'true', 'none', 500)));
		$this->registerHook('actionObjectManufacturerUpdateAfter');
	    $this->registerHook('actionObjectManufacturerDeleteAfter');
		$this->registerHook('actionObjectManufacturerAddAfter');	
		
		if (parent::install() == false
			OR !$this->registerHook('header')
			OR !$this->registerHook('top')
			OR !$this->registerHook('home')
			OR !$this->registerHook('footer')
		)
            return false;
        return true;
    }

	public function uninstall()
    {
        if (parent::uninstall() == false ||
		    !Configuration::deleteByName('MAN_CAROUSEL')
		)
            return false;
		return true;
    }

	public function getContent()
	{
		if (Tools::isSubmit('manCarouselFormSubmit'))
		{
		    $hook = Tools::getValue('man_carousel_hook');
			$type = Tools::getValue('man_carousel_image_type');
			$items = Tools::getValue('man_carousel_display_items');
			$scroll = Tools::getValue('man_carousel_scroll_items');
			$responsive = Tools::getValue('man_carousel_responsive');
			$time = Tools::getValue('man_carousel_pause_time');
			$start = Tools::getValue('man_carousel_auto_start');
			$random = Tools::getValue('man_carousel_random');
			$circular = Tools::getValue('man_carousel_circular');
			$infinite = Tools::getValue('man_carousel_infinite');
			$mouseover_pause = Tools::getValue('man_carousel_mouseover_pause');
			$fx = Tools::getValue('man_carousel_fx');
			$fx_time = Tools::getValue('man_carousel_fx_time');

			Configuration::updateValue('MAN_CAROUSEL', serialize(array((int)$hook, $type, (int)$items, (int)$scroll, $responsive, (int)$time, $start, $random, $circular, $infinite, $mouseover_pause, $fx, (int)$fx_time)));
			
			$this->restoreManCarouselCaches();

			$this->_html .= '<div class="conf">'.$this->l('Settings updated').'</div>';
	    }

		if (Tools::isSubmit('flushCacheFormSubmit'))
		{
			if(_PS_VERSION_ > '1.4.0.0' && _PS_VERSION_ < '1.5.0.0')
            {
			    $files = glob('../tools/'.(_PS_FORCE_SMARTY_2_ ? 'smarty_v2' : 'smarty').'/cache/*.mancarousel.tpl.php',GLOB_BRACE);
		    }
		    elseif(_PS_VERSION_ >= '1.5.0.0' && _PS_VERSION_ < '1.5.4.1')
            {
			    $files = glob('../cache/smarty/cache/*.mancarousel.tpl.php',GLOB_BRACE);
		    }
		    elseif(_PS_VERSION_ == '1.5.4.1' && _PS_VERSION_ < '1.5.5.0')
		    {
			    $files = glob('../cache/smarty/cache/mancarousel/*/*/*/*/*/*/*/*.mancarousel.tpl.php',GLOB_BRACE);
		    }
		    elseif(_PS_VERSION_ >= '1.5.5.0')
	        {
		   	    $files = glob('../cache/smarty/cache/*/*/*/*/*/*/*/*/*/*/*.mancarousel.tpl.php',GLOB_BRACE);
    	    }

			if($files)
			{
			    $num_files = count($files);
				foreach($files as $file)
				{
				    if(is_file($file))
                        unlink($file);
				}

				$this->_html .=  '<div class="conf">'.$this->l('Cache flushed!').'<br/>'. $this->l('Removed items').' : '.$num_files.'<br/>';

					foreach($files as $index => $file)
				    {
				        $this->_html .= ($index+1).' "'.$file.'"<br/>';
				    }

				$this->_html .=  '</div>';
			}
			else{
			    $this->_html .=  $this->displayConfirmation($this->l('Files not found.'));
			}
	    }

		$this->_html .= '<h2>'.$this->displayName.'</h2>';

		$this->_html .= '
		<style type="text/css">
		    #imprint{width: 100%; text-align: right;}
            #imprint-logo {float: left;}
		</style>';

		$mancarousel = $this->getManCarouselConfig();
		$images = ImageType::getImagesTypes('manufacturers');

		$this->_html .= '
		<fieldset>
			<legend><img src="'.$this->_path.'logo.gif" alt="" />'.$this->l('Settings').'</legend><br/>
			<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			    <label>'.$this->l('Display in').':</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_hook" id="man_carousel_hook_0" value="0" '.((int)$mancarousel['hook'] == 0 ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_hook_0"><b>'.$this->l('Top').'</b></label><br/>
					<input type="radio" name="man_carousel_hook" id="man_carousel_hook_1" value="1" '.((int)$mancarousel['hook'] == 1 ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_hook_1"><b>'.$this->l('Home').'</b></label><br/>
					<input type="radio" name="man_carousel_hook" id="man_carousel_hook_2" value="2" '.((int)$mancarousel['hook'] == 2 ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_hook_2"><b>'.$this->l('Footer').'</b></label>
					<p class="preference_description clear">'.$this->l('Select the hook where you want to display the block').'.</p>
				</div>
				<label>'.$this->l('Select image type').'</label>
			    <div class="margin-form">
			        <select id="man_carousel_image_type" name="man_carousel_image_type">';
		        foreach ($images AS $key => $image)
		        {
				    $this->_html .= '<option value="' . $image['name'] . '"'.($mancarousel['type'] == $image['name'] ? ' selected="selected" class="selected"' : '').'>' . $image['name'] . ' (' . $image['width'] . 'x' . $image['height'] . ')</option>';
		        }
		        $this->_html .= '
				    </select>
				</div>
				<label>'.$this->l('Responsive').'</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_responsive" id="man_carousel_responsive_on" value="true" '.(($mancarousel['responsive'] == 'true') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_responsive_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="man_carousel_responsive" id="man_carousel_responsive_off" value="false" '.(($mancarousel['responsive'] == 'false') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_responsive_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="preference_description clear">'.$this->l('If enabled, the visible and scroll items will ignored').'.</p>
				</div>
			    <label>'.$this->l('Visible items').'</label>
				<div class="margin-form">
					<input type="text" name="man_carousel_display_items" id="man_carousel_display_items" size="3" value="'.Tools::getValue('man_carousel_display_items', $mancarousel['items']).'" />
				</div>
				<label>'.$this->l('Scroll items').'</label>
				<div class="margin-form">
					<input type="text" name="man_carousel_scroll_items" id="man_carousel_scroll_items" size="3" value="'.Tools::getValue('man_carousel_scroll_items', $mancarousel['scroll']).'" />
				</div>
				<label>'.$this->l('Pause').'</label>
				<div class="margin-form">
					<input type="text" name="man_carousel_pause_time" id="man_carousel_pause_time" size="3" value="'.Tools::getValue('man_carousel_pause_time', $mancarousel['time']).'" />
					<p class="preference_description clear">'.$this->l('The amount of milliseconds the carousel will pause').'.</p>
				</div>
				<label>'.$this->l('Auto start').'</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_auto_start" id="man_carousel_auto_start_on" value="true" '.(($mancarousel['start'] == 'true') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_auto_start_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="man_carousel_auto_start" id="man_carousel_auto_start_off" value="false" '.(($mancarousel['start'] == 'false') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_auto_start_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				<label>'.$this->l('Random').'</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_random" id="man_carousel_random_on" value="true" '.(($mancarousel['random'] == 'true') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_random_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="man_carousel_random" id="man_carousel_random_off" value="false" '.(($mancarousel['random'] == 'false') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_random_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				<label>'.$this->l('Circular').'</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_circular" id="man_carousel_circular_on" value="true" '.(($mancarousel['circular']  == 'true') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_circular_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="man_carousel_circular" id="man_carousel_circular_off" value="false" '.(($mancarousel['circular'] == 'false') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_circular_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="preference_description clear">'.$this->l('Determines whether the carousel should be circular').'.</p>
				</div>
				<label>'.$this->l('Infinite').'</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_infinite" id="man_carousel_infinite_on" value="true" '.(($mancarousel['infinite'] == 'true') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_infinite_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="man_carousel_infinite" id="man_carousel_infinite_off" value="false" '.(($mancarousel['infinite'] == 'false') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_infinite_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="preference_description clear">'.$this->l('Determines whether the carousel should be infinite. Note: It is possible to create a non-circular, infinite carousel, but it is not possible to create a circular, non-infinite carousel').'.</p>
				</div>
				<label>'.$this->l('Mouseover pause').'</label>
				<div class="margin-form">
					<input type="radio" name="man_carousel_mouseover_pause" id="man_carousel_mouseover_on" value="true" '.(($mancarousel['mouseover_pause'] == 'true') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_mouseover_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="man_carousel_mouseover_pause" id="man_carousel_mouseover_off" value="false" '.(($mancarousel['mouseover_pause'] == 'false') ? 'checked="checked" ' : '').'/>
					<label class="t" for="man_carousel_mouseover_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				<label>'.$this->l('Transition').'</label>
				<div class="margin-form">
					<select name="man_carousel_fx" style="width:100px;" />
					    <option value="none"'.($mancarousel['fx'] == 'none' ? ' selected="selected"' : '').'>'.$this->l('None').'</option>
					    <option value="scroll"'.($mancarousel['fx'] == 'scroll' ? ' selected="selected"' : '').'>'.$this->l('Scroll').'</option>
						<option value="directscroll"'.($mancarousel['fx'] == 'directscroll' ? ' selected="selected"' : '').'>'.$this->l('Direct scroll').'</option>
						<option value="fade"'.($mancarousel['fx'] == 'fade' ? ' selected="selected"' : '').'>'.$this->l('Fade').'</option>
						<option value="crossfade"'.($mancarousel['fx'] == 'crossfade' ? ' selected="selected"' : '').'>'.$this->l('Crossfade').'</option>
						<option value="cover"'.($mancarousel['fx'] == 'cover' ? ' selected="selected"' : '').'>'.$this->l('Cover').'</option>
						<option value="cover-fade"'.($mancarousel['fx'] == 'cover-fade' ? ' selected="selected"' : '').'>'.$this->l('Cover fade').'</option>
						<option value="uncover"'.($mancarousel['fx'] == 'uncover' ? ' selected="selected"' : '').'>'.$this->l('Uncover').'</option>
						<option value="uncover-fade"'.($mancarousel['fx'] == 'uncover-fade' ? ' selected="selected"' : '').'>'.$this->l('Uncover fade').'</option>
					</select>
				</div>
				<label>'.$this->l('Duration').'</label>
				<div class="margin-form">
					<input type="text" name="man_carousel_fx_time" id="man_carousel_fx_time" size="3" value="'.Tools::getValue('man_carousel_fx_time', $mancarousel['fx_time']).'" />
					<p class="preference_description clear">'.$this->l('Duration of the transition in milliseconds').'.</p>
				</div>
				<div class="margin-form">
				    <input class="button" name="manCarouselFormSubmit" type="submit" value="'.$this->l('Save').'" />
				</div>
		</form></fieldset><br/>';

		$this->displayCacheTools();

		$this->_html .= '
		<div id="imprint">
		    <fieldset>
			    <span id="imprint-logo"><a href="http://kik-off.com" target="_blank" title="http://kik-off.com"><img src="'.$this->_path.'img/logo_kik_off.gif" alt="" /></a> '.$this->displayName.' v'.$this->version.'</span>
			    <span id="imprint-text">'.$this->l('Module by').': <a href="http://kik-off.com" target="_blank" title="http://kik-off.com">kik-off.com</a>, <a href="mailto:support@kik-off.com">support@kik-off.com</a></span>
			</fieldset>
		</div>
		';

		return $this->_html;
	}
	
	private function getManCarouselConfig()
	{
	    $getConfig = unserialize(Configuration::get('MAN_CAROUSEL'));
		
		$mancarousel = array();
		$mancarousel['hook'] = $getConfig[0];
		$mancarousel['type'] = $getConfig[1];
		$mancarousel['items'] = $getConfig[2];
		$mancarousel['scroll'] = $getConfig[3];
		$mancarousel['responsive'] = $getConfig[4];
		$mancarousel['time'] = $getConfig[5];
		$mancarousel['start'] = $getConfig[6];
		$mancarousel['random'] = $getConfig[7];
		$mancarousel['circular'] = $getConfig[8];
		$mancarousel['infinite'] = $getConfig[9];
		$mancarousel['mouseover_pause'] = $getConfig[10];
		$mancarousel['fx'] = $getConfig[11];
		$mancarousel['fx_time'] = $getConfig[12];
		
	    return $mancarousel;
	}
	
	private function getManCarouselHook()
	{
	    $getConfig = unserialize(Configuration::get('MAN_CAROUSEL'));
		
		$hook = $getConfig[0];
		
	    return $hook;
	}
	
	public function restoreManCarouselCaches()
	{
	    if(_PS_VERSION_ > '1.4.0.0' && _PS_VERSION_ < '1.5.0.0')
        {
			$files = glob('../tools/'.(_PS_FORCE_SMARTY_2_ ? 'smarty_v2' : 'smarty').'/cache/*.mancarousel.tpl.php',GLOB_BRACE);
		}
		elseif(_PS_VERSION_ >= '1.5.0.0' && _PS_VERSION_ < '1.5.4.1')
        {
			$files = glob('../cache/smarty/cache/*.mancarousel.tpl.php',GLOB_BRACE);
		}
		elseif(_PS_VERSION_ == '1.5.4.1' && _PS_VERSION_ < '1.5.5.0')
		{
			$files = glob('../cache/smarty/cache/mancarousel/*/*/*/*/*/*/*/*.mancarousel.tpl.php',GLOB_BRACE);
		}
		elseif(_PS_VERSION_ >= '1.5.5.0')
	    {
		   	$files = glob('../cache/smarty/cache/*/*/*/*/*/*/*/*/*/*/*.mancarousel.tpl.php',GLOB_BRACE);
    	}

		if($files)
		{
			foreach($files as $file)
			{
				if(is_file($file))
                    unlink($file);
			}
		}
	}

	public function displayCacheTools()
	{			
		if(_PS_VERSION_ > '1.4.0.0' && _PS_VERSION_ < '1.5.0.0')
        {
			$files = glob('../tools/'.(_PS_FORCE_SMARTY_2_ ? 'smarty_v2' : 'smarty').'/cache/*.mancarousel.tpl.php',GLOB_BRACE);
		}
		elseif(_PS_VERSION_ >= '1.5.0.0' && _PS_VERSION_ < '1.5.4.1')
        {
			$files = glob('../cache/smarty/cache/*.mancarousel.tpl.php',GLOB_BRACE);
		}
		elseif(_PS_VERSION_ == '1.5.4.1' && _PS_VERSION_ < '1.5.5.0')
		{
			$files = glob('../cache/smarty/cache/mancarousel/*/*/*/*/*/*/*/*.mancarousel.tpl.php',GLOB_BRACE);
		}
		elseif(_PS_VERSION_ >= '1.5.5.0')
	    {
		   	$files = glob('../cache/smarty/cache/*/*/*/*/*/*/*/*/*/*/*.mancarousel.tpl.php',GLOB_BRACE);
    	}

		$this->_html .= '
		<fieldset>
		<legend><img src="'.$this->_path.'logo.gif" alt="" />'.$this->l('Cache').'</legend>
		<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<label>'.$this->l('Flush cache').'</label>
            <div class="margin-form">
				<button id="flushCacheFormSubmit" class="button" name="flushCacheFormSubmit">'.$this->l('OK').'</button>
			</div>
		</form>
		<label>'.$this->l('Cached files').'</label>
		<ul class="margin-form" style="list-style: none;">';
		if ($files)
		{
    	    foreach($files as $index => $file)
			{
				if ($size = filesize($file))
                {
                    $fileSize = round(($size / 1024), 2).' KB';
                }
	    		$this->_html .= '<li><b>'.($index+1).'</b> "'.$file.'" '.$fileSize.' '.date ("F d Y H:i:s.", filemtime($file)).'</li>';
		    }
		}
		else
		{
		    $this->_html .= '<li>'.$this->l('Cache is empty').'</li>';
		}
		$this->_html .= '</ul>
		</fieldset>
		<br/>';
	}
	
	public function hookActionObjectManufacturerUpdateAfter($params)
	{
		$this->restoreManCarouselCaches();
	}

	public function hookActionObjectManufacturerDeleteAfter($params)
	{
		$this->restoreManCarouselCaches();
	}

	public function hookHeader($params)
    {
		if(_PS_VERSION_ > '1.4.0.0' && _PS_VERSION_ < '1.5.0.0')
        {
		    Tools::addCSS($this->_path.'css/'.$this->name.'.css', 'all');
			Tools::addJS($this->_path.'js/jquery.carouFredSel-6.2.1-packed.js');
		}
		if(_PS_VERSION_ > '1.5.0.0')
		{
		    $this->context->controller->addCSS(($this->_path).'css/'.($this->name).'.css', 'all');
			$this->context->controller->addJS(($this->_path).'js/jquery.carouFredSel-6.2.1-packed.js');
		}
    }
	
	public function _createManCarousel()
	{
		$mancarousel = $this->getManCarouselConfig();
		
		if(_PS_VERSION_ > '1.4.0.0' && _PS_VERSION_ < '1.5.0.0')
    	{
			global $smarty, $cookie;
			
			$id_lang = $cookie->id_lang;
			$id_customer = null;
			
			$mancarousel_items = Manufacturer::getManufacturers(false, $id_lang, true, false, false, false);
			$groups = $id_customer ? implode(', ', Customer::getGroupsStatic($id_customer)) : _PS_DEFAULT_CUSTOMER_GROUP_;
			$smartyCacheId = 'mancarousel|'.$groups.'_'.$id_lang;

			$smarty->cache_lifetime = 360000;
		    Tools::enableCache();
		   	if (!$this->isCached('mancarousel.tpl', $smartyCacheId))
		   	{
			    $smarty->assign(array(
				    'mancarousel' => $mancarousel,
					'imageSize' => Image::getSize($mancarousel['type']),
				    'mancarousel_items' => $mancarousel_items
			    ));
			}
			$html = $this->display(__FILE__, 'mancarousel.tpl', $smartyCacheId);
		    Tools::restoreCacheSettings();
		    return $html;
		}
		elseif(_PS_VERSION_ > '1.5.0.0')
		{
		    $id_current_shop_group = Shop::getContextShopGroupID();
			$mancarousel_items = Manufacturer::getManufacturers(true, $this->context->language->id, true, false, false, false, $id_current_shop_group);
			
			if(_PS_VERSION_ >= '1.5.0.0' && _PS_VERSION_ < '1.5.4.1')
		    {
	    	    $this->user_groups =  ($this->context->customer->isLogged() ? $this->context->customer->getGroups() : array(Configuration::get('PS_UNIDENTIFIED_GROUP')));
		        $smarty_cache_id = 'mancarousel-'.(int)$this->context->shop->id.'-'.implode(', ',$this->user_groups).'-'.(int)$this->context->language->id;
		   	    $this->context->smarty->cache_lifetime = 360000;
		   	    Tools::enableCache();

		        if (!$this->isCached('mancarousel.tpl', $smarty_cache_id))
			    {
				    $this->smarty->assign(array(
				        'mancarousel' => $mancarousel,
					    'imageSize' => Image::getSize($mancarousel['type']),
				        'mancarousel_items' => $mancarousel_items
				    ));
			    }

		        $html = $this->display(__FILE__, 'mancarousel.tpl', $smarty_cache_id);
		        Tools::restoreCacheSettings();
		        return $html;
		    }
		    elseif(_PS_VERSION_ >= '1.5.4.1')
		    {
                if (!$this->isCached('mancarousel.tpl', $this->getCacheId()))
			    {
			        $this->smarty->assign(array(
				        'mancarousel' => $mancarousel,
					    'imageSize' => Image::getSize($mancarousel['type']),
				        'mancarousel_items' => $mancarousel_items
				    ));
			    }
		        return $this->display(__FILE__, 'mancarousel.tpl', $this->getCacheId());
		    }
		}
	}

	public function hookFooter($params)
    {
		if($this->getManCarouselHook() == 2)
		{
			return $this->_createManCarousel();
		}
    }

	public function hookHome($params)
    {
	    if($this->getManCarouselHook() == 1)
		{
			return $this->_createManCarousel();
		}
	}

	public function hookTop($params)
    {
	    if($this->getManCarouselHook() == 0)
		{
			return $this->_createManCarousel();
		}
	}
}
?>