<?php
/**
 * $ModDesc
 * 
 * @version		$Id: file.php $Revision
 * @package		modules
 * @subpackage	$Subpackage.
 * @copyright	Copyright (C) December 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>.All rights reserved.
 * @license		GNU General Public License version 2
 */
if (!defined('_CAN_LOAD_FILES_')){
	define('_CAN_LOAD_FILES_',1);
}    

class lofnewproduct extends Module
{
	private $_params = '';	
	private $_postErrors = array();	
    
    	
	function __construct(){
		$this->name = 'lofnewproduct';
		parent::__construct();			
		$this->tab = 'LandOfCoder';				
		$this->version = '1.0.0';
		$this->displayName = $this->l('Lof New Products Module');
		$this->description = $this->l('Lof New Products Module');
		if( file_exists( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/params.php' ) && !class_exists("LofParams", false) ){
			if( !defined("LOF_LOAD_LIB_PARAMS") ){				
				require( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/params.php' );
				define("LOF_LOAD_LIB_PARAMS",true);
			}
		}		
		$this->_params = new LofParams( $this->name );
        	   
	}
  
   /**
    * process installing 
    */
	function install(){		
		if (!parent::install())
			return false;
		if(!$this->registerHook('home'))
			return false;
		if(!$this->registerHook('header'))
			return false;	
		return true;
	}
	
    /*
    * Add Position for site
    */
    
    function hooklofPresDemo($params){
        return $this->processHook( $params,"lofPresDemo");
    }
    
    function hooklofnewproduct($params){
        return $this->processHook( $params,"lofnewproduct");
    }
	/*
	 * register hook right comlumn to display slide in right column
	 */
	function hookrightColumn($params)
	{		
		return $this->processHook( $params,"rightColumn");
	}
    
	function hookleftColumn($params)
	{		
		return $this->processHook( $params,"leftColumn");
	}
	
	function hooktop($params){		
		return '</div><div class="clearfix"></div><div>'.$this->processHook( $params,"top");
	}
	
	function hookfooter($params)
	{		
		return $this->processHook( $params,"footer");
	}
	
	function hookcontenttop($params)
	{ 		
		return $this->processHook( $params,"contenttop");
	}
    function hooklofTop($params){
		return $this->processHook( $params,"lofTop");
	}
		
	function hookHome($params)
	{
		return $this->processHook( $params,"home");
	}
	
	
	function hookHeader($params)
	{
		if(_PS_VERSION_ <="1.4"){							
			$header = '
			<link type="text/css" rel="stylesheet" href="'.($this->_path).'tmpl/assets/style.css'.'" />
			<link type="text/css" rel="stylesheet" href="'.($this->_path).'tmpl/'. $this->getParamValue('module_theme','default').'/assets/style.css'.'" />			
            <script type="text/javascript" src="'.($this->_path).'assets/script.js'.'"></script>';			
			return $header;			
		}elseif(_PS_VERSION_ < "1.5"){
		    if( !defined("_LOF_NEW_PRODUCT_") ){
                
				Tools::addJS( ($this->_path).'assets/script.js', 'all');
                define('_LOF_NEW_PRODUCT_', 1);         
            }
            Tools::addCSS( ($this->_path).'tmpl/assets/style.css', 'all');
			Tools::addCSS( ($this->_path).'tmpl/'. $this->getParamValue('module_theme','default').'/assets/style.css', 'all');   
		}else{
		    if( !defined("_LOF_NEW_PRODUCT_") ){                
				$this->context->controller->addJS( ($this->_path).'assets/script.js', 'all');
                define('_LOF_NEW_PRODUCT_', 1);         
            }
            $this->context->controller->addCSS( ($this->_path).'tmpl/assets/style.css', 'all');
			$this->context->controller->addCSS( ($this->_path).'tmpl/'. $this->getParamValue('module_theme','default').'/assets/style.css', 'all');   
		}		
	}
	      
	/**
    * Proccess module by hook
    * $pparams: param of module
    * $pos: position call
    */
	function processHook( $mparams, $pos="home" ){
        global $cookie, $link, $smarty;
       	$id_lang = intval($cookie->id_lang);               
		$site_url = Tools::htmlentitiesutf8('http://'.$_SERVER['HTTP_HOST'].__PS_BASE_URI__);	
        
		// files
		if(_PS_VERSION_ <="1.4"){
			$thumbPath = _PS_IMG_DIR_.$this->name;// create thumbnail folder	 						
			if( !file_exists($thumbPath) ) {
				mkdir( $thumbPath, 0777 );			
			};
			$thumbUrl = $site_url."img/".$this->name;
		}else{			
			$thumbPath = _PS_CACHEFS_DIRECTORY_.$this->name; // create thumbnail folder
			if( !file_exists(_PS_CACHEFS_DIRECTORY_) ) {
				mkdir( _PS_CACHEFS_DIRECTORY_, 0777 );  			
			}; 
			if( !file_exists($thumbPath) ) {
				mkdir( $thumbPath, 0777 );			
			};
			$thumbUrl = $site_url."cache/cachefs/".$this->name;			
		}
		
		if( file_exists( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/group_base.php' ) && !class_exists("LofNewProductDataSourceBase", false) ){
			if( !defined("LOF_NEWPRODUCT_LOAD_LIB_GROUP") ) {
				require_once( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/group_base.php' );
				define("LOF_NEWPRODUCT_LOAD_LIB_GROUP",true);
			}
		}
		if( file_exists( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/phpthumb/ThumbLib.inc.php' ) && !class_exists('PhpThumbFactory', false)){						
			if( !defined("LOF_NEWPRODUCT_LOAD_LIB_PHPTHUMB") ) {
				require( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/phpthumb/ThumbLib.inc.php' );	
				define("LOF_NEWPRODUCT_LOAD_LIB_PHPTHUMB",true);
			}			
		}
		
		//config
		$moduleId = rand().time();
        $params = $this->_params;
		$params->set( 'auto_renderthumb',0);
        $theme = $params->get("module_theme","default");	
		
		$tmp 			= $params->get( 'md_height', 'auto' );
		$moduleHeight   =  'auto';
		$tmp            = $params->get( 'md_width', 'auto' );
		$moduleWidth    =  ( $tmp=='auto') ? 'auto': (int)$tmp;		
		
		$sh = $params->get( 'slide_height', '\'auto\'' );
		$slide_height = ( $sh=='auto' ) ? '\'auto\'' : (int)$sh;
		$sh = $params->get( 'slide_width', '\'auto\'' );
		$slide_width = ( $sh=='auto') ? '\'auto\'': (int)$sh;
		$auto_play = $params->get('auto_play', 1);
		$auto_play = ($auto_play == 1) ? 'true' : 'false';
		$scroll_items = $params->get('scroll_items', '1');
		
		$main_height = $params->get('main_height', '100');
		$main_width = $params->get('main_width', '100');
		$limit_cols = $params->get('limit_cols', '4');
        
		$show_price	= $params->get('show_price',1);
		$priceSpecial   = $params->get('price_special',1);
		$show_desc	= $params->get('show_desc',1);
		
		$show_title	= $params->get('show_title',1);
		$show_image	= $params->get('show_image',1);
		$show_date	= $params->get('show_puplic',1);
		$show_pager	= $params->get('show_pager',1);
		$show_button = $params->get('show_button',1);
		
		$source = 'product';        
		$path = dirname(__FILE__).'/libs/groups/'.strtolower($source).'/product.php';
		if( !file_exists($path) ){
			return array();	
		}
		require_once $path;
		$objectName = "LofNew".ucfirst($source)."DataSource";
        $object = new $objectName();
        $object->setThumbPathInfo($thumbPath,$thumbUrl)
               ->setImagesRendered( array( 'mainImage' => array( (int)$params->get( 'main_width', 150 ), (int)$params->get( 'main_height', 100 )) ) );
		
		$listNews = $object->getListFeatured( $params );
		//echo "<pre>"; print_r($listNews); die;
        //assign params
        $smarty->assign( array(
								'moduleId' 		=> $moduleId,
								'site_url'      => $site_url,
								'theme'	        => $theme,
								'moduleHeight'  => $moduleHeight,
								'moduleWidth'   => $moduleWidth,
								'slide_width'	=> $slide_width,
								'auto_play' 	=> $auto_play,
								'scroll_items'	=> $scroll_items,
								'main_height' 	=> $main_height,
								'main_width'	=> $main_width,
								'limit_cols' 	=> $limit_cols,
							  
								'show_price'	=> $show_price,
								'priceSpecial'  => $priceSpecial,
								'show_desc'		=> $show_desc,
								'show_title'	=> $show_title,
								'show_image'	=> $show_image,
								'show_date'		=> $show_date,
								'show_pager'	=> $show_pager,
								'show_button'	=> $show_button,
							  
								'listNews'		=> $listNews,
                        ));
        //assign layout
        $layout = $this->getLayoutPath("default");  
        return $this->display(__FILE__, $layout ); 				
	}
	
    public function getLayoutPath( $theme="default" ){
        $layout = 'tmpl/'.$theme.'/default.tpl';
        return $layout;
    }
    
    public function splitingCols ( $products ){
        return $output; 
    }  
    
     	   	
   /**
    * Get list of sub folder's name 
    */
	public function getFolderList( $path ) {
		$items = array();
		$handle = opendir($path);
		if (! $handle) {
			return $items;
		}
		while (false !== ($file = readdir($handle))) {
			if (is_dir($path . $file))
				$items[$file] = $file;
		}
		unset($items['.'], $items['..'], $items['.svn']);
		
		return $items;
	}
	
   /**
    * Render processing form && process saving data.
    */	
	public function getContent()
	{
		$html = "";
		if (Tools::isSubmit('submit'))
		{
			$this->_postValidation();

			if (!sizeof($this->_postErrors))
			{													
		        $definedConfigs = array(
		          /* general config */
		          'module_theme'      => '',
                  //image group
                  'module_group'      => '',
                  'image_folder'      => '',
                  'image_category'    => '',
                  'image_ordering'    => '',
                  'online_icon'       => '',
                  'feature_icon'      => '',
                  'new_icon'          => '',
                  'sale_icon'         => '',
                  'price_special'     => '',
                                                      
                  //product group
		          'home_sorce'        => '',
                  'product_ids'       => '',
                  
                  'featured_tab'      => '',
		          'show_tips'        => '',
		          'timenew'        => '',
                  'order_by'          => '',  
                  'limit_cols'          => '',  
                  'limit_rows'          => '',  
                  'des_max_chars'     => '',                  
	              'productids'        => '',                  		          		          		                            		        
	              'pos_act'        => '',                  		          		          		                            		        
	              'show_box_tips'        => '',                  		          		          		                            		        
		          'read_text'            => 'readmore',
		          'speed'       => '200',
		          'md_height'     => '',
		          'md_width'      => '',
				  'slide_height'	=> '',
				  'slide_width'		=> '',
				  'delCaImg'	      => '',
				  'limit_items'       =>'',
                  'scroll_items'       =>'',
		          /*Main CoinSlider Setting*/
                  'show_tooltip'           => '',
                  'show_button'           => '',
				  'show_pager' => '',
				  //'controls_btn_show'     => '',
                  
                  'show_image'            => '',
                  'show_desc'        => '',                                  		                            		          
		          'cre_main_size'     => '',
		          'main_img_size'     => '',
		          'main_height'       => '100',
		          'main_width'        => '150',
                  'thumb_height'       => '',
		          'thumb_width'        => '',
				  'auto_play' =>'',
		          /*Navigator Setting */
		          'show_price'     => '',
		          'show_title'     => '',
		          'show_puplic'=> '',
		          'mer_cat'=> '',
		          /*Effect Setting*/
		          'event'           => '',
		          'layout_style'      => '',
		          'spacing'          => '',
		          'duration'          => '',
		          'lofeffect'            => '',
                  'min_width_expanded'         => '',                  
		          'max_width_expanded'        => '',
		          'target'       =>'',
				  /*Customize Style*/
		          'enable_caption'    => '',
		          'caption_bg'        => '',
                  'caption_opacity'   => '',                  
                  'caption_fontcolor' => '',
                  'caption_linkcolor' => '',
                  'price_color'       => '',
                  'show_price'        => ''   , 
				  'file_path' => ''
		        );
				 for($i=1; $i<=10; $i++){
                    $definedConfigs[$i."-enable"]    = "";
                    if(Tools::getValue($i."-enable")){
                        $definedConfigs[$i."-filetype"]  = "";                                        
                        $definedConfigs[$i."-path"]      = "";
                        $definedConfigs[$i."-link"]      = "";                                                                            
                        $definedConfigs[$i."-timer"]     = "";
                        $definedConfigs[$i."-target"]    = "";
                        $definedConfigs[$i."-imagePos"]  = "";
                        $definedConfigs[$i."-pan"]       = "";
                        $definedConfigs[$i."-desc"]      = "";
                        $definedConfigs[$i."-title"]     = ""; 
                        $definedConfigs[$i."-preview"]   = "";
                        $definedConfigs[$i."-pan"]       = "";
                        $definedConfigs[$i."-imagePos"]  = "";
                        $definedConfigs[$i."-timer"]     = "";
                    }                                                          
                }
				
		        foreach( $definedConfigs as $config => $key ){
	 
		      		Configuration::updateValue($this->name.'_'.$config, Tools::getValue($config), true);
		    	}
                
                //echo "<pre>";print_r(Tools::getValue("home_sorce")); die;
                //$params->set( 'custom_id_parent', $ids );
                if(Tools::getValue('category')){
    		        if(in_array("",Tools::getValue('category'))){
    		          $catList = "";
    		        }else{
    		          $catList = implode(",",Tools::getValue('category'));  
    		        }
                    Configuration::updateValue($this->name.'_category', $catList, true);
                }
				//manu tab
				if(Tools::getValue('manu')){  		        
    		        $catList = implode(",",Tools::getValue('manu'));    		        
                    Configuration::updateValue($this->name.'_manu', $catList, true);
                }
                $linkArray = Tools::getValue('override_links');
                if($linkArray){
                    foreach ($linkArray as $key => $value) {
                        if (is_null($value) || $value == "") {
                            unset ($linkArray[$key]);
                        }
                    }
                    $override_links = implode(",",$linkArray);
                    Configuration::updateValue($this->name.'_override_links', $override_links, true);
                }
				$delText = '';	
		        if(Tools::getValue('delCaImg')){					
					if(_PS_VERSION_ <="1.4"){						
						$cacheFol = _PS_IMG_DIR_.$this->name;												
					}else{			
						$cacheFol = _PS_CACHEFS_DIRECTORY_.$this->name;							
					}					
					if( file_exists( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/group_base.php' ) && !class_exists("LofNewProductDataSourceBase", false) ){
						if( !defined("LOF_LOAD_LIB_GROUP") ) {
							require_once( _PS_ROOT_DIR_.'/modules/'.$this->name.'/libs/group_base.php' );
							define("LOF_LOAD_LIB_GROUP",true);
						}
					}
					if (LofDataSourceBase::removedir($cacheFol)){
						$delText =  $this->l('. Cache folder has been deleted');
					}else{
						$delText =  $this->l('. Cache folder can\'tdeleted');
					}  
				}
		        $html .= '<div class="conf confirm">'.$this->l('Settings updated').$delText.'</div>';
			}
			else
			{
				foreach ($this->_postErrors AS $err)
				{
					$html .= '<div class="alert error">'.$err.'</div>';
				}
			}
			// reset current values.
			$this->_params = new LofParams( $this->name );	
		}
			
		return $html.$this->_getFormConfig();
	}
	
	/**
	 * Render Configuration From for user making settings.
	 *
	 * @return context
	 */
	private function _getFormConfig(){		
		$html = '';
		 
	    $formats = ImageType::getImagesTypes( 'products' );
	    $themes=$this->getFolderList( dirname(__FILE__)."/tmpl/" );
        $groups=$this->getFolderList( dirname(__FILE__)."/libs/groups/" );

	    ob_start();
	    include_once dirname(__FILE__).'/config/lofnewproduct.php'; 
	    $html .= ob_get_contents();
	    ob_end_clean(); 
		return $html;
	}
    
	/**
     * Process vadiation before saving data 
     */
	private function _postValidation()
	{
		if (!Validate::isCleanHtml(Tools::getValue('module_height')))
			$this->_postErrors[] = $this->l('The module height you entered was not allowed, sorry');
		if (!Validate::isCleanHtml(Tools::getValue('module_width')))
			$this->_postErrors[] = $this->l('The module width you entered was not allowed, sorry');
		if (!Validate::isCleanHtml(Tools::getValue('des_max_chars')) || !is_numeric(Tools::getValue('des_max_chars')))
			$this->_postErrors[] = $this->l('The description max chars you entered was not allowed, sorry');
		
		if (!Validate::isCleanHtml(Tools::getValue('main_height')) || !is_numeric(Tools::getValue('main_height')))
			$this->_postErrors[] = $this->l('The Main Image Height you entered was not allowed, sorry');
		if (!Validate::isCleanHtml(Tools::getValue('main_width')) || !is_numeric(Tools::getValue('main_width')))
			$this->_postErrors[] = $this->l('The Main Image Width you entered was not allowed, sorry');
 
                      							
	}
	
	public function getProFeature(){
		$sql = 'SELECT DISTINCT p.id_product FROM `'._DB_PREFIX_.'category_product` cp '
		 . 'LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product` '
		 . 'WHERE cp.`id_category` =1';    
		return Db::getInstance()->ExecuteS($sql);
	} 	 
        
	
   /**
    * Get value of parameter following to its name.
    * 
	* @return string is value of parameter.
	*/
	public function getParamValue($name, $default=''){
		return $this->_params->get( $name, $default );	
	}	  	  		
} 