<?php
/**
  @licence GPL 2005-2010  The osCSS developers - osCSS Open Source E-commerce
  @package oscss-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  18/12/10, 13:08
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class cfg_30
  @brief Manage All status in table status, for all status type
*/


Class cfg_30 /*implements ext_configuration*/{

  /**
    @var array liste des type de status dispo
  */
  public static $list_types;
  /**
    @var array list status en cours
  */
  public static $list;
  /**
    @var array list type avec option suppl
  */
  public static $type_advanced;
  /**
    @var object
  */
  public static $oInfo;
  /**
    @var string recup GET action
  */
  public static $action;
  /**
    @var Array private
      default_id
      default_completed
      default_annulate
  */
  public static $config;

  /**
  */
  protected static $remove_status;

  /**
  */
  function __construct(){
    $this->code='cfg_30';
    global $messageStack, $language, $oscss;

    $oscss->pile_file_lang(DIR_FS_ADMIN.DIR_WS_LANGUAGES.$language.'/modules/configuration/'.$this->code.'.txt');

    self::$oInfo=array();

    //! Type
    self::$config=$this->config( (isset($_GET['type'])? $_GET['type'] : 'orders' ) );


    self::$list_types=$this->load_db_type('');
    // Title
//     $this->titleh3=__('Edition de status',__CLASS__);

    //! les type ayant besoin de constante de config complementaire
    self::$type_advanced=array('orders','returns');


  }

/** PRIVATE METHODE */

  /**
    @fn config($type)
    @brief Charge la configuration
    @param type string (orders, returns, reason,...)
  */
  private  function config($type){
    $TYPE=strtoupper($type);
    return array( 'type'=>$type,
		  'default_id'=>(defined('DEFAULT_'.$TYPE.'_STATUS_ID')? (int)constant('DEFAULT_'.$TYPE.'_STATUS_ID') : 1),
		  'default_completed'=>(defined('DEFAULT_'.$TYPE.'_STATUS_COMPLETED')? (int)constant('DEFAULT_'.$TYPE.'_STATUS_COMPLETED') : 1),
		  'default_annulate'=>(defined('DEFAULT_'.$TYPE.'_STATUS_ANNULATE')? (int)constant('DEFAULT_'.$TYPE.'_STATUS_ANNULATE') : 1),
		  'cst_default_id'=>'DEFAULT_'.$TYPE.'_STATUS_ID',
		  'cst_default_completed'=>'DEFAULT_'.$TYPE.'_STATUS_COMPLETED',
		  'cst_default_annulate'=>'DEFAULT_'.$TYPE.'_STATUS_ANNULATE',
		    );
  }




  /**
    @fn update_advanced()
    @brief Add/update les constantes associé au status
	  Lisaison talle configuration
  */
  private function update_advanced(){
    if (isset($_POST['default']) && ($_POST['default'] == 'on'))
      tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . tep_db_input($list_status_id) . "' where configuration_key = '".self::$config['cst_default_id']."'");
    if (isset($_POST['default_completed']) && ($_POST['default_completed'] == 'on'))
      tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . tep_db_input($list_status_id) . "' where configuration_key = '".self::$config['cst_default_completed']."'");
    if (isset($_POST['default_annulate']) && ($_POST['default_annulate'] == 'on'))
      tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . tep_db_input($list_status_id) . "' where configuration_key = '".self::$config['cst_default_annulate']."'");
  }

  /**
    @fn form_advanced($action)
    @brief From update adanvced
  */
  private static function form_advanced($action){
    $contents=array();
    if ($action=='add' || ($action=='edit' && self::$config['default_id'] != self::$oInfo->status_id) ) $contents[] = array('class' => 'block_input','text' => tep_draw_checkbox_field('default') .' '. __('utiliser comme status par default', __CLASS__));
    if ($action=='add' || ($action=='edit' && self::$config['default_completed'] != self::$oInfo->status_id) ) $contents[] = array('class' => 'block_input','text' => tep_draw_checkbox_field('default_completed') .' '. __('utiliser comme status termine', __CLASS__));
    if ($action=='add' || ($action=='edit' && self::$config['default_annulate'] != self::$oInfo->status_id) ) $contents[] = array('class' => 'block_input','text' => tep_draw_checkbox_field('default_annulate') .' '. __('utiliser comme status annule', __CLASS__));
    return  $contents;
  }





  /**
    @fn _draw_list_type($list)
    @brief Gestion list de status type
  */
  static private function _draw_list_type($list){
    global $current_theme;
    $sor=''.
	    '<tr>'."\n".
	      '<th>'.__('Liste de status / type',__CLASS__).'</th>'."\n".
	    '</tr>'."\n".
	  '</thead>'."\n".
	  '<tbody>'."\n";
    foreach ($list as $theme) {
      $sor .= '<tr class="view parent dataTableRow  '.(($theme->status_id==@$_GET['sID'])?'Selected' :'').'">'."\n".
	      '<td>'.$theme->status_name.'</td>'."\n".
	      '<td class="row_action">'.
		'<span class="view fils ">';
	$sor .='</span>'.
	      '</td>'."\n".
	    '</tr>'."\n";
    }
    return $sor;
  }


/** PUBLIC STATIC  METHODE */


  /**
    MEnu specifique pour ce module

  */
  public static function menu_mod(){
    $s ='<div class="button_nav">'."\n".
// 	'<a class="button" href="'.tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')).'action=addtype').'">'. tep_image(DIR_WS_ICONS.'icon_add_new.png' , __('Add status type',__CLASS__)).__('Add status type',__CLASS__).'</a>'."\n".
	'<a class="button" href="'.tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')).'action=add').'">'. tep_image(DIR_WS_ICONS.'icon_add_new.png' , __('Add status ',__CLASS__)).__('Add status ',__CLASS__).'</a>'."\n";
    foreach (self::$list_types as $type)
      $s .='<a class="button" href="'.tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')).'action=list&amp;type='.$type->name).'">'.__('Liste '.$type->name,__CLASS__).'</a>'."\n";
    $s .='</div>';
    return $s;
  }


  /**
    @fn add_language($new_lg)
    @brief  Add langue pour tous les status
    Utilisé dans class de gestion langue cf @class cfg_31
    @param $languages_id string
  */
  static public function add_language($new_lg){
    global $languages_id;
    $query = "SELECT DISTINCT status_type as type FROM " . TABLE_STATUS . " WHERE  language_id = '" . (int)$languages_id . "' GROUP BY status_type  ";
    $que=tep_db_query($query);
    $list_s=array();
    while ($list_status = tep_db_fetch_array($que)){
      $status_query = tep_db_query($sql="select status_id, status_name, status_color from " . TABLE_STATUS . " where status_type='".$list_status['type']."' and language_id = '" . (int)$languages_id . "'");
      while ($status = tep_db_fetch_array($status_query)) {
	tep_db_query("insert into " . TABLE_STATUS . " (status_id, status_type, language_id, status_name,status_color) values ('" . (int)$status['status_id'] . "','" .$list_status['type'] . "', '" . (int)$new_lg . "', '" . tep_db_input($status['status_name']) . "', '" . tep_db_input($status['status_color']) . "')");
      }
    }
  }

  /**
    Add langue pour tous les status
    Utilisé dans class de gestion langue cf @class cfg_31
    @param string $languages_id
  */
  static public function del_language($lg){
    tep_db_query("DELETE FROM " . TABLE_STATUS . " WHERE language_id = '" . (int)$lg . "'" );
  }


/** PUBLIC METHODE */

  /**
    Action en remplacement des action par defaut
  */
  public function draw_action(){
    global $action,$messageStack;

    self::$action=$action;

    switch ($action) {
      case 'insert':
      case 'save':
	if (isset($_GET['sID'])) $list_status_id = tep_db_prepare_input($_GET['sID']);
	$list_status_hexacolor = $_POST['status_hexacolor'];

	$languages = tep_get_languages();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
	  $list_status_name_array = $_POST['status_name'];

	  $language_id = $languages[$i]['id'];

	  $sql_data_array = array('status_name' => tep_db_prepare_input($list_status_name_array[$language_id]),
				  'status_color' => $list_status_hexacolor);

	  if ($action == 'insert') {
	    if (empty($list_status_id)) {
	      $next_id_query = tep_db_query("select max(status_id) as status_id from " . TABLE_STATUS . " where status_type='".self::$config['type']."' ");
	      $next_id = tep_db_fetch_array($next_id_query);
	      $list_status_id = $next_id['status_id'] + 1;
	    }

	    $insert_sql_data = array( 'status_id' => $list_status_id,
				      'status_type' => self::$config['type'],
				      'status_color' => $list_status_hexacolor,
				      'language_id' => $language_id);

	    $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

	    tep_db_perform(TABLE_STATUS, $sql_data_array);
	  } elseif ($action == 'save') {
	    tep_db_perform(TABLE_STATUS, $sql_data_array, 'update', "status_type='".self::$config['type']."' and status_id = '" . (int)$list_status_id . "' and language_id = '" . (int)$language_id . "'");
	  }
	}

	// update_advanced
	if(in_array(self::$config['type'],self::$type_advanced )) $this->update_advanced();


	tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID'),false).  '&sID=' . $list_status_id));
	break;

      case 'deleteconfirm':
	$sID = tep_db_prepare_input($_GET['sID']);

	$list_status_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'DEFAULT_ORDERS_STATUS_ID'");
	$list_status = tep_db_fetch_array($list_status_query);

	if ($list_status['configuration_value'] == $sID) {
	  tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '' where configuration_key = 'DEFAULT_ORDERS_STATUS_ID'");
	}

	tep_db_query("delete from " . TABLE_STATUS . " where orders_status_id = '" . tep_db_input($sID) . "'");

	tep_redirect(tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID'),false)));
      break;

      case 'delete':
	$sID = tep_db_prepare_input($_GET['sID']);

	$status_query = tep_db_query("select count(*) as count from " . TABLE_ORDERS . " where orders_status = '" . (int)$sID . "'");
	$status = tep_db_fetch_array($status_query);


	self::$remove_status = true;
	if ($sID == DEFAULT_ORDERS_STATUS_ID) {
	  self::$remove_status = false;
	  $messageStack->add(__('error remove default order status'), 'error');
	} elseif ($status['count'] > 0) {
	  self::$remove_status = false;
	  $messageStack->add(__('error status used in orders'), 'error');
	} else {
	  $history_query = tep_db_query("select count(*) as count from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_status_id = '" . (int)$sID . "'");
	  $history = tep_db_fetch_array($history_query);
	  if ($history['count'] > 0) {
	    self::$remove_status = false;
	    $messageStack->add(__('error status used in history'), 'error');
	  }
	}
      break;

      default:
    }

  }




  /**
  */
  public function load_db_values($id){
    global $action,$languages_id;

    $list_status_query_raw = "select distinct status_id, status_name, status_color from " . TABLE_STATUS . " where  status_type='".self::$config['type']."' and language_id = '" . (int)$languages_id . "' order by status_id";
    $list_status_query = tep_db_query($list_status_query_raw);
    $list_s=$lg=array();
    while ($list_status = tep_db_fetch_array($list_status_query)) {
      if (isset($_GET['sID']) && ($_GET['sID'] == $list_status['status_id']) ) {
	$query = tep_db_query("select  status_name, language_id from " . TABLE_STATUS . " where  status_type='".self::$config['type']."' and status_id='".(int)$list_status['status_id']."' ");
	while ($lg_status = tep_db_fetch_array($query))
	     $lg['name'][$lg_status['language_id']]=$lg_status['status_name'];
	self::$oInfo = new objectInfo(array_merge($list_status, $lg) );
      }

      $class_s=(isset($oInfo) && is_object($oInfo) && ($list_status['status_id'] == $oInfo->status_id)) ? " Selected": '';

      if (self::$config['default_id'] == (int)$list_status['status_id']) $list_status['status_name'] .= ' (' . __('text default') . ')';
      elseif(self::$config['default_completed'] == (int) $list_status['status_id'])  $list_status['status_name'] .=  ' (' . __('text default completed') . ')';
      elseif(self::$config['default_annulate'] == (int) $list_status['status_id'])  $list_status['status_name'].=  ' (' . __('text default annulate') . ')';

      $list_s[]=new objectInfo($list_status);
    }
    return $list_s;
  }


  /**
    Recup les types de status de type
  */
  public function load_db_type($Id){
    global $action,$languages_id;

    $query = "SELECT DISTINCT status_type as name FROM " . TABLE_STATUS . " WHERE  language_id = '" . (int)$languages_id . "' GROUP BY status_type  ";
    $que=tep_db_query($query);
    $list_s=array();
    while ($list_status = tep_db_fetch_array($que))  $list_s[]=new objectInfo($list_status);

    return $list_s;
  }

  /**
    Appelé dans le header de page
  */
  public static function draw_header(){

    tep_include_file ("includes/javascript/farbtastic/farbtastic.css",true);
    tep_include_file ("includes/javascript/farbtastic.min.js",true);
    ?>
    <script type="text/javascript"><!--
    $.fn.validHex = function() {
      return this.each(function() {
        var value = $(this).val();
        value = value.replace(/[^#a-fA-F0-9]/g, ''); // non [#a-f0-9]
        if(value.match(/#/g) && value.match(/#/g).length > 1) value = value.replace(/#/g, ''); // ##
        if(value.indexOf('#') == -1) value = '#'+value; // no #
        if(value.length > 7) value = value.substr(0,7); // too many chars
        $(this).val(value);
      });
    };

    $(function() {
      $('#colorpicker')
        .validHex()
        .keyup(function() {$(this).validHex();})
        .each(function() {
        var inp = $(this),
        picker = $('<div id="picker" class="ui-widget-content ui-helper-clearfix ui-corner-all" style="position:absolute; margin-top:20px;"/>'),
        farb = $.farbtastic(picker, function(c) {
          if(c) {
            inp[0].value = c.toUpperCase();
            inp.change();
          }
        });

        inp.focus( function() {
          farb.setColor(this.value);
          picker.css(inp.position()).fadeIn();
          $(document).bind('mousedown', function handler() {
            picker.fadeOut();
            $(this).unbind('mousedown', handler)
          });
        });

        picker.insertAfter(inp).hide().mousedown(function(e) {
          e.stopPropagation();
        });
      });
    });
    --></script>
    <?php
  }

  /**
    Contenu central
  */
  public function draw(){
    global $action,$gparentID,$current_theme;

    if($action=='cfg')  return;
    self::$list = $this->load_db_values('');
    return tep_get_include_contents(__CLASS__.'.listing');
  }



  /**
    list templates directorys public
  */
  public static  function draw_right_columm() {
    $heading = array();
    $contents = array();

    $action=self::$action;
    $oInfo=self::$oInfo;
    switch ($action) {
      case 'addtype':
	$heading[] = array('text' => __('ajoute un type de status', __CLASS__) );
	$contents[] = array('text' => __('not implemented', __CLASS__) );
	$contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_insert.gif', IMAGE_INSERT) . ' <a class="button"  href="' . tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID'))) . '">' . IMAGE_CANCEL . '</a>');
      break;
      case 'add':
	$heading[] = array('text' => __('ajoute un status', __CLASS__) );

	$contents = array('form' => tep_draw_form('status', FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')). '&amp;action=insert'));

	$languages = tep_get_languages();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
	  $contents[] = array('class' => 'block_input','text' => tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . '&nbsp;' . tep_draw_input_field('status_name[' . $languages[$i]['id'] . ']'));
	}

	$contents[] = array('class' => 'block_input','text' =>  __('utiliser une couleur', __CLASS__) . tep_draw_input_field('status_hexacolor','colorpicker',''));

	if(in_array(self::$config['type'],self::$type_advanced ))self::form_advanced($action);

	$contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_insert.gif', IMAGE_INSERT) . ' <a class="button"  href="' . tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID'))) . '">' . IMAGE_CANCEL . '</a>');
      break;

      case 'edit':
	$heading[] = array('text' =>__('Editer le status', __CLASS__) );

	$contents = array('form' => tep_draw_form('status', FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')).  '&amp;sID=' . $oInfo->status_id  . '&amp;action=save'));

	$languages = tep_get_languages();
	for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
	  $txt=(isset($oInfo->name[$languages[$i]['id']]) ?$oInfo->name[$languages[$i]['id']] : '');
	  $contents[] = array('class' => 'block_input','text' => tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . '&nbsp;' . tep_draw_input_field('status_name[' . $languages[$i]['id'] . ']','', $txt));
	}

	$contents[] = array('class' => 'block_input','text' =>  __('utiliser une couleur', __CLASS__) . tep_draw_input_field('status_hexacolor','colorpicker',$oInfo->status_color));

	if(in_array(self::$config['type'],self::$type_advanced ))$contents=array_merge($contents,self::form_advanced($action));

	$contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_update.gif', IMAGE_UPDATE) . ' <a  class="button"  href="' . tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')). '&amp;sID=' . $oInfo->status_id) . '">' .  IMAGE_CANCEL . '</a>');
      break;

      case 'delete':
	$heading[] = array('text' => __('text info heading delete orders status') );

	$contents = array('form' => tep_draw_form('status', FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')). '&amp;sID=' . $oInfo->status_id  . '&amp;action=deleteconfirm'));
	$contents[] = array('text' => __('text info delete intro'));
	$contents[] = array('text' => '<strong>' . $oInfo->status_name . '</strong>');
	if (self::$remove_status) $contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_delete.gif', IMAGE_DELETE) . ' <a  class="button" href="' . tep_href_link(FILENAME_CONFIGURATION, tep_get_all_get_params(array('action','sID')). '&amp;sID=' . $oInfo->status_id) . '">' .  IMAGE_CANCEL . '</a>');
	break;
      default:
	if (isset($oInfo) && is_object($oInfo)) {
	  $heading[] = array('text' => $oInfo->status_name );

	  $languages = tep_get_languages();
	  for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
	    $txt=(isset($oInfo->name[$languages[$i]['id']]) ?$oInfo->name[$languages[$i]['id']] : '');
	    $contents[] = array('text' => tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']) . '&nbsp;' . $txt );
	  }
	}
	break;
    }

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

}


?>
