<?php

session_start();

require './authenticate.user.php';



require './configuration.php';

require_once './includes/common.functions.php';

require_once ('./classes/database.php');

require_once ('./classes/functions.php');

$sqlObj = new mysqlClass;

$funcObj = new funcClass;

$table = "##super_user";

$ACTION				= 'add';

require_once ('includes/validate.manageusers.php');



if ($_SESSION['IS_USER_CLIENT'])

{

	die ("Sorry, you are not authorized to access this page");

}



//ADD RECORD

if (($_POST['formaction'] == 'add') && (empty($error)))

{

	

	

	# check for duplicate record entry

	$query = "SELECT COUNT(*) FROM $table WHERE EMAIL = '$EMAIL'";

	if ($funcObj->CustomQueryCount($query) == 0)

	{

		$query = "INSERT INTO $table SET FULLNAME='$FULLNAME', EMAIL='$EMAIL', USER_TYPE = '$USER_TYPE', PASSWORD=SHA1('$PASSWORD'), REGISTRATION_DATE=NOW(), IS_ACTIVE='$IS_ACTIVE'";

		

		$insertId = $funcObj->insertQuery($query);

		if ($insertId > 0)

		{

			$message = "Record has been added successfully";

		}

		## RESET THE FORM SO THAT 

		## NO VALUES SHOULD BE SHOWN

		## IF THE FORM IS IN THE ADD

		## MODE

		

		$USER_ID			= NULL;

		$FULLNAME			= NULL;

		$EMAIL 				= NULL;

		$USER_TYPE			= NULL;

		$IS_ACTIVE			= NULL;

	}

	else

	{

		$message = "User already registered with same e-mail. Please try another e-mail address.";

	}

}



//EDIT RECORD

if (($_POST['formaction'] == 'edit') && (empty($error)))

{

	

	

	# check for duplicate record entry

	$query = "SELECT COUNT(*) FROM $table WHERE EMAIL = '$EMAIL'";

	$countRecords = $funcObj->CustomQueryCount($query);

	if ($countRecords < 2)

	{

		$setFields = array();

		$setFields['FULLNAME']	=	$FULLNAME;

		$setFields['EMAIL']		=	$EMAIL;

		$setFields['USER_TYPE']	=	$USER_TYPE;

		$setFields['PASSWORD']	=	$PASSWORD;

		$setFields['IS_ACTIVE']	=	$IS_ACTIVE;

		

		$query = "UPDATE $table SET FULLNAME='$FULLNAME', EMAIL='$EMAIL', USER_TYPE = '$USER_TYPE',"; 

		if (!empty($PASSWORD))

			$query .= " PASSWORD=SHA1('$PASSWORD'), ";

		

		$query .= " REGISTRATION_DATE=NOW(), IS_ACTIVE='$IS_ACTIVE'";

		$query .= " WHERE USER_ID = {$ID}";

		

		$updateId = $funcObj->updateQuery($query);

		if ($updateId == 1)

		{

			$message = "Record has been successfully updated.";

		}

		

		## RESET THE FORM SO THAT 

		## NO VALUES SHOULD BE SHOWN

		## IF THE FORM IS IN THE ADD

		## MODE

		

		$USER_ID			= NULL;

		$FULLNAME			= NULL;

		$EMAIL 				= NULL;

		$USER_TYPE			= NULL;

		$IS_ACTIVE			= NULL;

	}

	else

	{

		$message = "User already registered with same e-mail. Please try another e-mail address.";

	}

}



## if edit is EDIT

# then load values into the form

if ($_GET['action'] == 'edit')

{

	$USER_ID = $_GET['id'];

	$whereFields['USER_ID'] = $USER_ID;

	$resultSet = $funcObj->getRecordDetails($table,$whereFields);

	

	$USER_ID			= trim($funcObj->AppendSlashes($resultSet[0]->USER_ID));

	$FULLNAME			= trim($funcObj->AppendSlashes($resultSet[0]->FULLNAME));

	$EMAIL 				= trim($funcObj->AppendSlashes($resultSet[0]->EMAIL));

	$USER_TYPE 				= trim($funcObj->AppendSlashes($resultSet[0]->USER_TYPE));

	$IS_ACTIVE			= $resultSet[0]->IS_ACTIVE;

	$ACTION				= 'edit';

	

	## current logged in user cannot make itself

	## inactive.

	if ($_SESSION['SUPER_USER_ID'] == $USER_ID)

	{

		$disabled = 'disabled = "disabled"';

	}

}



$superID = 1;



$searchTxt = trim($funcObj->AppendSlashes($_REQUEST['searchbox']));

$searchArray = 'USER_ID,FULLNAME,EMAIL,USER_TYPE,REGISTRATION_DATE';

$status = $_REQUEST['status'];

$User_ID=$_REQUEST['id'];



$doUpdation = false;



switch ($status)

{

	case 'activate': 

		$setField	= 'IS_ACTIVE';

		$setValue	= '1';

		$doUpdation = true;

		break;

	case 'deactivate': 

		$setField	= 'IS_ACTIVE';

		$setValue	= '0';

		$doUpdation = true;

		break;

}	



if($doUpdation)

{

	$whereField = "USER_ID";

	$whereValue = $User_ID;

    $funcObj->UpdateRecord($table,$setField,$setValue,$whereField,$whereValue);

}	



if($_GET['action']=='del')

{

	$whereField = "USER_ID";

	$whereValue = $User_ID;

	$funcObj->DeleteRecord($table,$whereField,$whereValue);

	$message = "User has been deleted successfully";

}

$resultSet = $funcObj->CountAllRecords("$table",$searchTxt,$searchArray);



$records	= $funcObj->fetchParameterValue('SHOW_RECORDS_PER_PAGE');

if($records > 0)

{

	$limit = intval($records);

}

else

{

	$limit = $configAdminPaging;

}



if($_REQUEST['start'])

	$start = $_REQUEST['start'];

else

	$start = 0;

	





$proCount = $resultSet;

$link = './manageusers.php?searchbox='.$_REQUEST['searchbox'];



require_once('./classes/paging.class.php');

$pageObj = new Paging( $proCount, $start , $limit);



/* ACTIVATE THE TAB */

$activeTab = 'Manage Users';

?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Segnant Mailer - Manage Users</title>

<link rel="stylesheet" type="text/css" href="./includes/css/segnantmailer.css" />

<link rel="stylesheet" href="./includes/css/themes/blue/style.css" type="text/css"  media="print, projection, screen" />

<link rel="stylesheet" type="text/css" href="./includes/css/paging.css"  />

<script type="text/javascript" src="./includes/js/jquery-1.3.2.min.js"></script>

<script type="text/javascript" src="./includes/js/jquery.tablesorter.js"></script>

<script type="text/javascript" src="./includes/js/common.jquery.js"></script>

<script type="text/javascript" src="./includes/js/manageusers.jquery.js"></script>

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

</head>

<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

  <tr>

    <td height="79" class="headerbg"><? require_once './includes/inc.header.php' ?>    

    </td>

  </tr>



  <tr>

    <td class="canvas" height="300" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="4">

      <tr>

        <td colspan="2" class="heading" height="50" valign="top">Manage Users</td>

        </tr>

      <tr>

        <td colspan="2" bgcolor="#eaeaea" style="padding:10px;">

                <table cellspacing="0" cellpadding="0" class="tabtable" >

<tr>

<?php

$file = basename($_SERVER['PHP_SELF']);



## ADD EXCEPTIONS



$tabArray = array("<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='manageusers.php'\"> Manage Users </td>",

		"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='clientaccess.php'\"> Manage Client Campaigns </td>");

foreach ($tabArray as $key => $val)

{

	$strpos = strpos($val, $file);



	if ($strpos > 0)

	{

		$newString = str_replace('style="cursor:pointer;"','style="cursor:pointer;" class="active" ',$val);

		echo $newString;

	}

	else

	{

		echo $val;

	}	

}

?>

</tr>

</table>

        <table width="100%" border="0" cellspacing="0" cellpadding="4">

                <tr>

                  <td height="405" bgcolor="#FFFFFF" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="1">

                      <tr>

                        <td class="pageHeading">Manage Users</td>

                      </tr>

                      <tr>

                        <td height="55" valign="top" align="right"><form name="formsearch" method="get" style="margin: 0;" action="">

                            <table border="0" cellspacing="2" cellpadding="2" align="right">

                              <tr>

                                <td nowrap="nowrap"><strong>Search</strong></td>

                                <td><input type="text" name="searchbox" class="textbox" value="<?=$funcObj->RemoveSlashes($_REQUEST['searchbox'])?>" style="margin-bottom: 2px;" size="20" /></td>

                                <td><input type="submit" name="submit" value="Search" class="button size2" /></td>

                              </tr>

                            </table>

                          </form></td>

                      </tr>

                      <?php if (!empty($message))

					  echo "

                      <tr>

                        <td class='message'>$message</td>

                      </tr>

					  ";

					  ?>

                      <tr>

                        <td><table cellspacing="1" class="tablesorter">

                        <thead>

                            <tr>

                              <th width="40" align="center">ID</th>

                              <th align="left">Full Name</th>

                              <th width="25%" align="left">Email</th>

                              <th width="13%" align="center">User Type</th>

                              <th width="16%" align="center">Reg. Date</th>

                              <th width="9%" align="center">Active</th>

                              <th width="13%" align="center">Action</th>

                            </tr>

                            </thead>

                            <tbody>

                            <?php

					$resultSet = $funcObj->FetchRecords("$table",$searchTxt,$searchArray,'USER_ID DESC', $pageObj->start, $pageObj->limit);

					$i=1;

					if(count($resultSet)!=0)

					{

					foreach ($resultSet as $row)

					{

						$i++;

						$inActive = ($row->IS_ACTIVE == 1) ? '' : 'inactive';

						$className="$inActive";

						echo "<tr $className>";

						echo "

						<td align='center'>{$row->USER_ID} </td>

						<td align='left'>{$row->FULLNAME}</td>

						<td align='left'>{$row->EMAIL}</td>

						<td align='center'>{$row->USER_TYPE}</td>

						<td align='center'>". date("M j, Y", strtotime($row->REGISTRATION_DATE)) . "</td>

						<td align='center'>";

						echo ($row->IS_ACTIVE == '1') ? "<img src='images/tick.png' alt='' />" : "<img src='images/cross.gif' alt='' />" ;

						echo "</td>

						<td align='center'>

						<a href='manageusers.php?action=edit&amp;id={$row->USER_ID}'><img src='images/edit.gif' alt='Edit' title='Edit' border='0' /></a>&nbsp;&nbsp;&nbsp;";

						

						// If the user is logged in user then do not allow to delete it.

						if ($_SESSION['SUPER_USER_ID'] != $row->USER_ID)

						{

						echo "<a href='javascript:confirmAction(\"Are you sure you want to delete this user?\",\"manageusers.php?action=del&amp;id={$row->USER_ID}\")'><img src='images/delete.gif' alt='Delete' title='Delete' border='0' /></a>";

						}

						else

						{

							echo "<img src='images/deletenotallowed.gif' alt='Deletion unauthorized' title='Deletion unauthorized' border='0' />";

						}

						echo "</td></tr>

						";

						}

					}

					else

					echo "<tr><td colspan='6' align='center' height='30' valign='middle' class='row0'>No Record Found... </td></tr>";

					?>

                          </tbody>

                          </table></td>

                      </tr>

                      <tr>

                        <td class="pagingTD"><table cellspacing='0' cellpadding='0'  width='100%'>

                            <tr>

                              <td style="text-align:left" class="form_base_header"><span class="pagenav">

                                <?=$pageObj->ShowPageInfo()?>

                                </span></td>

                              <td style="text-align:right" class="form_base_header"><span class="pagenav">

                                <?=$pageObj->Show($link)?>

                                </span></td>

                            </tr>

                          </table></td>

                      </tr>

                    </table></td>

                  <td valign="top" align="left" width="240">                  

                  <form name="formsuperuser" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" style="margin: 0;">

                  <table width="100%" border="0" cellspacing="1" cellpadding="1" class="inputformtable">

                      <tr>

                        <td class="pageHeadingRt"><?php echo ucwords($ACTION) ?> user  

                        <?php if ($ACTION == 'edit') { echo "&nbsp;&nbsp;<small>(<a href='{$_SERVER[PHP_SELF]}'>Cancel Edit</a>)</small>"; } ?>

                        </td>

                      </tr>

                      <tr>

                        <td height="25" valign="top" <?= (! empty ($errorMsg)) ? 'class="error"' : '' ?>><?php

				   errorMessage($errorMsg);

				   ?></td>

                      </tr>

                       <tr>

                        <td class="inputlabel">User Type *</td>

                      </tr>

                      <tr>

                        <td><select name="selusertype" class="textbox" style="width: 175px;">

                        <option value="ADMIN" <?php echo ('ADMIN' == $funcObj->RemoveSlashes($USER_TYPE) ? 'selected="selected"' : '')?>>Admin</option>

                        <option value="CLIENT" <?php echo ('CLIENT' == $funcObj->RemoveSlashes($USER_TYPE) ? 'selected="selected"' : '')?>>Client</option>

                        </select>

                        </td>

                      </tr>

                      <tr>

                        <td class="inputlabel">Name *</td>

                      </tr>

                      <tr>

                        <td><input type="text" name="txtname" class="textbox" value="<?=$funcObj->RemoveSlashes($FULLNAME)?>" maxlength="30" size="30" /></td>

                      </tr>

                      <tr>

                        <td class="inputlabel">Email *</td>

                      </tr>

                      <tr>

                        <td><input type="text" name="txtemail" class="textbox" value="<?=$funcObj->RemoveSlashes($EMAIL)?>" maxlength="35" size="30" /></td>

                      </tr>

                      <tr>

                        <td class="inputlabel">Password *</td>

                      </tr>

                      <tr>

                        <td><input type="password" name="txtpassword" class="textbox" value="" size="30" maxlength="20" /></td>

                      </tr>

						<tr>

                        <td class="inputlabel">Confirm password *</td>

                      </tr>

                      <tr>

                        <td><input type="password" name="txtconfirmpassword" class="textbox" value="" size="30" maxlength="20" /></td>

                      </tr>

                      <tr>

                        <td class="inputlabel">Is Active?</td>

                      </tr>

                      <?php

					  $chkIsActive = $IS_ACTIVE;

					  if ($chkIsActive == 0)

					  {

					  		$yes = '';

							$no = 'checked="checked"';

					  }

					  else

					  {

					  		$yes = 'checked="checked"';

							$no = '';

					  }

					  ?>

                      <tr>

                        <td><input type="radio" name="chkIsActive" value="1" <?php echo $yes ?> <?=$disabled?> />

                          Yes&nbsp;&nbsp;&nbsp;&nbsp;

                          <input type="radio" name="chkIsActive" value="0" <?php echo $no ?> <?=$disabled?> />

                          No</td>

                      </tr>

                      <tr>

                        <td height="35"><input type="submit" name="submit" value="Save" class="button size1" /></td>

                      </tr>

                      <tr>

                        <td height="45">Fields marked with * are mandatory.</td>

                      </tr>

                    </table>

                    <?

					if (! empty($disabled))

						echo '<input type="hidden" name="chkIsActive" value="1" />';

					?>

                    <input type="hidden" name="ID" value="<?php echo $_GET['id']?>" />

                    <input type="hidden" name="formaction" value="<?php echo $ACTION?>" />

                    

                    </form>

                    </td>

                </tr>

              </table></td>

      </tr>

    </table></td>

  </tr>

<? require_once 'includes/inc.footer.php' ?>

</table>

</body>

</html>

