<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  31/03/11, 20:12
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @Class listing

  charge les modules actifs
*/

class listing{

  //! @p object
  protected static $_instance;

  public static $modules;
  /**
    @p object
  */
  private static $pdm;

  /**
  */
  protected function __construct($full) {
    global $languages_id;
//     contentData::start();
    if($full) self::start_module();
  }

  protected static function start_module(){
    self::$pdm=listingModule::getInstance();
    self::$modules=self::$pdm->ret_modules();
  }

  public static function getInstance($full=false) {
    if(self::$_instance == null) self::$_instance = new self($full);
    return self::$_instance;
  }

  public static function resetInstance(){
    self::$_instance = null;
    return self::getInstance();
  }


  /**
     méthode magique
  */
  public function __call($methode, $args){

    $arguement= (count($args)>1) ?  implode(', ',$args) : @$args[0];

    //! test for class listingModule
    if(method_exists(self::$pdm,$methode) ) return self::$pdm->$methode($arguement);
    elseif(method_exists('listingModule',$methode) ) return @listingModule::$methode($arguement);

    //! test for class listingUtility
   if(method_exists('listingUtility',$methode) ) return call_user_func_array(array('listingUtility',$methode), $args);

    //! test for class listingData
   if(method_exists('listingData',$methode) ) return call_user_func_array(array('listingData',$methode), $args);


  }


  /**
    Module configuration
  */
  public function ret_modules(){ self::start_module(); return self::$modules;}



}

/**
   Gestion de la production des listing
*/
class listingData{

  public static $type_object='products';

  /**
    @p string requet sql
  */
  public static $listing_sql;
  /**
    @p string force orderby
  */
  public static $sql_sort='';
  /**
    @p string limit
  */
  public static $limit='';

  private static $category_id=false;

  static public function _reset(){
    self::$limit='';
    self::$category_id=false;
    self::$sql_sort='';
  }

  static public function listing($type_object,$category_depth){
    global $page;

    if($category_depth=='nested')self::$type_object= 'nested';
    elseif((isset($type_object) && $type_object=='products') || $category_depth=='products') self::$type_object= 'products';
    elseif((isset($type_object) && $type_object=='pages') || $category_depth=='pages') self::$type_object= 'pages';


    $listing_sql=self::query();

    $listing_sql .=self::Exeorderby().self::$limit;

    if( empty(self::$limit) ) {
      if(!class_exists('splitPageResults')) require_once(DIR_WS_CLASSES . 'split_page_results.php');
      if( self::$type_object =='products' || isset($_GET['manufacturers_id']))
	$listing_split = new splitPageResults($listing_sql,  $page->_conf_value('MAX_DISPLAY_PAGE_LINKS'), 'p.products_id');
      elseif( self::$type_object =='pages')
	$listing_split = new splitPageResults($listing_sql,  $page->_conf_value('MAX_DISPLAY_PAGE_LINKS'));
      elseif( self::$type_object =='nested')
	$listing_split = new splitPageResults($listing_sql,  $page->_conf_value('MAX_DISPLAY_PAGE_LINKS'), 'p.products_id');

      return $listing_split;
    }
    else
      return $listing_sql;


  }

  static private function query(){
    global $languages_id, $current_category_id;

    //! cat courante
    $cID=(self::$category_id ===false)? $current_category_id : self::$category_id;

    //! We show them all and all type (page, products,link )
    switch (self::$type_object){
      case 'products':
	$listing_sql = " select DISTINCT p.*, pd.products_name from  ".TABLE_V_PRODUCTS." p
			  LEFT JOIN  " . TABLE_PRODUCTS_DESCRIPTION . " pd on pd.products_id = p.products_id
			  LEFT JOIN   " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c on p2c.products_id= p.products_id
			  WHERE pd.language_id = '" . (int)$languages_id . "'  ";

	if (isset($_GET['manufacturers_id']) && isset($_GET['filter_id']) && tep_not_null($_GET['filter_id']))
	  $listing_sql .=" and manufacturers_id = '" . (int)$_GET['manufacturers_id'] . "' and p2c.categories_id = '" . (int)$_GET['filter_id'] . "' ";
	elseif (isset($_GET['filter_id']) && tep_not_null($_GET['filter_id']))
	  $listing_sql .=" and manufacturers_id = '" . (int)$_GET['filter_id'] . "'";
	elseif (isset($_GET['manufacturers_id']))
	  $listing_sql .=" and manufacturers_id = '" . (int)$_GET['manufacturers_id'] . "'";
	elseif (!empty($cID))
	  $listing_sql .=" and p2c.categories_id = '" . (int)$cID . "'";


      break;

      case 'pages':

	$listing_sql = "select DISTINCT c.content_id,ctc.categories_id, content_name,content_title,content_text, c.date_added, c.last_modified, content_status, ctc.categories_id    from " . TABLE_CONTENT_DESCRIPTION . " cd, " . TABLE_CONTENT . " c,   " . TABLE_CONTENT_TO_CATEGORIES . " ctc, " . TABLE_CATEGORIES . " cat where cat.categories_id=ctc.categories_id and cat.categories_status='1' and c.content_status = '1' and c.content_id = ctc.content_id and cd.content_id = ctc.content_id and cd.language_id = '" . (int)$languages_id . "' and cat.categories_id = '" . (int)$cID . "'";
      break;

      case 'nested':
	global $list;

	$listing_sql = "select DISTINCT p.*, pd.products_name from ".TABLE_V_PRODUCTS." p, " . TABLE_PRODUCTS_DESCRIPTION . " pd,  " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_CATEGORIES . " c WHERE  c.categories_id=p2c.categories_id and c.categories_status='1' AND  pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "' and p.products_id = p2c.products_id ".(tep_not_null($list)? " AND  p2c.categories_id IN (" . $list . ")" : '');

	self::orderby('c.sort_order ');
      break;
    }

    return $listing_sql;
  }


  static private function Exeorderby($sql_sort=''){
    $listing_sql = ' order by ';

    $sort=listingUtility::sortby(@$_GET['sort']);
    $listing_sql .= ((strlen(self::$sql_sort)>0 && strlen($sort)>0)? self::$sql_sort.',': self::$sql_sort);
    $listing_sql .= $sort;
    return $listing_sql;
  }


  /**
    Add condition order by
  */
  public static function orderby($_sort){
    self::$sql_sort=((strlen(self::$sql_sort)>0)?',':'').$_sort ;
  }

  /**
    Add condition limit
  */
  public static function limit($limit){
    self::$limit=$limit ;
  }

  /**
    Add Force current_category_id
  */
  public static function currentCatId($cID){
    self::$category_id=(int)$cID ;
  }

}




class listingUtility{

  public static $column_list=array( 'PRODUCT_LIST_MODEL' ,
				    'PRODUCT_LIST_NAME' ,
				    'PRODUCT_LIST_MANUFACTURER' ,
				    'PRODUCT_LIST_PRICE' ,
				    'PRODUCT_LIST_QUANTITY' ,
				    'PRODUCT_LIST_WEIGHT' ,
				    'PRODUCT_LIST_IMAGE',
				    'PRODUCT_LIST_BUY_NOW' );


  static public function sortby($GETsort){
    global $categories;
    $listing_sql = '';
/*    if ( (!isset($GETsort)) && (!preg_match('/[1-8][ad]/', $GETsort)) && (substr($GETsort, 0, 1) > sizeof(self::$column_list)) ) {
      for ($i=0, $n=sizeof(self::$column_list); $i<$n; $i++) {
	if (self::$column_list[$i] == 'PRODUCT_LIST_NAME') {
	  $GETsort = $i+1 . 'a';
	  if(!isset($_GET['type_object']) || $_GET['type_object']=='products') return $listing_sql.=" p2c.categories_id,pd.products_name";
	}
      }
    }
    else*/if ( isset($GETsort)) {
      $sort_col = substr($GETsort, 0 , 1);
      $sort_order = substr($GETsort, 1);

	switch (self::$column_list[$sort_col-1]) {
	  case 'PRODUCT_LIST_MODEL':  $listing_sql.="p.products_model " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name"; break;
	  case 'PRODUCT_LIST_NAME':  $listing_sql.="pd.products_name " . ($sort_order == 'd' ? 'desc' : ''); break;
	  case 'PRODUCT_LIST_MANUFACTURER':   $listing_sql.="m.manufacturers_name " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name"; break;
	  case 'PRODUCT_LIST_QUANTITY':   $listing_sql.="p.products_quantity " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name"; break;
	  case 'PRODUCT_LIST_IMAGE':   $listing_sql.="pd.products_name"; break;
	  case 'PRODUCT_LIST_WEIGHT':  $listing_sql.="p.products_weight " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name"; break;
	  case 'PRODUCT_LIST_PRICE':  $listing_sql.="final_price " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name"; break;
	}
    }
    /**
      @brief Tri par default, option des categorie Champs sortchids_products & sortchids_content
    */
    elseif(isset($categories->sortchids_products) || isset($categories->sortchids_content)){
      if(tep_not_null($categories->sortchids_products) && ( listingData::$type_object=='products' || listingData::$type_object=='nested' ) ) $listing_sql .= $categories->sortchids_products.", pd.products_name";
      elseif( tep_not_null($categories->sortchids_content) && listingData::$type_object=='pages' )  $listing_sql .= $categories->sortchids_content;
    }


    /**
      Tri si aucun tri deja effectué
    */
    if(empty($listing_sql)){
      if( listingData::$type_object=='products' ) $listing_sql .=  'pd.products_name';
      elseif( listingData::$type_object=='pages' )  $listing_sql .=  'content_name';
    }


    return $listing_sql;
  }


  static public function menuSortBy($name='sort',$id,$selected='', $parameters=''){

    $cpt=0;
    $_array=array();
    foreach(self::$column_list as $it) {
      $cpt++;
      $_array[]=array('id'=>$cpt, 'text'=>str_replace('_LIST','',$it));
    }
    return tep_draw_pull_down_menu($name,$id, $_array, $selected, $parameters);
  }

}


/**
  Support des class ACA
*/

class listingModule
  extends AbstractAcaModule
    implements InterfaceAcaGene{

  protected static $_instance;

  /**
  */
  protected function __construct() {
    global $language, $page;
    $this-> name='listing';
    $this->modules=array();

    foreach(parent::initialise_type('MODULE_LISTING_INSTALLED','listing') as $class){
      $cl[$class]=new $class ();
      $list_mod[$class] = $cl[$class]->sort_order;
      asort($list_mod);
      foreach($list_mod as $class=>$s){
	$this->modules[$class] =$cl[$class];
      }
      unset($cl);unset($list_mod);
    }
  }

  public static function getInstance() {
    if(self::$_instance == null) self::$_instance = new self();
    return self::$_instance;
  }

  public static function resetInstance(){
    self::$_instance = null;
    return self::getInstance();
  }

  public function display_view($ID,$class=''){return array();}

  /**
    Affiche module display_view mini

    @param
      @a int  cID le Id du customers
      @a string class le nom de la class appelé, ou vide pour toutes les class enfants
  */
  public function display_view_min($cID,$class=''){
    global  $page;
    if (!empty($class)) {
      if (isset($this->modules[$class]) && $this->modules[$class]->enabled and (method_exists($module, 'display_view_min' ))){
        $this->modules[$class]->load_db_values($cID);
        return $this->modules[$class]->display_view_min($cID);
      }
    } else {
       $c='';
      foreach ($this->modules as $key=>$module) {
        if (($module->enabled)  and (method_exists($module, 'display_view_min' ))) {
          $this->modules[$key]->load_db_values($cID);
          $c .=$this->modules[$key]->display_view_min($cID);
        }
      }
      return $c;
    }
  }


  /**
    return_db_min module display_view mini

    @param
      @a int  cID le Id du customers
      @a string class le nom de la class appelé, ou vide pour toutes les class enfants
  */
  public function return_db_min($cID,$class=''){
    global  $page;
    if (!empty($class)) {
      if (isset($this->modules[$class]) && $this->modules[$class]->enabled and (method_exists($module, 'return_db_min' ))){
        $this->modules[$class]->load_db_values($cID);
        return $this->modules[$class]->return_db_min($cID);
      }
    } else {
       $c=array();
      foreach ($this->modules as $key=>$module) {
        if (($module->enabled)  and (method_exists($module, 'return_db_min' ))) {
          $this->modules[$key]->load_db_values($cID);
          $c[$key]=$this->modules[$key]->return_db_min($cID);
        }
      }
      return $c;
    }
  }

}
?>