<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2010  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.0.9
  @date  17/07/10, 10:32
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class currencies
*/

error_reporting(E_ALL);

class adminGroup
  implements ExtModPage, InterfaceModule {

  /**
    Configuration
  */
  const FILENAME = FILENAME_ADMINGROUP;
  /**
    @param int
  */
  public static $count_groups;
  /**
    @param obj
  */
  public static  $gInfo;
  /**
    @param string
  */
  public static $code;
  /**
    @param string
  */
  public static $action;
  /**
    @param array
  */
  public static $list=array();
  /**
    @param array
  */
  public static $Rightlist=array();
  /**
    @param string
  */
  public static $manager;
  /**
    @param string
  */
  public static $set;
  /**
    @param string
  */
  public static $class;
  /**
    @param array
  */
  public static $code_inistalletd_array=array();
  /**
    @param array
  */
  public static $modules_array=array();





  /**
    class constructor
  */
  public function __construct() {
    self::$code=__CLASS__;
//     self::init();

    if(isset($_GET['gID']))self::$gInfo=self::load_db_values((int)$_GET['gID']);
  }

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

    self::$action=$actions;


    switch(self::$action){
      case 'group_define':
        $selected_checkbox = $_POST['groups_to_boxes'];
        $for_grp=$_GET['gID'];
        $define_files_query = tep_db_query("select admin_files_id, admin_groups_id from " . TABLE_ADMIN_FILES . " order by admin_files_id");

        while ($define_files = tep_db_fetch_array($define_files_query)) {
          $admin_files_id= $define_files['admin_files_id'];
          $admin_groups_id = $define_files['admin_groups_id'];
          $gps_id=explode(',',$admin_groups_id);

            if (in_array ($admin_files_id, $selected_checkbox)){
            $chek=true;
//             echo "on pour:".$admin_files_id.' '.$_POST['checked_' . $admin_files_id]."<br />";
            } else  $chek=false;

            if ($chek)
              if (!in_array ($for_grp, $gps_id)) $final=preg_replace('/(^,)|(,,)/i',',',implode(',',$gps_id).','.$for_grp.',');
              else $final=preg_replace('/(^,)|(,,)/i',',',implode(',',$gps_id).',');

            if (!$chek)
              if (in_array ($for_grp, $gps_id)) {
//                 echo 'effacement:<br >';
                $id_gps=array_flip($gps_id);

                unset($id_gps[$for_grp]);
                $final=preg_replace('/(^,)|(,,)/i',',',implode(',',array_flip($id_gps)));
              }
              else $final=preg_replace('/(^,)|(,,)/i',',',implode(',',$gps_id).',');

//             echo $final.'<br >';
            $sql_data_array = array('admin_groups_id' => $final);


            tep_db_perform(TABLE_ADMIN_FILES, $sql_data_array, 'update', 'admin_files_id = \'' . tep_db_prepare_input($_POST['menu_id_' . $admin_files_id]) . '\'');
          }

        tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $_POST['admin_groups_id']));
        break;
      case 'delete_confirm':
        $set_groups_id = tep_db_prepare_input( $_GET['gID']);

        tep_db_query("delete from " . TABLE_ADMIN_GROUPS . " where admin_groups_id = '" . (int)$set_groups_id . "'");
//         tep_db_query("update  table " . TABLE_ADMIN_FILES . " change admin_groups_id set( " .  (int)$set_groups_id . " ) NOT NULL DEFAULT '1' ");
        tep_db_query("delete from " . TABLE_ADMIN . " where admin_groups_id = '" . (int) $set_groups_id . "'");

        tep_redirect(tep_href_link(self::FILENAME, 'gID=groups'));
        break;
      case 'group_edit':
        $admin_groups_name = ucwords(strtolower(tep_db_prepare_input($_POST['admin_groups_name'])));
        $name_replace = preg_replace ("/\40/", "%", $admin_groups_name);

        if (($admin_groups_name == '' || NULL) || (strlen($admin_groups_name) <= 5) ) {
          tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $_GET[gID] . '&gName=false&action=action=edit_group'));
        } else {
          $check_groups_name_query = tep_db_query("select admin_groups_name as group_name_edit from " . TABLE_ADMIN_GROUPS . " where admin_groups_id <> " . $_GET['gID'] . " and admin_groups_name like '%" . $name_replace . "%'");
          $check_duplicate = tep_db_num_rows($check_groups_name_query);
          if ($check_duplicate > 0){
            tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $_GET['gID'] . '&gName=used&action=edit_group'));
          } else {
            $admin_groups_id = $_GET['gID'];
            tep_db_query("update " . TABLE_ADMIN_GROUPS . " set admin_groups_name = '" . $admin_groups_name . "' where admin_groups_id = '" . $admin_groups_id . "'");
            tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $admin_groups_id));
          }
        }
        break;
      case 'new_confirm':
        $admin_groups_name = ucwords(strtolower(tep_db_prepare_input($_POST['admin_groups_name'])));
        $name_replace = preg_replace ("/\40/", "%", $admin_groups_name);

//         if (($admin_groups_name == '' || NULL) || (strlen($admin_groups_name) <= 5) ) {
//           tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $_GET[gID] . '&gName=false&action=new_confirm'));
//         } else {
          $check_groups_name_query = tep_db_query("select admin_groups_name as group_name_new from " . TABLE_ADMIN_GROUPS . " where admin_groups_name like '%" . $name_replace . "%'");
          $check_duplicate = tep_db_num_rows($check_groups_name_query);
          if ($check_duplicate > 0){
            tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $_GET['gID'] . '&gName=used&action=new_confirm'));
          } else {
            $sql_data_array = array('admin_groups_name' => $admin_groups_name);
            $res=tep_db_perform(TABLE_ADMIN_GROUPS, $sql_data_array);
            $admin_groups_id = tep_db_insert_id($res);
/*
            $set_groups_id = tep_db_prepare_input($_POST['set_groups_id']);
            $add_group_id = $set_groups_id . ',\'' . $admin_groups_id . '\'';
            tep_db_query("alter table " . TABLE_ADMIN_FILES . " change admin_groups_id admin_groups_id set( " . $add_group_id . ") NOT NULL DEFAULT '1' ");*/

            tep_redirect(tep_href_link(self::FILENAME, 'gID=' . $admin_groups_id));
          }
//         }
        break;

    }

  }

  public function get_header(){
    if(self::$action=='new' || self::$action=='edit') :
      tep_include_file (DIR_WS_TEMPLATE."jquery.validate.css",true);
      tep_include_file ("includes/javascript/jquery.validate.min.js",true);
    ?>
    <script type="text/javascript">
    $(function(){
      // validate signup form on keyup and submit
      $("#new_group").validate({
	invalidHandler: function(e, validator) {
	  var errors = validator.numberOfInvalids();
	  if (errors) {
	    var message = errors == 1
	      ? 'You missed 1 field. It has been highlighted below'
	      : 'You missed ' + errors + ' fields.  They have been highlighted below';
	    $("div.error span").html(message);
	    $("div.error").show();
	  }
	  else {$("div.error").hide();}
	},
	onkeyup: false,
	rules: {
	  admin_groups_name: {required: true, minlength: 6},
	},
	messages: {
	  admin_groups_name: {
	    required: "Please enter a group name",
	    minlength: "Your username must consist of at least 5 characters"
	  }
	}
      });
    });
    </script>
    <?php endif;
  }


  public static function load_db_values($ID){
    global $osCSS_Cache, $messageStack;

    $DB=Database::getInstance();
    $res=$DB->query("select * from ".TABLE_ADMIN_GROUPS. " where admin_groups_id='".(int)$ID."' ");
    return new objectInfo($res->fetchAssoc());

  }




  public function display_view(){
    switch(self::$action){
      case 'edit':

// 	return tep_get_include_contents(__CLASS__.'.listing');
//       break;
      default:
      self::tep_get_list();
      return tep_get_include_contents(__CLASS__.'.listing');
    }
  }


  public static function get_right_bar(){
    global $language;
      $heading = array();
      $contents = array();
      $DB=Database::getInstance();

      switch (self::$action) {
	case 'new':
	  $heading[] = array('text' => __('text info heading groups') );

	  $contents = array('form' => tep_draw_form('new_confirm', self::FILENAME, 'action=new_confirm', 'post'));
	  /* Retour erreur */
	    if (isset($_GET['gName']) && $_GET['gName'] == 'false')  $contents[] = array('text' => __('text info groups name false'));
	    elseif (isset($_GET['gName']) && $_GET['gName'] == 'used')  $contents[] = array('text' => __('text info groups name used'));

	    $contents[] = array('class' => 'block_input','text' => '<label for="admin_groups_name">' . __('text info groups name') . '</label>' . tep_draw_input_field('admin_groups_name') . tep_draw_hidden_field('set_groups_id', '', ''/*substr($add_groups_prepare, 4)*/));
	  $contents[] = array('class' => 'button_nav','text' => '<a  class="button"  href="' . tep_href_link(self::FILENAME) . '">' .  IMAGE_CANCEL . '</a> ' . tep_image_submit('button_next.gif', IMAGE_NEXT) );
	  break;
	case 'edit':
	  $heading[] = array('text' => __('text info heading edit group') );

	  $contents = array('form' => tep_draw_form('edit_group', self::FILENAME, 'action=group_edit&amp;gID=' . $_GET['gID'], 'post', 'enctype="multipart/form-data"'));
	  $contents[] = array('class' => 'block_input','text' => '<label for="admin_groups_name">' . __('text info edit group intro') . '</label>' . tep_draw_input_field('admin_groups_name','', self::$gInfo->admin_groups_name));
	  $contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_save.gif', IMAGE_SAVE) . ' <a class="button"  href="' . tep_href_link(self::FILENAME, 'gID=' . self::$gInfo->admin_groups_id) . '">' .  IMAGE_CANCEL . '</a>');
	break;
	case 'delete':
	  $heading[] = array('text' => __('text info heading delete groups') );

	  $contents = array('form' => tep_draw_form('delete_group', self::FILENAME, 'action=delete_confirm&amp;gID=' . self::$gInfo->admin_groups_id, 'post'));
	  if (self::$gInfo->admin_groups_id == 1) {
	    $contents[] = array('text' => sprintf(__('text info delete groups intro not'), self::$gInfo->admin_groups_name));
	    $contents[] = array('class' => 'button_nav','text' => '<a  class="button" href="' . tep_href_link(self::FILENAME, 'gID=' . $_GET['gID']) . '">' .  IMAGE_BACK . '</a>');
	  } else {
	    $contents[] = array('text' => sprintf(__('text info delete groups intro'), self::$gInfo->admin_groups_name) . tep_draw_hidden_field('set_groups_id', '', substr($del_groups_prepare, 4)));
	    $contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_delete.gif', IMAGE_DELETE) . ' <a class="button"  href="' . tep_href_link(self::FILENAME, 'gID=' . $_GET['gID']) . '">' .  IMAGE_CANCEL. '</a>');
	  }
	  break;
	case 'define_group':
	  $heading[] = array('text' => TEXT_INFO_HEADING_DEFINE );

	    if ($_GET['gPath'] == 1) {
		$contents[] = array('text' => '<span class="alert">'.sprintf(TEXT_INFO_DEFINE_INTRO_BLOCK, $group_name['admin_groups_name']).'</span>');
		$contents[] = array('text' => TEXT_NOTE_DEFINE_GRP);
		$contents[] = array('class' => 'button_nav','text' => '<a class="button" href="' . tep_href_link(self::FILENAME, 'gID=' . $_GET['gPath']) . '">' . IMAGE_CANCEL . '</a>');
	    } else {
		$contents[] = array('text' => sprintf(TEXT_INFO_DEFINE_INTRO, $group_name['admin_groups_name']));
	    }
	  break;
// 	case 'show_group':
// 	  $heading[] = array('text' => TEXT_INFO_HEADING_EDIT_GROUP );
// 	    $check_email_query = tep_db_query("select admin_email_address from " . TABLE_ADMIN . "");
// 	    //$stored_email[];
// 	    while ($check_email = tep_db_fetch_array($check_email_query)) {
// 	      $stored_email[] = $check_email['admin_email_address'];
// 	    }
//
// 	    if (in_array($_POST['admin_email_address'], $stored_email)) {
// 	      $checkEmail = "true";
// 	    } else {
// 	      $checkEmail = "false";
// 	    }
// 	  $contents = array('form' => tep_draw_form('show_group', self::FILENAME, 'action=show_group&amp;gID=groups', 'post', 'enctype="multipart/form-data"'));
// 	  $contents[] = array('class' => 'block_input','text' => $define_files['admin_files_name'] . tep_draw_input_field('level_edit','level_edit','', $checkEmail));
// 	  $contents[] = array('class' => 'button_nav','text' => tep_image_submit('button_insert.gif', IMAGE_INSERT) . ' <a href="' . tep_href_link(self::FILENAME, 'gID=' . self::$gInfo->admin_groups_id) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>');
// 	  break;
      }

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


/** Interne module */




  /** public static InterfacedTJsonS */

  private static function get_item_status($pkg){

    $s= '';
    if(self::pkg_is_installed($pkg))  $s .=tep_image(DIR_WS_ICONS . 'install.gif', ICON_REMOVE)."\n";
    else  $s .=tep_image(DIR_WS_ICONS . 'remove.gif', ICON_INSTALL)."\n";

    if(!is_dir(DIR_FS_CIP.$pkg)) $s .=tep_image(DIR_WS_ICONS . 'unpack.gif', ICON_UNZIP)."\n";
    if(file_exists(DIR_FS_CIP.$pkg.'.zip'))  $s .=tep_image(DIR_WS_ICONS . 'pack.gif', ICON_INSTALL)."\n";

//     else  $s .=tep_image(DIR_WS_ICONS . 'remove.gif', ICON_INSTALL)."\n";

    $s .= '';

    return $s;
  }

  private static function get_item_action($pkg, $pkg_full, $url_pck){

//     $s= '<span class="view fils fleft">';
//     if(self::pkg_is_installed($pkg_full)){
//       $s .='<a href="'.tep_href_link(self::FILENAME,'action=remove&amp;pkgID='.urlencode($url_pck)).'" title="'.ICON_REMOVE.'"> '.tep_image(DIR_WS_ICONS . 'install.gif', ICON_REMOVE).'</a>'."\n";
//       $s .='<a href="'.tep_href_link(self::FILENAME,'action=config&amp;class='.$pkg.'" title="'.ICON_INSTALL).'"> '.tep_image(DIR_WS_ICONS . 'icon_edit.png', IMAGE_EDIT).'</a>'."\n";
//     }else {
// //       $s .='<a href="'.tep_href_link(FILENAME_AJAX,'class=adminGroup_installer&funct=view&var='.urlencode($url_pck)).'" title="'.ICON_INSTALL.'"> '.tep_image(DIR_WS_ICONS . 'remove.gif', ICON_INSTALL).'</a>'."\n";
//       $s .='<a href="'.tep_href_link(self::FILENAME,'action=detail&amp;pkgID='.urlencode($url_pck)).'" title="'.ICON_INSTALL.'"> '.tep_image(DIR_WS_ICONS . 'remove.gif', ICON_INSTALL).'</a>'."\n";
//     }
//
//     $s .= '</span>';

    return $s;
  }

  public static function tep_get_modele(){
    return array( 'admin_groups_name',
// 		  'level',
		);
  }

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

    $DB=Database::getInstance();

      $_query = "select * from " . TABLE_ADMIN_GROUPS . " ".$sWhere." order by ".(!empty($sOrder)?" ".$sOrder : "admin_groups_id");

      $categories_split = new splitPageResults($page, $rowbyp, $_query,$query_numrows);

      $pq=$DB->query($_query);


      $list_g=array();
      $add_groups_prepare = '\'0\'' ;
      $del_groups_prepare = '\'0\'' ;
      self::$count_groups = 0;

      while ($groups = $pq->fetchAssoc() ) {
// 	$add_groups_prepare .= ',\'' . $groups['admin_groups_id'] . '\'' ;
	self::$count_groups++;
// 	$class_s="";
// 	if (((!$_GET['gID']) || ($_GET['gID'] == $groups['admin_groups_id']) || ($_GET['gID'] == 'groups')) && (!isset(self::$gInfo)) ) {
// 	self::$gInfo = new objectInfo($groups);
// 	}
	self::$list[]=$groups;
      }

    $li=$res=array();
    foreach(self::$list as $item){
//        $li['nu']='<img src="'.DIR_WS_ICONS .'details_open.png">';
      foreach(self::tep_get_modele() as $k) $li[$k]=(string)$item[$k];
//       $li['repository']=__('official');
//       $li['status']=self::get_item_status($item->ident.'_'.$item->level );
//       $li['action']=self::get_item_action($item->ident,$item->ident.'_'.$item->level,$item->url_src );
      $res[]=$li;
    }

    return $res;
  }

/** Interface module */

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

?>