<?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  15/05/11, 19:25
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class attributes
*/

class attributes
  implements ExtModPage, InterfaceModule, InterfacedTJsonS,InterfacedInnerHtml {

  const FILENAME =FILENAME_ATTRIBUTES;

  public static $code;

  public static $action;
  /**
    @p string type value (options|values)
  */
  public static $type='options';

  public static $list=array();

  public static $languages;

  public static $poIDInfo;

  /**
    @p int Option Id
  */
  public static $poID;
  public static $povID;

  public static $products_options_images_enabled;
  public static $products_options_track_stock;
  public static $products_options_condition;

  /**
    class constructor
  */
  public function __construct() {
    self::GetConf();
  }

  /**
    @brief Load , adjust and define var environement exe for module
	Is use in module and class abstract for init value config this module
  */
  public static function GetConf(){
    global $languages_id;

    self::$code=__CLASS__;

    self::$action=(isset($_REQUEST['action'])? $_REQUEST['action'] : 'listing' );
    self::$type=(isset($_GET['type'])? $_GET['type']: 'options');

    /**
      @remarks not load if not first init
    */
    if(defined('JSONSTATMENT')) return;

    //! active datatable in ajax, precise les GET necessaire
    define('JSONSTATMENT', 'mod=page&type='.self::$code);
    //! detail item in ajax
    define('AJAXSTATMENTDETAIL', 'mod=page&type='.self::$code);


    self::$languages = tep_get_languages();

    self::$products_options_images_enabled=array(
      array('id'=>0,'text'=>__('text opt img enable n')),
      array('id'=>1,'text'=>__('text opt img enable y'))
    );
    self::$products_options_track_stock=array(
      array('id'=>0,'text'=>__('text opt stock n')),
      array('id'=>1,'text'=>__('text opt stock y'))
    );
    self::$products_options_condition=array(
      array('id'=>0,'text'=>__('text opt mode n')),
      array('id'=>1,'text'=>__('text opt mode y'))
    );
  }

  public function check_action($actions){
    global $messageStack;


    self::$action=$actions;

    switch (self::$action) {
      case 'setsort';
      case 'setimg';
      case 'setstock';
      case 'setcond';
	attr__UpExe_SetOption(self::$action,$_GET['flag'],tep_db_prepare_input($_GET['poID']));
	tep_redirect(tep_href_link(self::FILENAME));
      break;
      case 'delete':
	if(self::$type=='options') {
	}
	elseif(self::$type=='values') {

	}
      break;
      case 'insert':
      case 'update':
	//! option
	if(self::$type=='options') {
	  $poID=(self::$action=='insert')
		  ? self::getNextAutoValue(TABLE_PRODUCTS_OPTIONS,'products_options_id')
		  : tep_db_prepare_input($_GET['poID']) ;

	  $sql_data_array['products_options_condition']=  (int)tep_db_prepare_input($_POST['products_options_condition']);
	  $sql_data_array['products_options_sort_order']=  tep_db_prepare_input($_POST['products_options_sort_order']);
	  $sql_data_array['products_options_track_stock']=  (int)tep_db_prepare_input($_POST['products_options_track_stock']);
	  $sql_data_array['products_options_images_enabled']=  (int)tep_db_prepare_input($_POST['products_options_images_enabled']);
	  $sql_data_array['products_options_type']=  tep_db_prepare_input($_POST['products_options_type']);
	  $sql_data_array['products_options_length']=  tep_db_prepare_input($_POST['products_options_length']);


	  for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {
	    $sql_data_array['products_options_name']= $_POST['products_options_name'][self::$languages[$i]['id']];
	    $sql_data_array['products_options_comment']=  $_POST['products_options_comment'][self::$languages[$i]['id']];

	    if(self::$action=='insert'){
	      $sql_data_array['products_options_id']=  $poID;
	      tep_db_perform(TABLE_PRODUCTS_OPTIONS, $sql_data_array);
	    }
	    else tep_db_perform(TABLE_PRODUCTS_OPTIONS, $sql_data_array, 'update', ' language_id = \''.(int)self::$languages[$i]['id'].'\' and products_options_id=\''.$poID.'\'');
	  }

	  tep_redirect(tep_href_link(self::FILENAME));
	}
	//! valeur d'option
	elseif(self::$type=='values') {

	  $poID=(isset($_GET['poID'])? (int)tep_db_prepare_input($_GET['poID']): '');

	  //! insert option value
	  $povID=(self::$action=='insert')
		  ? self::getNextAutoValue(TABLE_PRODUCTS_OPTIONS_VALUES,'products_options_values_id')
		  : tep_db_prepare_input($_GET['povID']) ;

	  for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {
	    $sql_data_array['products_options_values_name']= $_POST['products_options_values_name'][self::$languages[$i]['id']];
	    $sql_data_array['products_options_values_thumbnail']= $_POST['products_options_values_thumbnail'][self::$languages[$i]['id']];
	    if(self::$action=='insert') {
	      $sql_data_array['products_options_values_id']= $povID;
	      $sql_data_array['language_id']= self::$languages[$i]['id'];
	      $res=tep_db_perform(TABLE_PRODUCTS_OPTIONS_VALUES, $sql_data_array);
	    }
	    else{
	      tep_db_perform(TABLE_PRODUCTS_OPTIONS_VALUES, $sql_data_array, 'update', ' language_id = \''.(int)self::$languages[$i]['id'].'\' and products_options_values_id=\''.$povID.'\'');
	    }
	  }

	  //! liaison value avec option
	  if(self::$action=='insert') {
	    $sql_data_array=array();
	    $sql_data_array['products_options_id']= $poID;
	    $sql_data_array['products_options_values_id']= $povID;
	    tep_db_perform(TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS, $sql_data_array);
	  }

	  tep_redirect(tep_href_link(self::FILENAME));
	}

      break;

      case 'new':
	$res=array();
	for ($i=0, $n=sizeof(self::$languages); $i<$n; $i++) {
	  $res['products_options_values_name'][self::$languages[$i]['id']] = "";
	  $res['products_options_values_thumbnail'][self::$languages[$i]['id']] = "";
	}
	self::$poIDInfo= new objectInfo($res);
      break;
    }

    return self::$action;
  }

  public function get_header(){
  }


  /**
  */
  public static function load_db_values($ID){

    $DB=Database::getInstance();
    switch (self::$type) {

      //! recup list valeur pour une option
      case 'values_for_option':
	//! recup toutes les langues
	$values = "select * from " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov  LEFT JOIN " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " pov2po on(pov.products_options_values_id)   where pov2po.products_options_id='".$ID."'  ";
	$res=$DB->query($values);

	while ($result=$res->fetchAssoc()){
	  $final['products_options_value_name'][$result['language_id']]=$result['products_options_value_name'];
	  $final['products_options_values_thumbnail'][$result['language_id']]=$result['products_options_values_thumbnail'];
	}
	self::$poIDInfo = ((isset($final) && is_array($final))? new objectInfo($final): new objectInfo($reinit) );
      break;

      //! recup detail une valeur
      case 'values':
	//! recup toutes les langues
	$values = "select * from " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov  LEFT JOIN " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " pov2po on(pov.products_options_values_id)   where pov.products_options_values_id='".$ID."'  ";
	$res=$DB->query($values);

	while ($result=$res->fetchAssoc()){
	  $final['products_options_values_id']=$result['products_options_values_id'];
	  $final['products_options_values_name'][$result['language_id']]=$result['products_options_values_name'];
	  $final['products_options_values_thumbnail'][$result['language_id']]=$result['products_options_values_thumbnail'];
	}
	self::$poIDInfo = ((isset($final) && is_array($final))? new objectInfo($final): new objectInfo($reinit) );
      break;

      //! recup une option
      case 'options':
      default:
	if(tep_not_null($ID)){
	  $options = "select * from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id='".$ID."'  ";
	  $res=$DB->query($options);

	  while ($result=$res->fetchAssoc()){
	    $final['products_options_id']= $result['products_options_id'];
	    $final['products_options_condition']=  $result['products_options_condition'];
	    $final['products_options_sort_order']=  $result['products_options_sort_order'];
	    $final['products_options_track_stock']=  $result['products_options_track_stock'];
	    $final['products_options_images_enabled']=  $result['products_options_images_enabled'];
	    $final['products_options_type']=  $result['products_options_type'];
	    $final['products_options_length']=  $result['products_options_length'];
	    $final['products_options_name'][$result['language_id']]=$result['products_options_name'];
	    $final['products_options_comment'][$result['language_id']]=$result['products_options_comment'];

	  }
	}
	self::$poIDInfo = ((isset($final) && is_array($final))? new objectInfo($final): new objectInfo($reinit) );
    }
  }

  public function display_view(){
    $action=self::$action;

    switch (self::$action) {
      case 'edit':
	self::$poID=(int)$_GET['poID'];
	if(self::$type=='options') self::load_db_values(self::$poID);
	else{
	  self::$povID=(int)$_GET['povID'];
	  self::load_db_values(self::$povID);
	}
      case 'new':
	$action='edit';
      break;
      case 'delete_confirm':
	self::$poID=(int)$_GET['poID'];
	if(self::$type=='options') self::load_db_values(self::$poID);
	else{
	  self::$povID=(int)$_GET['povID'];
	  self::getProductforOptionValue(self::$povID);
	}
	$action='delete';
      break;
      default:
	self::tep_get_list();
	$action='listing';
    }
    /// use master gabarit
    return MGabCont::CallGab(self::$type.'.'.$action,__FUNCTION__,__CLASS__);
  }


  public static function get_right_bar(){
    global $attributes;
    $heading = array();
    $contents = array();

    if(isset($_GET['cID']))  $cInfo=self::load_db_values($_GET['cID']);

    switch (self::$action) {
    }

    if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
      $box = new box;
      echo $box->infoBox($heading, $contents);

    }
  }


  /** public static InterfacedTJsonS */

  private static function get_item_action($item){
    return '<span class="view fils fleft">'.
// 	      '<a class="button" href="' . tep_href_link(attributes::FILENAME,'poID='.$item['products_options_id'].'&amp;action=list_option'  ) . '">'.__('image list').'</a>'.
	      '<a class="buttonimg" href="' . tep_href_link(attributes::FILENAME,'poID='.$item['products_options_id'].'&amp;action=edit'  ) . '">'.tep_image(DIR_WS_ICONS . 'icon_edit.png', IMAGE_EDIT).'</a>'.
            '</span>';
  }

  //! flag optionnel
  private static function get_item_optionnel($item){
    if ($item['products_options_condition'] == '1') {
      return tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . ' <a href="' . tep_href_link(attributes::FILENAME ,'action=setcond&amp;flag=0&amp;poID=' . $item['products_options_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    } else {
      return '<a href="' . tep_href_link(attributes::FILENAME ,'action=setcond&amp;flag=1&amp;poID=' . $item['products_options_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a> ' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED);
    }
  }
  //! flag track stock
  private static function get_item_stock($item){
    if ($item['products_options_track_stock'] == '1') {
      return tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . ' <a href="' . tep_href_link(attributes::FILENAME,'action=setstock&amp;flag=0&amp;poID=' . $item['products_options_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    } else {
      return '<a href="' . tep_href_link(attributes::FILENAME,  'action=setstock&amp;flag=1&amp;poID=' . $item['products_options_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a>&nbsp;' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED);
    }
  }
  //! flag image
  private static function get_item_images($item){
    if ($item['products_options_images_enabled'] == '1') {
      return tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . ' <a href="' . tep_href_link(attributes::FILENAME, 'action=setimg&amp;flag=0&amp;poID=' . $item['products_options_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    } else {
      return '<a href="' . tep_href_link(attributes::FILENAME, 'action=setimg&amp;flag=1&amp;poID=' . $item['products_options_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a> ' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED);
    }
  }

  private static function emptyResult(){
    return array( 'null',
		  'products_options_id',
                  'products_options_name',
                  'products_options_condition',
		  'products_options_type',
                  'products_options_length',
                  'products_options_comment',
                  'products_options_track_stock',
                  'products_options_sort_order',
                  'products_options_images_enabled',
		  'action'
                );
  }

  public static function tep_get_modele(){
    return array( 0 =>false,
		  'products_options_id'=>true,
                  'products_options_name'=>true,
                  'products_options_condition'=>true,
		  'products_options_type'=>true,
                  'products_options_length'=>true,
                  'products_options_comment'=>true,
                  'products_options_track_stock'=>true,
                  'products_options_sort_order'=>true,
                  'products_options_images_enabled'=>true,
		  'action'=>false
                );
  }

  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows,$languages_id;

    $DB=Database::getInstance();

    $query_raw = "select * from " . TABLE_PRODUCTS_OPTIONS . " where language_id = '" . (int)$languages_id . "' order by products_options_sort_order DESC, products_options_name ASC";
    $split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);

    $query = $DB->query($query_raw);

    while ($row = $query->fetchAssoc() ) {
      $row['products_options_type']=translate_type_to_name($row['products_options_type']);
      $row[0]=$row['products_options_id'];
      $row['products_options_condition']=self::get_item_optionnel($row);
      $row['products_options_track_stock']=self::get_item_stock($row);
      $row['products_options_images_enabled']=self::get_item_images($row);
      $row['action']=self::get_item_action($row);
      self::$list[]=$row;
    }

    $li=$res=array();

    foreach(self::$list as $item){
      foreach(self::tep_get_modele() as $k=>$v) $li[$k]=(tep_not_null($item[$k]))?$item[$k]:'&nbsp;';
      $res[]=$li;
    }

    if(count($res)==0) $res[]= self::emptyResult();
    return $res;
  }


 /** static InterfacedInnerHtml */

  public static function detail_row_page($id){
//     self::init();
    self::$poID=(int)$id;
    self::$type='values_for_option';
    self::load_db_values((int)$id);
    return tep_get_include_contents(__CLASS__.'.options.inline');
  }



/** Interface module */

  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }

/** private specific module */
  /**
  * Returns placebo autoincrement value
  * @access public
  * @param $strTable string table name
  * @param $strField string field name
  * @return mixed
  */
  private static function getNextAutoValue($strTable,$strField) {
    $db=Database::getInstance();
    $objres=$db->query("select max($strField) + 1 as next from $strTable limit 1");
    $res=$objres->fetchAssoc();
    return (int)$res['next']; //amDB::getOne("select max($strField) + 1 as next from $strTable limit 1");
  }

  /**
    Fournis la liste des produits utilisant cette valeurs d'option
  */
  private static function getProductforOptionValue($povid){

    $DB=Database::getInstance();

    $query_raw = "SELECT p.* FROM " . TABLE_PRODUCTS . " p ," . TABLE_PRODUCTS_ATTRIBUTES . " pa  WHERE p.products_id=pa.products_id AND options_values_id = '".$povid."' ";
    $query = $DB->query($query_raw);

    while ($row = $query->fetchAssoc() ) {
      self::$list[]=$row;
    }
  }
}

?>