<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

/**
*
* @package simpleMembership
* @copyright Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Anton Getman(ljanton@mail.ru);
* Homepage: http://www.ordasoft.com
* @version: 1.2 FREE
*
**/


defined( '_VM_IS_BACKEND' ) or define( '_VM_IS_BACKEND', '1' );
include_once( dirname(__FILE__).'/compat.joomla1.5.php' );
$GLOBALS['database'] = $database;
$mainframe = $GLOBALS['mainframe'] = JFactory::getApplication(); 
$my=$GLOBALS['my'];
$css = $mosConfig_live_site.'/administrator/components/com_simplemembership/includes/simplemembership.css';
$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path']=JPATH_SITE;

require_once ($mosConfig_absolute_path."/components/com_simplemembership/simplemembership.class.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_simplemembership/admin.simplemembership.html.php");
include_once($mosConfig_absolute_path.'/libraries/joomla/html/pagination.php');
require_once ($mosConfig_absolute_path."/administrator/components/com_simplemembership/admin.simplemembership.class.conf.php");
$GLOBALS['user_configuration'] = $user_configuration;
$GLOBALS['my'] = $my;
$GLOBALS['mosConfig_mailfrom'] = $mosConfig_mailfrom;
// load language
$lang_def_en=0;
$lang =JFactory::getLanguage();
JFactory::getLanguage()->load('com_users', JPATH_SITE, $lang->getTag(), true);//add language for com_user


//   $config_for_trigger=new JConfig();
//   $prfbd=$config_for_trigger->dbprefix;
//   $mysqli = new mysqli($config_for_trigger->host, $config_for_trigger->user, $config_for_trigger->password, $config_for_trigger->db);
//   $query="ALTER TBALE ".$prfbd."advlogin_users ADD COLUMN `sent_approved` int(11) DEFAULT '0'";
//   if(!$mysqli->multi_query($query)){
//     echo '<b style="color:red" >Error with alter table for advlogin, because:';
//     echo $mysqli->error;
//   }
//   $query="CREATE TRIGGER confirm_user AFTER UPDATE ON ".$prfbd."virtuemart_orders
//           FOR EACH ROW BEGIN
//             DECLARE USER_ID INT;
//             DECLARE PRODUCT_ID INT;
//             DECLARE GROUP_ID INT;
//             DECLARE RESULT_CONFIRM INT;
//             IF ( NEW.order_status != OLD.order_status AND NEW.order_status = 'C') THEN
//                 SELECT virtuemart_user_id INTO USER_ID FROM ".$prfbd."virtuemart_orders WHERE ".$prfbd."virtuemart_orders.virtuemart_order_id=NEW.virtuemart_order_id;
//                 SELECT virtuemart_product_id INTO PRODUCT_ID FROM ".$prfbd."virtuemart_order_items WHERE ".$prfbd."virtuemart_order_items.virtuemart_order_id=NEW.virtuemart_order_id;
//                 SELECT ".$prfbd."advlogin_groups.id INTO GROUP_ID FROM ".$prfbd."advlogin_groups WHERE ".$prfbd."advlogin_groups.product_id=PRODUCT_ID;
//                 SELECT count(*) INTO RESULT_CONFIRM FROM ".$prfbd."advlogin_groups WHERE  ".$prfbd."advlogin_groups.product_id=PRODUCT_ID;
//                 IF (RESULT_CONFIRM = 1 ) THEN
//                   UPDATE ".$prfbd."advlogin_users SET approved='0', sent_approved='0', last_approved=CURDATE(), advgroup_id=GROUP_ID  WHERE joomid=USER_ID;
//                 END IF ;
//             END IF ;
//           END ;";
//   $mysqli = new mysqli($config_for_trigger->host, $config_for_trigger->user, $config_for_trigger->password, $config_for_trigger->db);
//   $mysqli->query('DROP TRIGGER IF EXISTS confirm_user');
//   if(!$mysqli->multi_query($query)){
//     echo '<b style="color:red" >Error with created trigger for virtuemart, because:';
//     echo $mysqli->error;
//   }
///my test
// if(isset($_GET['test']) & $_GET['test']=='joom'){
//   for($i=1001; $i<=2000; $i++){
//       $query = "INSERT INTO #__users SET name='".$i."', email='".$i."jfsdjkl@jhk.jc'";
//       $database->setQuery($query);
//       $database->query();
//       $database->getErrorMsg();
//       $query = "SELECT id FROM #__users ORDER BY id DESC";
//       $database->setQuery($query);
//       $id=$database->loadResult();
//       $query="INSERT INTO #__user_usergroup_map SET user_id='".$id."', group_id='2'";
//       $database->setQuery($query);
//       $database->query();
//   }
// }
// // 
// // 
// // 
// if(isset($_GET['test']) & $_GET['test']=='adv'){
//       $query = "UPDATE #__simplemembership_users SET last_approved='2011-01-03', approved='0', advgroup_id='1'";
//  //     $query = "UPDATE #__simplemembership_users SET approved='0'";
//       $database->setQuery($query);
//       $database->query();
//       echo $database->getErrorMsg(); exit;
// }

///my test






foreach ($lang->getLocale() as $locale) {
          $mosConfig_lang=$locale;
    if (file_exists($mosConfig_absolute_path."/components/com_simplemembership/language/{$mosConfig_lang}.php" ))     {  
          include_once($mosConfig_absolute_path."/components/com_simplemembership/language/{$mosConfig_lang}.php" );
          $lang_def_en=1;
           break;
    } 
}
if ( $lang_def_en != 1 ) {
   $mosConfig_lang = "english";  
   include_once($mosConfig_absolute_path."/components/com_simplemembership/language/english.php" );
}


$GLOBALS['user_configuration'] = $user_configuration;
$GLOBALS['database'] = $database;

$GLOBALS['mosConfig_absolute_path'] = $mosConfig_absolute_path;
$GLOBALS['task'] = $task = mosGetParam($_REQUEST, 'task', '');
$GLOBALS['option'] = $option = mosGetParam($_REQUEST, 'option', 'com_simplemembership');

$bid = mosGetParam($_POST, 'bid', array (0));
$section = mosGetParam( $_REQUEST, 'section', '' );



require_once($mosConfig_absolute_path.'/administrator/components/com_simplemembership/syncexpire.php');
check_users();



if (isset($section) && $section=='group')
{
	switch ($task){

		case "edit" :
			editGroup($option, $bid[0]);
			break;
		case "add":
			editGroup($option, 0);
			break;
		case "cancel":
			cancelGroup();
			break;

		case "publish":
			group_publish();
			break;

		case "unpublish":
			group_unpublish();
			break;


		case "save":
			saveGroup();
			break;
		case "remove":
			removeCategories($option, $bid);
			break;

		case "add_acl_group" :
			add_acl_group();
			break;

		case "del_acl_group_form" :
			del_acl_group_form();
			break;

		case "show":
			default :
				showCategories();
	}
}
else
{
	switch ($task) {
		case "categories":
	echo "now work $section=='group , this part not work"; exit;
	mosRedirect( "index.php?option=com_simplemembership&section=group" );
	break;

	case "save_user" :
		saveUser($option, 0);
		break;

	case "add_user" :
		editUser($option, 0);
		break;

	case "edit_user" :
		editUser($option, array_pop($bid));
		break;

	case "remove" :
		 removesimplememberships($bid, $option);
		 break;

	case "publish" :
	 	publishUsers($bid, 1, $option);
	 	break;

	case "unpublish" :
		publishUsers($bid, 0, $option);
	 	break;

	 case "approve" :
	 	approveUsers($bid, 1, $option);
	 	break;

	 case "unapprove" :
	 	approveUsers($bid, 0, $option);
	 	break;

	 case "cancel" :
	 	cancelsimplemembership($option);
	 	break;

	case "config_frontend" :
	 	configure_frontend($option);
	 	break;

	 case "manage_qmodifications" :
	 	manage_qmodifications($option, "");
	 	break;
 
	 case "config_backend" :
	 	configure_backend($option);
	 	break;

	 case "config_save_frontend" :
	 	configure_save_frontend($option);
	 	break;

	 case "config_save_backend" :
	 	configure_save_backend($option);
	 	break;

	 case "about" :
                $htmlSimplemembership = new HTML_simplemembership();
	 	$htmlSimplemembership -> about(); 
	 	break;

	case "add_acl_group" :
	 	add_acl_group();
	 	break;

	case "save_newacl" :
	 	save_newacl();
	 	break;

	case "del_acl_group" :
		del_acl_group();
		break;

	 default :
	 	showUsers($option); 
	 	break;
	}
} //else

class CAT_Utils
{
	function categoryArray()
	{
		global $database;
		// get a list of the menu items
		$query = "SELECT c.*, c.parent_id AS parent"
		. "\n FROM #__categories c"
		. "\n WHERE section='com_simplemembership'"
		. "\n AND published <> -2"
		. "\n ORDER BY ordering" ;
		$database->setQuery($query);
		$items = $database->loadObjectList();
		// establish the hierarchy of the menu
		$children = array();
		// first pass - collect children
		foreach ($items as $v) {
			$pt = $v->parent;
			$list = @$children[$pt] ? $children[$pt] : array();
			array_push($list, $v);
			$children[$pt] = $list;
		}
		// second pass - get an indent list of the items
		$array = mosTreeRecurse(0, '', array(), $children);
		return $array;
	}
}

/**
 * HTML Class
 * Utility class for all HTML drawing classes
 * @desc class General HTML creation class. We use it for back/front ends.
 */


function group_publish()
{
	global $database;
	if(array_key_exists('bid', $_POST))
	$in = implode(',', $_POST['bid']);
	else
	mosRedirect('index.php?option=com_simplemembership&section=group','At least one item must be selected');

	$query = "update #__simplemembership_groups set published='1' where id IN ($in)";
	$database->setQuery($query);
	$database->query();
	mosRedirect('index.php?option=com_simplemembership&section=group');
}

function group_unpublish()
{
	global $database;
	if(array_key_exists('bid', $_POST))
	$in = implode(',', $_POST['bid']);
	else
	mosRedirect('index.php?option=com_simplemembership&section=group','At least one item must be selected');

	$query = "update #__simplemembership_groups set published='0' where id IN ($in)";
	$database->setQuery($query);
	$database->query();
	mosRedirect('index.php?option=com_simplemembership&section=group');
}

function add_acl_group()
{
	global $acl,$mosConfig_absolute_path;

	$option = 'com_simplemembership';
  $group_children_tree = array ();
  
  include_once($mosConfig_absolute_path.'/administrator/components/com_users/models/groups.php'); // for J 1.6
  
  $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
  $mosHTML = new mosHTML ();

  foreach ($g = $model->getItems() as $k => $v) { // $g contains basic usergroup items info
    $group_title = '.';
    for ($i=1; $i<=$g[$k]->level; $i++) 
    {
      $group_title .= '-';
    }
    $group_title .= '-'.$g[$k]->title;
    
    $group_children_tree[] = $mosHTML -> makeOption($g[$k]->id, $group_title);
  }


  $gtree[] = $mosHTML -> makeOption('-2', 'Everyone');
  $gtree = array_merge ( $gtree, $group_children_tree); 
$group_children_tree = array ();
$gtree = array_merge ( $gtree, $group_children_tree); 
$mosHTML = new mosHTML();
	$lists['acl_group_select'] = $mosHTML ->selectList($gtree, 'acl_group_select', 'size="4" ', 'value', 'text');
        $htmlSimplemembership = new HTML_simplemembership();
	$htmlSimplemembership -> add_acl_group_form($option,$lists);
}

function del_acl_group_form()
{
	global $acl,$database;
	$option = 'com_simplemembership';
	$query = "select * from #__usergroups where id>'0'
	 AND title<>'USERS'
	 AND title<>'ROOT'
   AND title<>'Public'
   AND title<>'Super Users'
	 AND title<>'Customer Group'
	 AND title<>'Administrator'
	 AND title<>'Registered'
	 AND title<>'Author'
	 AND title<>'Editor'
	 AND title<>'Publisher'
	 AND title<>'Manager'
   AND title<>'Super Administrator'
   AND title<>'Shop Suppliers'
";
	$database->setQuery($query);

	$lists['custom_groups'] = '';
	$groups = $database->loadObjectList();
	foreach($groups as $group)
	$lists['custom_groups'] .= '<input type="radio" name="bid[]" value="'.$group->id.'">'.$group->name.'<br />';
        $htmlSimplemembership = new HTML_simplemembership();
	$htmlSimplemembership -> del_acl_group_form($option,$lists);
}

function rebuild_tree($parent_id, $left) {
  global $database; 
  
    // the right value of this node is the left value + 1
       $right = $left+1;

       // get all children of this node
      $query = 'SELECT id FROM #__usergroups '.'WHERE parent_id="'.$parent_id.'";';
      $database->setQuery($query);
      $groups = $database ->loadObjectList();

        foreach($groups as $group) {
           // recursive execution of this function for each
           // child of this node
           // $right is the current right value, which is
           // incremented by the rebuild_tree function
           $right = rebuild_tree($group->id, $right);
         }

       // we've got the left value, and now that we've processed
       // the children of this node we also know the right value
      $query = 'UPDATE #__usergroups SET lft='.$left.', rgt='.
                    $right.' WHERE id="'.$parent_id.'";';
      $database->setQuery($query);
      $database -> query();

       // return the right value of this node + 1
       return $right+1;
    }

function del_acl_group()
{
//	print_r($_POST);exit;
	global $database;
	if(!is_array($_POST['bid']))
	mosRedirect('index.php?option=com_simplemembership&section=group','No selected items');
	$bid = (int)$_POST['bid'][0];

	$query = "delete from #__usergroups where id='$bid'";
	$database->setQuery($query);
	$database -> query();
	rebuild_tree(0,1);
	mosRedirect('index.php?option=com_simplemembership&section=group');
}

function save_newacl()
{
	global $database,$mainframe;
 
	if($_POST['acl_name']=='')
	{
		$mainframe->enqueueMessage('Joomla group name must not be empty!!. ','error');
		mosRedirect("index.php?option=com_simplemembership&section=group");
	}

	$acl_name = $_POST['acl_name'];
	$acl_group_select = (int)$_POST['acl_group_select'];

	if($acl_group_select=='')
	{
		$mainframe->enqueueMessage('Parent group must be present. ','error');
		mosRedirect("index.php?option=com_simplemembership&section=group");
	}

  $query = "insert into #__usergroups (title, parent_id) VALUES ('".($acl_name)."','$acl_group_select')";
 
	$database->setQuery($query);
	$database->query();
	//print_r($database);  exit;
  
  rebuild_tree(0,1);
	mosRedirect('index.php?option=com_simplemembership&section=group');
}


function showCategories()
{
	global $database, $my, $option, $menutype, $mainframe, $mosConfig_list_limit,$mosConfig_fromname;

	
	$query = "SELECT * from #__simplemembership_groups order by name";

	$database->setQuery($query);
	$rows = $database->loadObjectList();

	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	// establish the hierarchy of the categories
        $htmlCategories = new HTML_Categories();
	$htmlCategories -> show($rows);
}

function editGroup($section = '', $uid = 0)
{
	global $database, $my,$acl;
	global $mosConfig_absolute_path, $mosConfig_live_site;

	$edit=false;
  
	if(array_key_exists('bid', $_POST))
	{
		$id = $_POST['bid'][0];
		$query = "select * from #__simplemembership_groups where id='$id'";
		$database->setQuery($query);
		$row = $database->loadObjectList();
		$row = $row[0];
    $query = "SELECT jgroup_id FROM #__simplemembership_group_joomgroup WHERE mgroup_id='$id'";
    $database->setQuery($query);
    $row->acl_gid=$database->loadResultArray();
    $edit = true;
  }
	else $row ='';


    
  $group_children_tree = array ();
  
  include_once($mosConfig_absolute_path.'/administrator/components/com_users/models/groups.php'); 
  
  $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
  $mosHTML =new mosHTML();

  foreach ($g = $model->getItems() as $k => $v) { // $g contains basic usergroup items info
    $group_title = '.';
    for ($i=1; $i<=$g[$k]->level; $i++) 
    {
      $group_title .= '-';
    }
    $group_title .= '-'.$g[$k]->title;
    
    $group_children_tree[] = $mosHTML -> makeOption($g[$k]->id, $group_title);
  }


  $gtree[] = $mosHTML -> makeOption('-2', 'Everyone');
  $gtree = array_merge ( $gtree, $group_children_tree); 
	
  if($edit){
        $mosHTML = new mosHTML();
	$lists['acl_group_select'] = $mosHTML ->selectList($gtree, 'acl_group_select[]', 'size="4" multiple', 'value', 'text', $row->acl_gid);
        }
        else{
        $mosHTML = new mosHTML();
	$lists['acl_group_select'] = $mosHTML ->selectList($gtree, 'acl_group_select[]', 'size="4" multiple', 'value', 'text');
        }
	$type = mosGetParam($_REQUEST, 'type', '');
	$redirect = mosGetParam($_POST, 'section', '');;
//echo 11111111111111111;
        $mosHTML = new mosHTML ();
	$date_list = array();
	$date_list[] = $mosHTML -> makeOption(0,'Never');
	$date_list[] = $mosHTML -> makeOption(5,'5 days');
	$date_list[] = $mosHTML -> makeOption(10,'10 days');
	$date_list[] = $mosHTML -> makeOption(30,'30 days');
	$date_list[] = $mosHTML -> makeOption(60,'60 days');
	$date_list[] = $mosHTML -> makeOption(90,'90 days');
	$date_list[] = $mosHTML -> makeOption(180,'180 days');
	$date_list[] = $mosHTML -> makeOption(365,'365 days');

	if($edit){
        $mosHTML = new mosHTML();        
	$lists['date_select'] = $mosHTML->selectList($date_list, 'date_select', 'size="1" ', 'value', 'text', $row->days_last);
        }
	else{
        $mosHTML = new mosHTML();
	$lists['date_select'] = $mosHTML->selectList($date_list, 'date_select', 'size="1" ', 'value', 'text');
        }
  
//	print_r($_POST);exit;
        $htmlCategories = new HTML_Categories();
	$htmlCategories -> edit( $section, $lists, $redirect, $row);
}

function saveGroup()
{

	global $database,$mosConfig_live_site;
	$post = $_POST;
	foreach ($_POST as $key => $val)
	{
    if($key == 'acl_group_select' ) {
      continue;
    }
		if(get_magic_quotes_gpc()) {
			$val = stripslashes($val);
		}
		$val = trim($val);
		$post[$key] = $val;
	}

	$acl_group = @$post['acl_group_select'];
	$product_id = (int)$post['product_select'];

	if(count($acl_group) < 1)
	{
		echo "<script> alert('Joomla group must be selected'); window.history.go(-1);</script>\n";
		exit;
	}
	if($product_id!=0)
	{
		$query = "select product_name from #__virtuemart_products_en_gb where virtuemart_product_id='$product_id'";
		$database->setQuery($query);
		$product_name = $database->loadResult();
    $link=$mosConfig_live_site.'/index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$product_id;
// 		$link = $mosConfig_live_site.'/index.php?page=shop.product_details&flypage=flypage.tpl&product_id='.$product_id.'&option=com_virtuemart';
	}
	else
	{
		$product_name = '';
		$link = '';
	}

	if($post['title']=='')
	{
		echo "<script> alert('Group name must be present'); window.history.go(-1);</script>\n";
		exit;
	}

	if(array_key_exists('id', $_POST) && (int)$_POST['id']!='')
	{
		$id = (int)$_POST['id'];
		$query = "update #__simplemembership_groups SET
name='".($post['title'])."',
days_last='".($post['date_select'])."',product_id='$product_id',
product_name='".($product_name)."',link='".($link)."'
,notes='".($post['notes'])."' where id='$id'";
		$database->setQuery($query);
		$database->query();
    $query="DELETE FROM #__simplemembership_group_joomgroup WHERE mgroup_id='$id'";
    $database->setQuery($query);
    $database->query();
    foreach($acl_group as $group){
      $query="INSERT INTO #__simplemembership_group_joomgroup SET mgroup_id='$id', jgroup_id='$group'";
      $database->setQuery($query);
      $database->query();
    }
  }
	else
	{
		$query = "insert into #__simplemembership_groups (name,days_last,product_id,product_name,link,notes)
 VALUES('".($post['title'])."','".($post['date_select'])."','$product_id',
'".($product_name)."','$link'
,'".($post['notes'])."')";
		$database->setQuery($query);
		$database->query();
		

    $query="SELECT id FROM #__simplemembership_groups ORDER BY #__simplemembership_groups.id DESC LIMIT 0 , 1";
    $database->setQuery($query);
    $id = $database->loadResult();
    foreach($acl_group as $group){
      $query="INSERT INTO #__simplemembership_group_joomgroup SET mgroup_id='$id', jgroup_id='$group'";
      $database->setQuery($query);
      $database->query();
    }
	}

//	 print_r($database);  exit;

  mosRedirect('index.php?option=com_simplemembership&section=group');
}


function removeCategoriesFromDB($cid)
{
	global $database, $my;

	if(array_key_exists('bid', $_POST))
	if(is_array($_POST['bid']))
	{
		$bid = $_POST['bid'];
		$instr = implode(',', $bid);

		$sql="DELETE FROM #__simplemembership_groups WHERE id IN ($instr) ";
		$database->setQuery($sql);
		$database->query();
	}
}

/**
 * Deletes one or more categories from the categories table
 *
 * @param string $ The name of the category section
 * @param array $ An array of unique category id numbers
 */
function removeCategories($section, $cid)
{
	//	print_r($_POST);exit;
	global $database;
	if (count($cid) < 1) {
		echo "<script> alert('Select a category to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	foreach ($cid as $catid) {
		removeCategoriesFromDB($catid) ;
	}
	$msg = (count($err) > 1 ? "Categories " : _SIMPLEMEMBERSHIP_CATEGORIES_NAME . " ") . _SIMPLEMEMBERSHIP_DELETED;
	mosRedirect('index.php?option=com_simplemembership&section=group&mosmsg=' . $msg) ;
}

/**
 * Publishes or Unpublishes one or more categories
 *
 * @param string $ The name of the category section
 * @param integer $ A unique category id (passed from an edit form)
 * @param array $ An array of unique category id numbers
 * @param integer $ 0 if unpublishing, 1 if publishing
 * @param string $ The name of the current user
 */

function publishCategories($section, $categoryid = null, $cid = null, $publish = 1)
{
	global $database, $my;

	if (!is_array($cid)) {
		$cid = array();
	}
	if ($categoryid) {
		$cid[] = $categoryid;
	}

	if (count($cid) < 1) {
		$action = $publish ? _PUBLISH : _DML_UNPUBLISH;
		echo "<script> alert('" . _DML_SELECTCATTO . " $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$cids = implode(',', $cid);

	$query = "UPDATE #__categories SET published='$publish'"
	. "\nWHERE id IN ($cids) AND (checked_out=0 OR (checked_out='$my->id'))" ;
	$database->setQuery($query);
	if (!$database->query()) {
		echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
		exit();
	}

	if (count($cid) == 1) {
		$row = new mosCategory($database);
		$row->checkin($cid[0]);
	}

	mosRedirect('index.php?option=com_simplemembership&section=group');
}

/**
 * Cancels an edit operation
 *
 * @param string $ The name of the category section
 * @param integer $ A unique category id
 */
function cancelGroup()
{
	global $database;
	$row = new mosCategory($database);
	$row->bind($_POST);
	$row->checkin();
	mosRedirect('index.php?option=com_simplemembership&section=group');
}


/**
 * changes the access level of a record
 *
 * @param integer $ The increment to reorder by
 */

function removesimplememberships($bid, $option)
{
	global $database;
  

	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	if (count($bid)) {
		$bids = implode(',', $bid);
		$database->setQuery("select joomid FROM #__simplemembership_users WHERE id IN ($bids)");
		$jom_userlist = $database->loadObjectList();


		foreach($jom_userlist as $user)
		{
			$database->setQuery("DELETE FROM #__users WHERE id='$user->joomid'");
			$database->query();
		}

		$database->setQuery("DELETE FROM #__simplemembership_users WHERE id IN ($bids)");
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect("index.php?option=$option");
}




function showUsers($option)
{
	advexpire();
	sync_users();
	global $database, $mainframe, $mosConfig_list_limit;

	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
	$advgid = $mainframe->getUserStateFromRequest("advgid{$option}", 'advgid', '-2');//old 0
	$pub = $mainframe->getUserStateFromRequest("pub{$option}", 'pub', '-1');//add nik
	$enable = $mainframe->getUserStateFromRequest("enable{$option}", 'enable', '-1');//add nik

	$search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
	$search = $database->getEscaped(trim(strtolower($search)));

	$where = array ();

	if ($pub== "pub") {
		array_push($where, "approved = 0");
	} else if ($pub == "not_pub") {
		array_push($where, "approved = 1");
	}

	if ($enable== "enable") {
		array_push($where, "block = 0");
	} else if ($enable == "not_enable") {
		array_push($where, "block = 1");
	}

	$query = "select * from #__simplemembership_groups where id='$advgid'";
	$database->setQuery($query);
	$test = $database->loadResult();
	if ($test!='') {
		array_push($where, "advgroup_id = $advgid");
	}

	if ($search) {
		array_push($where, "(LOWER(a.username) LIKE '%$search%')");
	}

	$database->setQuery("SELECT count(*) FROM #__simplemembership_users AS a".
	(count($where) ? "\nWHERE ".implode(' AND ', $where) : ""));

	$total = $database->loadResult();

	echo $database->getErrorMsg();

	//require_once ($GLOBALS['mosConfig_absolute_path'].'/administrator/includes/pageNavigation.php');
	$pageNav = new JPagination( $total, $limitstart, $limit );

// 	$selectstring = "SELECT a.*, gr.name AS group_name,ju.title AS joom_usertype ,jub.title AS joom_usertypew FROM #__simplemembership_users AS a "
// 	. "\n LEFT JOIN #__simplemembership_groups AS gr ON gr.id = a.advgroup_id".
// 	 "\n LEFT JOIN #__usergroups AS ju ON ju.id = a.gid".
// 	 "\n LEFT JOIN #__usergroups AS jub ON jub.id = a.want_gid".
// 	(count($where) ? "\nWHERE ".implode(' AND ', $where) : "").
// 					"\nORDER BY name".
// 					"\nLIMIT $pageNav->limitstart,$pageNav->limit;";


 $selectstring = "SELECT a.*, gr.name AS group_name,ju.title AS joom_usertype ,jub.title AS joom_usertypew FROM #__simplemembership_users AS a "
 . "\n LEFT JOIN #__simplemembership_groups AS gr ON gr.id = a.advgroup_id".
  "\n LEFT JOIN #__usergroups AS ju ON ju.id = a.gid".
  "\n LEFT JOIN #__usergroups AS jub ON jub.id = a.want_gid".
 (count($where) ? "\nWHERE ".implode(' AND ', $where) : "").
         "\nORDER BY name".
         "\nLIMIT $pageNav->limitstart,$pageNav->limit;";


	$database->setQuery($selectstring);
	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}
$temp_rows=$rows;
  foreach($rows as $row_key => $row_value){
    $query ="SELECT ug.title from #__usergroups AS ug 
    LEFT JOIN #__user_usergroup_map AS ugm ON ug.id=ugm.group_id 
    WHERE ugm.user_id=".$row_value->joomid;
    $database->setQuery($query);
    $current_groups=$database->loadResultArray();
    $temp_rows[$row_key]->gid=$current_groups;

    $query ="SELECT ug.title FROM #__usergroups AS ug
    LEFT JOIN #__simplemembership_group_joomgroup as sgj ON ug.id=sgj.jgroup_id 
    WHERE sgj.mgroup_id=(SELECT advgroup_id FROM #__simplemembership_users WHERE id=".$row_value->id.")";
    $database->setQuery($query);
    $want_groups=$database->loadResultArray();
    if(count($want_groups) >= 1 ) {
      $temp_rows[$row_key]->joom_usertypew=$want_groups;
    }
    else {
      $temp_rows[$row_key]->joom_usertypew=array($temp_rows[$row_key]->joom_usertypew);
    }
  }
$rows=$temp_rows;


	/*
	 * select list treeSelectList
	 */
        $mosHTML = new mosHTML (); 
	$categories[] = $mosHTML -> makeOption('0', _SIMPLEMEMBERSHIP_LABEL_SELECT_CATEGORIES);
	$categories[] = $mosHTML -> makeOption('-1', _SIMPLEMEMBERSHIP_LABEL_SELECT_ALL_CATEGORIES);

	$pubmenu[] = $mosHTML -> makeOption('0', _SIMPLEMEMBERSHIP_LABEL_SELECT_TO_PUBLIC);
	$pubmenu[] = $mosHTML -> makeOption('-1', _SIMPLEMEMBERSHIP_LABEL_SELECT_ALL_PUBLIC);
	$pubmenu[] = $mosHTML -> makeOption('not_pub', _SIMPLEMEMBERSHIP_LABEL_SELECT_NOT_PUBLIC);
	$pubmenu[] = $mosHTML -> makeOption('pub', _SIMPLEMEMBERSHIP_LABEL_SELECT_PUBLIC);

	$publist = $mosHTML -> selectList($pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);

	$enablemenu[] = $mosHTML -> makeOption('0', _SIMPLEMEMBERSHIP_LABEL_SELECT_TO_ENABLE);
	$enablemenu[] = $mosHTML -> makeOption('-1', _SIMPLEMEMBERSHIP_LABEL_SELECT_ALL_ENABLE);
	$enablemenu[] = $mosHTML -> makeOption('not_enable', _SIMPLEMEMBERSHIP_LABEL_SELECT_NOT_ENABLE);
	$enablemenu[] = $mosHTML -> makeOption('enable', _SIMPLEMEMBERSHIP_LABEL_SELECT_ENABLE);

	$enablelist = $mosHTML -> selectList($enablemenu, 'enable', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $enable);

	$options = array();
	$query = "select * from #__simplemembership_groups";
	$database->setQuery($query);
	$pr_lis = $database->loadObjectList();

	$options[] = $mosHTML ->makeOption( -2, 'All groups');
	$options[] = $mosHTML ->makeOption( 0, 'Joomla group');

	foreach($pr_lis as $item)
	$options[] = $mosHTML ->makeOption( $item->id, $item->name);
	
	$olist = $mosHTML ->selectList($options, 'advgid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $advgid);
        $HTML_simplemembership = new HTML_simplemembership();
        $HTML_simplemembership -> showUsers($option, $rows, $publist, $search, $pageNav, $olist, $enablelist);
}

function saveUser()
{
	global $database, $my, $user_configuration,$mainframe,$mosConfig_live_site;

	$default_group = $user_configuration['default_group'];
	
  $default_group = $user_configuration['default_group']; 
  if(count($default_group)<1) {
    $default_group=array('2'=>'2');
    $default_group_name='Registered';
  }
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ( ".implode(",",$default_group)." )";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $default_group_name=implode(",",$default_group_name);
    $default_group=array_combine($default_group,$default_group);
  }
  
  
  
  
  
//   if($default_group=='')
// 	$default_group = 2;
// 	$query = "SELECT title FROM #__usergroups WHERE id='$default_group'";
// 	$database->setQuery($query);
// 	$default_group_inf = $database->loadResult();
// 
// 	if(!$default_group_inf)
// 	{
// 		$default_group_id = 2;
// 		$default_group_name = 'Registered';
// 	}
// 	else
// 	{
// 		$default_group_id = $default_group;
// 		$default_group_name = $default_group_inf;
// 	}

	if($_POST['name'] == '' ||$_POST['email'] == '' || $_POST['username'] == '')
	{
		$mainframe->enqueueMessage('Fields Name, UserName and email must be filled!. ','error');
		mosRedirect("index.php?option=com_simplemembership");
	}

	if(array_key_exists('bid', $_POST))
	$bid = (int)$_POST['bid'];
	else
	$bid = 0;

	$new_ug_id = (int)$_POST['advgid'];

	$user = new JUser();

	if($bid!=0)
	{
		$query = "SELECT * from #__simplemembership_users where id='$bid'";
		$database->setQuery($query);
		$tmp_us = $database->loadObject();
		$adv_uid = $tmp_us->id;
		$joom_id = $tmp_us->joomid;
		$adv_wg = $tmp_us->want_gid;
		$adv_dl = $tmp_us->days_last;
		$user->load($joom_id);
  $data_for_bind=$_POST;
  $data_for_bind['id']=$joom_id;
  $user->bind($data_for_bind);
		if($new_ug_id!=-1 && $new_ug_id!=-2)
		{
			$query = "select * from #__simplemembership_groups where id='$new_ug_id'";
			$database->setQuery($query);
			$group = $database->loadObjectList();
			$group = $group[0];

			$g_acl_gid = $group->acl_gid;
			$g_dl = $group->days_last;
		}
		else
		{
			$g_acl_gid = $default_group;
			$g_dl = 0;
		}

		if(($adv_wg!=$g_acl_gid) ||($adv_dl!=$g_dl))
		{
			if($new_ug_id!=-2)
			{
				$user->groups=$default_group;
				$user->usertype = $default_group_name;
			}
		}
	}
	else
	{
		$user->bind($_POST);
		$user->groups=$default_group;
		$user->usertype = $default_group_name;
	}
  $user->name = $_POST['name'];
  $user->email = $_POST['email'];
  $user->username = $_POST['username'];

// 	if($bid==0)
// 	$user->password = $_POST['password'];

	$user->registerDate = date('Y-m-d h:i:s');

	if($user->save())
	{ 
		$al_user = new mos_alUser($database);
		if($bid!=0)
		$al_user->load($bid);
		$al_user->bind($_POST);

		$al_user->joomid = $user->id;

		$prev_group = $al_user->advgroup_id;

		if($new_ug_id!=-1)
		{
			$query = "select * from #__simplemembership_groups where id='$new_ug_id'";
			$database->setQuery($query);
			$group = $database->loadObjectList();
			$group = $group[0];

			$al_user->want_gid = $group->acl_gid;
			$al_user->want_group = $group->acl_group;
			$al_user->days_last = $group->days_last;
			$al_user->advgroup_id = $new_ug_id;
		}
		else
		{
			$al_user->want_gid = $default_group;
			$al_user->want_group = $default_group_name;
			$al_user->days_last = 0;
			$al_user->advgroup_id = 0;
		}

//		print_r($user);
//		echo '<br />catch<br /> :: '.$prev_group.' :: '.$new_ug_id.' |';exit;

		if($prev_group!=$new_ug_id)
		{
			if($new_ug_id!=-2)
			{
				$al_user->gid = $default_group;
				$al_user->usertype = $default_group_name;
			}
			$al_user->block = $user->block;
			$al_user->approved = 1;
		}
		$al_user->store();
		$mainframe->enqueueMessage('User created');
	}
	else
	{
		$mainframe->enqueueMessage('User not created. '. $user->getError(),'error');
	}
	mosRedirect("index.php?option=com_simplemembership");
}

function editUser($option,$bid)
{
	global $database, $my, $mosConfig_live_site, $user_configuration, $mosConfig_absolute_path; 

	/// DEFAULT GROUP
  $default_group = $user_configuration['default_group']; 
  if(count($default_group)<1) {
    $default_group=array('2'=>'2');
    $default_group_name='Registered';
  }
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id = '$default_group' ";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $default_group_name=$default_group_name;
 //   $default_group=array_combine($default_group,$default_group);
  }
  
  
//   if($default_group=='')
// 	$default_group = 2;
// 
// 	$query = "select title from #__usergroups where id='$default_group'";
// 	$database->setQuery($query);
// 	$default_group_inf = $database->loadResult();
// 
// 	if(!$default_group_inf)
// 		$default_group_name = 'Registered';
// 	else
// 		$default_group_name = $default_group_inf;

	/// END DEFAULT GROUP

	$user = new mos_alUser($database);
	$user->load(intval($bid));

	$joom_user = new JUser();
	if($bid)
	{
		$joom_user->load($user->joomid);
	}
  $joom_user->params=json_decode($joom_user->params, true);
	$options = array();
	$query = "select * from #__simplemembership_groups where published='1'";
	$database->setQuery($query);
	$pr_lis = $database->loadObjectList();

	if($user->advgroup_id==0 && $bid!=0){
        $mosHTML = new mosHTML();
	$options[] = $mosHTML -> makeOption( -2, $joom_user->usertype .'(Joomla group)');
        }
	

	foreach($pr_lis as $item)
	{
             if($item->id==$user->advgroup_id)
                 $name_of_group=$item->name; 
            $options[] = $mosHTML ->makeOption( $item->id, $item->name);
	}

	if(array_key_exists(0, $options)){
        $mosHTML = new mosHTML();     
	$olist = $mosHTML ->selectList($options, 'advgid', '', 'value', 'text', $user->advgroup_id);
        }
	else
	$olist = $default_group_name.'(Joomla group)';
  
  
  
  $last_approved_date=strtotime($user->last_approved);
  $cur_date=@date("U");
  $days_gone = (int)($cur_date-$last_approved_date)/86400;
  if((($user->days_last)-$days_gone)<0){
  if(isset($name_of_group) && $name_of_group !=''){
    $msg='<br/>This user is exired for group <b>'.$name_of_group;
  }
  else{
    $msg='<br/>This user can be in ones of these groups';
  }
  }
  if((($user->days_last)-$days_gone)>0){
  $msg='<br/>This user can be in this group for next '.ceil($user->days_last-$days_gone).'day(s)';
  }
  
  
//add profile and basic form fields
  $dispatcher = JDispatcher::getInstance();
      JPluginHelper::importPlugin('user');
      JForm::addFormPath($mosConfig_absolute_path.'/components/com_simplemembership/forms');
      $user_profile_form = JForm::getInstance('com_users.user', 'user');
      //$user_profile_form->load('com_users.profile', 'profile', array('control' => 'jform', 'load_data' => $joom_user));
      //JForm::addFormPath($mosConfig_absolute_path.'/components/com_simplemembership/forms');
      //$user_profile_form->loadFile('params', true);

      //$results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.registration', $joom_user));
      $results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.user', $joom_user));
      $results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $joom_user));
      //$user_profile_form->loadFile('frontend_admin', false);
//       print_r($joom_user);
//       echo"2222";print_r($user_profile_form);
      //$user_profile_form->params = array();
      $user_profile_form->bind($joom_user);
  //print_r($user_profile_form);
  
  
        $htmlSimplemembership = new HTML_simplemembership();
	$htmlSimplemembership -> editUser($option, $user, $olist, $bid, $msg, $user_profile_form);
}

/**
 * Deletes one or more records
 * @param array - An array of unique category id numbers
 * @param string - The current author option
 */

function publishUsers($bid, $publish, $option)
{
	global $database, $my,$user_configuration,$mosConfig_mailfrom;
	$catid = mosGetParam($_POST, 'catid', array (0));
	if (!is_array($bid) || count($bid) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}
	$bids = implode(',', $bid);

	$database->setQuery("select * from #__simplemembership_users ".
						"\nWHERE id IN ($bids)");
	$list_id = $database->loadObjectList();

	$str_id = '';

	foreach($list_id as $item_id)
	{
		$arr[] = $item_id->joomid;
	}
	$str_id = implode(',', $arr);

	$database->setQuery("UPDATE #__users SET block='$publish' ".
						"\nWHERE id IN ($str_id)");

	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	$database->setQuery("UPDATE #__simplemembership_users SET block='$publish' ".$date_string.
						"\nWHERE id IN ($bids)");

	if($publish)
	foreach($list_id as $item_id)
	{
		JUTility::sendMail($mosConfig_mailfrom,'simplemembership joomla',$item_id->email , 'account enabled',stripslashes($user_configuration['user_enabled_msg']),1);
	}

	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	if (count($bid) == 1) {
		$row = new mos_alUser($database);
		$row->checkin($bid[0]);
	}
	mosRedirect("index.php?option=$option");
}

function approveUsers($bid, $publish, $option)
{

	global $database, $my,$user_configuration,$mosConfig_mailfrom;
	$catid = mosGetParam($_POST, 'catid', array (0));
	if (!is_array($bid) || count($bid) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}
	$bids = implode(',', $bid);

	$date = date('Y-m-d');

	$date_string = '';

	if($publish==0)
	{
		$date = date('Y-m-d');
		$date_string = ",last_approved='$date'";
	}

	$database->setQuery("select * from #__simplemembership_users ".
						"\nWHERE id IN ($bids)");
	$list_id = $database->loadObjectList();

	$str_id = '';

	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	$database->setQuery("UPDATE #__simplemembership_users SET user_type='valid', approved='$publish' ".$date_string.
						"\nWHERE id IN ($bids)");

	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	$user = new JUser();
	if(!$publish){
	  foreach($list_id as $item_id)
	  {
		  $advgroup_id = $item_id->advgroup_id;
		  if($advgroup_id!=0)
		  {
// 			  $query="select * from  #__simplemembership_groups where id='$advgroup_id'";
// 			  $database->setQuery($query);
// 			  $cur_advgroup = $database->loadObject();
        $query ="SELECT ug.id FROM #__usergroups AS ug
        LEFT JOIN #__simplemembership_group_joomgroup as sgj ON ug.id=sgj.jgroup_id 
        WHERE sgj.mgroup_id=(SELECT advgroup_id FROM #__simplemembership_users WHERE id=".$item_id->id.")";
        $database->setQuery($query);
        $want_groups=$database->loadResultArray();
        $query ="SELECT ug.title FROM #__usergroups AS ug
        LEFT JOIN #__simplemembership_group_joomgroup as sgj ON ug.id=sgj.jgroup_id 
        WHERE sgj.mgroup_id=(SELECT advgroup_id FROM #__simplemembership_users WHERE id=".$item_id->id.")";
        $database->setQuery($query);
        $want_groups_name=$database->loadResultArray();
        $want_groups_name=implode(",",$want_groups_name);
        echo $database->getErrorMsg();
        $want_groups=array_combine($want_groups,$want_groups);
// 			print_r($want_groups);exit;
        $user->load($item_id->joomid);
			  $user->groups=$want_groups;/*array($cur_advgroup->acl_gid => $cur_advgroup->acl_gid);*/
    	  $user->usertype = $want_groups_name;
			  $user->save();
// 			  $query = "UPDATE #__simplemembership_users SET usertype='$cur_advgroup->acl_group', gid='$cur_advgroup->acl_gid', ".
// 		  "want_group='$cur_advgroup->acl_group', want_gid='$cur_advgroup->acl_gid'".
// 						  "\nWHERE id='".$item_id->id."'";
// 			  $database->setQuery($query);
// 			  $database->query();
		  }
		  
		  JUTility::sendMail($mosConfig_mailfrom,'simplemembership joomla',$item_id->email , 'account approved',stripslashes($user_configuration['user_approve_msg']),1);
      
      $query ="UPDATE #__simplemembership_users SET sent_approved='1' WHERE id=".$item_id->id;
      $database->setQuery($query);
      $database->query();
    }
  }

	if($publish)
	{

		foreach($list_id as $item_id)
		{
			if($item_id->advgroup_id!=0)
			{
				//// Default group
				
        $default_group = $user_configuration['default_group']; 
        if(count($default_group)<1) {
          $default_group=array('2'=>'2');
          $default_group_name='Registered';
        }
        else {
          $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ( ".implode(",",$default_group)." )";
          $database->setQuery($query);
          $default_group_name=$database->loadResultArray();
          $default_group_name=implode(",",$default_group_name);
          $default_group=array_combine($default_group,$default_group);
        }
        
        
        
// 				$default_group = $user_configuration['default_group'];
//           if(count($default_group)<1) $default_group=array('2'=>'2');
//           else $default_group=array_combine($default_group,$default_group);
// 				if($default_group=='')
// 				$default_group = 2;
// 				$query = "select title from #__usergroups where id='$default_group'";
// 				$database->setQuery($query);
// 				$default_group_inf = $database->loadResult();
// 					
// 				if(!$default_group )
// 				{
// 					$default_group_id = 2;
// 					$default_group_name = 'Registered';
// 				}
// 				else
// 				{
// 					$default_group_id = $default_group;
// 					$default_group_name = $default_group_inf;
// 				}
// 					
				//// End Default group

				$user->load($item_id->joomid);
				$user->groups=$default_group;
        $user->usertype = $default_group_name;
				$user->save();

// 				$query = "UPDATE #__simplemembership_users SET usertype='$default_group_name', gid='$default_group_id'".
// 						"\nWHERE id='".$item_id->id."'";
// 				$database->setQuery($query);
// 				$database->query();
			}
			JUTility::sendMail($mosConfig_mailfrom,'simplemembership joomla',$item_id->email , 'account disapproved',stripslashes($user_configuration['user_disapprove_msg']),1);
		}
	}
	if (count($bid) == 1) {
		$row = new mos_alUser($database);
		$row->checkin($bid[0]);
	}
	mosRedirect("index.php?option=$option");
}

/**
 * Moves the order of a record
 * @param integer - The increment to reorder by
 */

function ordersimplememberships($bid, $inc, $option)
{
	global $database;
	$user = new mos_alUser($database);
	$user->load($bid);
	$user->move($inc);
	mosRedirect("index.php?option=$option");
}

/**
 * Cancels an edit operation
 * @param string - The current author option
 */

function cancelsimplemembership($option)
{
	global $database;
	$row = new mos_alUser($database);
	$row->bind($_POST);
	$row->checkin();
	mosRedirect("index.php?option=$option");
}

function configure_save_frontend($option)
{
	global $my, $user_configuration;

	//*********   begin add send mail for admin   *******
	$user_configuration['acl_group_set_email']['show'] = mosGetParam($_POST, 'acl_group_set_email_show', 0);

  $str = '';
  $supArr = JArrayHelper::getValue($_POST, 'other_profiles', 0);
    for($i = 0;$i<count($supArr);$i++){
        $str.=$supArr[$i].',';
    }
  $str = substr($str,0,-1);
  $user_configuration['other_profiles'] = $str;
	$user_configuration['activationmsg'] = addslashes($_POST['activationmsg']);
	$user_configuration['preregister'] = addslashes($_POST['preregister']);

	mos_alUserOthers :: setParams();
	configure_frontend($option);
}

function configure_save_backend($option)
{
	global $my, $user_configuration;

//	print_r($_POST);exit;
	$user_configuration['useradd_notification_email'] = mosGetParam($_POST, 'useradd_notification_email', "");//back--1

  $str = '';
  $supArr = JArrayHelper::getValue($_POST, 'default_group', 0);
    for($i = 0;$i<count($supArr);$i++){
        $str.=$supArr[$i].',';
    }
  $str = substr($str,0,-1);
	$user_configuration['default_group'] = $str;
	$user_configuration['admin_created_msg'] = addslashes($_POST['admin_created_msg']);
	$user_configuration['user_created_msg'] = addslashes($_POST['user_created_msg']);
	$user_configuration['user_enabled_msg'] = addslashes($_POST['user_enabled_msg']);
	$user_configuration['user_approve_msg'] = addslashes($_POST['user_approve_msg']);
	$user_configuration['user_disapprove_msg'] = addslashes($_POST['user_disapprove_msg']);

	mos_alUserOthers :: setParams();
	configure_backend($option);
}

function configure_frontend($option)
{
	global $my, $user_configuration, $acl, $mosConfig_live_site, $mosConfig_absolute_path;
        $mosHTML = new mosHTML();
	$yesno[] = $mosHTML -> makeOption('1', _SIMPLEMEMBERSHIP_YES);
	$yesno[] = $mosHTML -> makeOption('0', _SIMPLEMEMBERSHIP_NO);


    $group_children_tree = array ();
    include_once($mosConfig_absolute_path.'/administrator/components/com_users/models/groups.php'); 
    $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
    foreach ($g = $model->getItems() as $k => $v){ // $g contains basic usergroup items info
        $group_title = '.';
        for ($i=1; $i<=$g[$k]->level; $i++){
            $group_title .= '-';
        }
        $group_title .= '-'.$g[$k]->title;
        $group_children_tree[] = $mosHTML -> makeOption($g[$k]->id, $group_title);
    }
    $gtree[] = $mosHTML -> makeOption('-2', 'Everyone');
    $gtree = array_merge ( $gtree, $group_children_tree);
    
    $f="";
    $s = explode(',',$user_configuration['other_profiles']);
    $mosHTML = new mosHTML();
    for($i = 0;$i<count($s);$i++) $f[] = $mosHTML->makeOption($s[$i]);    
    
    $lists['other_profiles'] = $mosHTML->selectList($gtree, 'other_profiles[]', 'size="9" multiple="" ', 'value', 'text', $f);

    /*$gtree[] = mosHTML :: makeOption('-2', 'Everyone');
    //$gtree = $acl->get_group_children_tree( null, 'USERS', false );
    $group_children_tree = array ();
    $gtree = array_merge ( $gtree, $group_children_tree); 
    $lists = array ();

    $f="";
    $s = explode(',',$user_configuration['acl_group_set']);
    for($i = 0;$i<count($s);$i++)

    $f[] = mosHTML::makeOption($s[$i]);
    $lists['acl_group_set'] = mosHTML::selectList($gtree, 'acl_group_set[]', 'size="4" multiple="multiple"', 'value', 'text', $f);*/

	//********   begin add send mail for admin  ******************

	$lists['acl_group_set_email']['show'] = $mosHTML -> RadioList($yesno, 'acl_group_set_email_show', 'class="inputbox"', $user_configuration['acl_group_set_email']['show'], 'value', 'text');

	$lists['preregister'] = stripslashes( $user_configuration['preregister']);
	$lists['activationmsg'] = stripslashes( $user_configuration['activationmsg']);

	//add for show subcategory
        $htmlSimplemembership = new HTML_simplemembership();
	$htmlSimplemembership -> showConfiguration_frontend($lists,$option);
}

function configure_backend($option)
{
	global $my, $user_configuration, $acl, $mosConfig_live_site, $mosConfig_absolute_path;
	$lists = array ();
	$lists['useradd_notification_email'] = '<input type="text" name="useradd_notification_email" value="'.$user_configuration['useradd_notification_email'].'" class="inputbox" size="50" maxlength="50" title="" />';
	//get host List

// $gtree[] = mosHTML :: makeOption('-2', 'Everyone');
// 	//$gtree = $acl->get_group_children_tree( null, 'USERS', false );
// 		//$gtree = $acl->get_group_children_tree( null, 'USERS', false );
// $group_children_tree = array ();
// $gtree = array_merge ( $gtree, $group_children_tree); 
//   $lists['default_group'] = mosHTML::selectList($gtree, 'default_group', 'size="4" ', 'value', 'text', $user_configuration['default_group']);

  $group_children_tree = array ();
  include_once($mosConfig_absolute_path.'/administrator/components/com_users/models/groups.php'); 
  $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
  $mosHTML = new mosHTML ();
  foreach ($g = $model->getItems() as $k => $v) { // $g contains basic usergroup items info
    $group_title = '.';
    for ($i=1; $i<=$g[$k]->level; $i++) 
    {
      $group_title .= '-';
    }
    $group_title .= '-'.$g[$k]->title;
    $group_children_tree[] = $mosHTML -> makeOption($g[$k]->id, $group_title);
  }
  $gtree[] = $mosHTML -> makeOption('-2', 'Everyone');
  $gtree = array_merge ( $gtree, $group_children_tree);
  $f="";
  $s = explode(',',$user_configuration['default_group']);
  $mosHTML = new mosHTML ();
  for($i = 0;$i<count($s);$i++) $f[] = $mosHTML ->makeOption($s[$i]);    
  
  $lists['default_group'] = $mosHTML ->selectList($gtree, 'default_group[]', 'size="4" multiple="" ', 'value', 'text', $f);

	$lists['jcron_link'] = $mosConfig_live_site.'/index.php?option=com_simplemembership&task=advexpire';
	$lists['admin_created_msg'] = stripslashes( $user_configuration['admin_created_msg']);
	$lists['user_created_msg'] = stripslashes( $user_configuration['user_created_msg']);
	$lists['user_enabled_msg'] = stripslashes( $user_configuration['user_enabled_msg']);
	$lists['user_approve_msg'] = stripslashes( $user_configuration['user_approve_msg']);
	$lists['user_disapprove_msg'] = stripslashes( $user_configuration['user_disapprove_msg']);
        
        $htmlSimplemembership = new HTML_simplemembership();
	$htmlSimplemembership -> showConfiguration_backend($lists, $option );
}
?>
