<?php
session_start();
?>
<?
	include("user.php");
	include("login.php");
	include("class.php");
//	session_start();
	
	if (!$_SESSION['user'])
		header("Location: index.php");
		
	if ($_GET['inactive'] == 1)
		$active = false;
	else
		$active = true;
		
	if ($_POST['fname']) {
		if (confirmPassword($_SESSION['user'], $_POST['adduserpass'])) {
			$chars = "abcdefghijkmnopqrstuvwxyz023456789";
			srand((double)microtime()*1000000);
			$i = 0;
			$randpass = '' ;
		
			while ($i <= 7) {
				$num = rand() % 33;
				$tmp = substr($chars, $num, 1);
				$randpass = $randpass.$tmp;
				$i++;
			}
			
			if (!get_magic_quotes_gpc()) {
				$fname = addslashes($_POST['fname']);
				$lname = addslashes($_POST['lname']);
				$email = addslashes($_POST['email']);
				$worked = addUser($fname, $lname, $email, $randpass, $_POST['adminlevel']);
				$newuser = getUser('Email', $email);
			}
			else {
				$worked = addUser($_POST['fname'], $_POST['lname'], $_POST['email'], 
										  $randpass, $_POST['adminlevel']);
				$newuser = getUser('Email', $_POST['email']);
			}
										  
			if ($_POST['addtoclass'])
				enrollUser($_POST['addtoclass'], $newuser['ID']);
			
			if ($worked) {
				$curUser = getUserName($_SESSION['user']);
				$curName = $curUser['FirstName']." ".$curUser['LastName'];
				$address = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
				$address = substr($address, 0, -9);
				$body = "Hello, ".$_POST['fname']."!  You have been added as a user to Syllogistek, the".
						" Argument Library Software, by ".$curName.".  Please login to the system ".
						"at ".$address.".  The password generated for you is:\n\n\t".$randpass."\n\nYou".
						" may change this password from your user information screen once you log in.".
						"\n\n\nThis message has been generated automatically.  Please do not reply to ".
						"this message.";
				$body = wordwrap($body, 70);
				mail($_POST['email'], "Welcome to Syllogistek!", $body, "From: donotreply@syll.net");
				$readytype = 1;
			}
			else
				$readytype = 2;
		}
		else
			$readytype = 3;			
	}		
	
	if ($_POST['deleteID']) {
		if (confirmPassword($_SESSION['user'], $_POST['deletepass'])) {
			if ($_POST['deleteID'] > 0)
				activateUser($_POST['deleteID'], true);
		    else
				activateUser(-$_POST['deleteID'], false);
		}
		else
			$readytype = 4;
	}
	
	if ($_POST['selClass']) {
		$classid = $_POST['selClass'];
		$userid = $_POST['curUser'];
		$enrolled = enrollUser($classid, $userid);
		if ($enrolled)
			$readytype = 5;
		else
			$readytype = 6;
	}
	
	if ($_POST['searchsubmit'] == 'View' && $_POST['sortclass'] != 0) {
		$myusers = getRoster_Inst($_POST['sortclass']);
		$classid = $_POST['sortclass'];
	}
	else {
		$_POST['sortclass'] = 0;
		if ($_POST['searchsubmit'] == 'Search' && $_POST['input']) {
				$name = $_POST['input'];
				$firstName = strtok($name, " ");
				$lastName = strtok(" ");
				if (!$lastName)
					$lastName = $firstName;
				$myusers = searchUsers($firstName, $lastName);
		}
		else if ($_SESSION['admin'] == -2)
			$myusers = getAllUsers($active);
		else
			$myusers = array();
	}
	
	if ($_SESSION['admin'] == -2)
		$classes = getActiveClasses(true, null);
	else {
		$classes = getActiveClasses(true, $_SESSION['user']);
		if (count($myusers) == 0) {
			$myusers = getRoster_Inst($classes[0]['ID']);
			$classid = $classes[0]['ID'];
		}
	}
	
	$total = count($myusers);
	$usersPerPage = 10;
	$numPages = ceil($total / $usersPerPage);
?>
<!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=iso-8859-1" />
<title>User Database</title>

<script language='javascript'>
<!--
	var usersPerPage = <? echo $usersPerPage; ?>;
	var numUsers = <? echo $total; ?>;
	var numPages = <? echo $numPages; ?>;
	var currentPage = 0;
	
	document.onmousemove = getMouseLoc;
	var mouseX = 0;
	var mouseY = 0;
	
	window.onload = createPageLinks;
	
	function createPageLinks() {
		if (this.numPages > 0)
			this.currentPage = 1;
	    var inner = "";
	    if (this.numPages > 1) {
			inner += "&lt;&lt;Prev &nbsp;";
			inner += "1-" + this.usersPerPage + " &nbsp;";
			for (var i = 1; i < this.numPages; i++) {
				inner += "<a href='javascript:changePage(" + 
					(i+1) + ")'>" + (i*usersPerPage+1) + "-";
				if ((i+1)*usersPerPage > numUsers) {
					if (numUsers == (i*usersPerPage+1))
						inner = inner.substring(0, inner.length-1);
					else
						inner += "" + numUsers;
				}
				else
					inner += "" + ((i+1)*usersPerPage);
				inner += "</a> &nbsp;";
			}
			inner += "<a href='javascript:changePage(2)'>Next&gt;&gt;</a>";
		}
		document.getElementById("pageSelect").innerHTML = inner;
		document.getElementById("pageSelect2").innerHTML = inner;
		document.getElementById("page1").style.display = 'block';
	}
	
	function changePage(page) {
		for(var i = 1; i < this.numPages + 1; i++)
			document.getElementById("page" + i).style.display="none";
			
		document.getElementById("page" + page).style.display="block";
		var inner = "";
		/*
		 * If the first page is selected, then the page links are built
		 * in a similar fashion to the createPageLinks method.
		 */
		if (page == 1) {
			inner += "&lt;&lt;Prev &nbsp;";
			inner += "1-" + this.usersPerPage + " &nbsp;";
			for (var i = 1; i < this.numPages; i++) {
				inner += "<a href='javascript:changePage(" + 
					(i+1) + ")'>" + (i*usersPerPage+1) + "-";
				if ((i+1)*usersPerPage > this.numUsers) {
					if (numUsers == (i*usersPerPage+1))
						inner = inner.substring(0, inner.length-1);
					else
						inner += "" + numUsers;
				}
				else
					inner += "" + ((i+1)*usersPerPage);
				inner += "</a> &nbsp;";
			}
			inner += "<a href='javascript:changePage(" +
				(page+1) + ")'>Next&gt;&gt;</a>";
		}
		/*
		 * If the page is in the middle, then the links are
		 * built up until 1 less than page at which point the
		 * current page link is plaintext.  The remainder of
		 * the pages are built as links.
		 */
		else if (page < this.numPages) {
			inner += "<a href='javascript:changePage(" +
				(page-1) + ")'>&lt;&lt;Prev</a> &nbsp;";
			for (var i = 0; i < page-1; i++) {
				inner += "<a href='javascript:changePage(" + 
					(i+1) + ")'>" + (i*usersPerPage+1) + 
					"-" + ((i+1)*usersPerPage) + 
					"</a> &nbsp;";
			}
			inner += "" + ((page-1)*this.usersPerPage+1) + "-" + 
				(page*this.usersPerPage) + " &nbsp;";
			for (var i = page; i < this.numPages; i++) {
				inner += "<a href='javascript:changePage(" + 
					(i+1) + ")'>" + (i*usersPerPage+1) + "-";
				if ((i+1)*usersPerPage > this.numUsers) {
					if (numUsers == (i*usersPerPage+1))
						inner = inner.substring(0, inner.length-1);
					else
						inner += "" + numUsers;
				}
				else
					inner += "" + ((i+1)*usersPerPage);
				inner += "</a> &nbsp;";
			}
			inner += "<a href='javascript:changePage(" +
				(page+1) + ")'>Next&gt;&gt;</a>";
		}
		/*
		 * If the page is the last one, then all the links
		 * are built up until the final page, which along with
		 * the "Next" link are merely plaintext.
		 */
		else if (page == this.numPages) {
			inner += "<a href='javascript:changePage(" +
				(page-1) + ")'>&lt;&lt;Prev</a> &nbsp;";
			for (var i = 0; i < this.numPages-1; i++) {
				inner += "<a href='javascript:changePage(" + 
					(i+1) + ")'>" + (i*usersPerPage+1) + 
					"-" + ((i+1)*usersPerPage) + 
					"</a> &nbsp;";
			}
			inner += "" + ((page-1)*this.usersPerPage+1);
			if (this.numUsers != ((page-1)*this.usersPerPage+1))
				inner += "-" + this.numUsers;
			inner += " &nbsp;Next&gt;&gt;";
		}
		this.currentPage = page;
		document.getElementById("pageSelect").innerHTML = inner;
		document.getElementById("pageSelect2").innerHTML = inner;
	}
	
	function addUser(show) {
		if (show)
			document.getElementById('add').style.display = 'block';
		else {
			document.getElementById('add').style.display = 'none';
			document.getElementById('noname').style.display = 'none';
			document.getElementById('noemail').style.display = 'none';
			document.getElementById('adduserpassM').style.display = 'none';
		}
	}
	
	function checkAddUser() {
		var email = document.getElementById('email').value;
		index = email.indexOf('@');
		var wrong = index <= 0 || index == (email.length-1)
		var fname = document.getElementById('fname').value;
		var lname = document.getElementById('lname').value;
		var noNames = !fname || !lname;
		if (wrong || noNames || noMatch) {
			if (wrong)
				document.getElementById('noemail').style.display = 'block';
			if (noNames)
				document.getElementById('noname').style.display = 'block';
			return false;
		}
		return true;
	}
	
	function deactivateUser(userID, deactivate) {
		if (deactivate)
			userID = -userID;
		document.getElementById('deleteID').value = userID;
		div = document.getElementById('confirm');
		div.style.left = (mouseX+10)+"px";
		div.style.top = mouseY+"px";
		div.style.display = 'block';
	}
	
	function confirmDeletePass() {
		document.getElementById('yesdelete').disabled = false;
		div = document.getElementById('confirm');
		div2 = document.getElementById('confirm2');
		div2.style.left = div.style.left;
		div2.style.top = div.style.top;
		div2.style.display = 'block';		
	}
	
	function closeConfirm() {
		document.getElementById('yesdelete').disabled = true;
		document.getElementById('confirm').style.display = 'none';
		document.getElementById('confirm2').style.display = 'none';
	}
	
	function enrollUser(theclass, user) {
		document.getElementById('curUser').value = user;
		document.getElementById('selClass').value = theclass;
	}
	
	function checkEnrollment() {
		user = document.getElementById('curUser').value;
		aclass = document.getElementById('selClass').value;
		return (user > 0) && (aclass > 0);
	}
	
	function getMouseLoc(e) {
		if (!e) var e = window.event;
		if (e.pageX || e.pageY) 	{
			mouseX = e.pageX;
			mouseY = e.pageY;
		}
		else if (e.clientX || e.clientY) 	{
			mouseX = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			mouseY = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}
	}

// -->
</script>

</head>

<? include("header.php"); ?>

<span style='color:#FF3300; display:<? if ($readytype == 1) echo("block"); else echo("none"); ?>'>
The user <? echo($_POST['fname']." ".$_POST['lname']); ?> has been successfully added to the database.<br>
An email will be sent to <? echo($_POST['fname']); ?> with the login information.</span>

<span style='color:#FF3300; display:<? if ($readytype == 2) echo("block"); else echo("none"); ?>'>
Error in database query.<br>Please ensure that information is correct and the email entered is not 
already in use by another user.<br>If problem persists, please request that your server's database 
manager inspect it.</span>

<span style='color:#FF3300; display:<? if ($readytype == 3) echo("block"); else echo("none"); ?>'>
User has not been added because validation failed.</span>

<span style='color:#FF3300; display:<? if ($readytype == 4) echo("block"); else echo("none"); ?>'>
User has not been deactivated because validation failed.</span>

<span style='color:#FF3300; display:<? if ($readytype == 5) echo("block"); else echo("none"); ?>'>
User has been successfully enrolled.</span>

<span style='color:#FF3300; display:<? if ($readytype == 6) echo("block"); else echo("none"); ?>'>
Enrollment has failed!</span>

<form id='search1' name='search1' submit='users.php' method='POST' >
<div style='position:relative; left:40px'>
	<br />
	<?
		if ($_SESSION['admin'] == 0)
			echo("Select a class roster to view.");
		else
			echo("Search for a specified name or select a class roster.");
	?>
	<table>
		<?
			if ($_SESSION['admin'] != 0) {
		?>
			<tr>
				<td align='right'><input type='text' id='input' name='input' size='26'/></td>
				<td align='left'><input type='submit' name='searchsubmit' value='Search' /></td>
			</tr>
		<? 	} ?>
		<tr>
			<td align='right'>
				<select id='sortclass' name='sortclass'>
				<?
					if ($_SESSION['admin'] == -2)
						echo("<option value='0'>No Class</option>");
					$max = count($classes);
					for ($n = 0; $n < $max; $n++) {
						echo("<option value='".$classes[$n]['ID']."' ");
						if ($_POST['sortclass'] == $classes[$n]['ID'])
							echo("SELECTED");
						echo(">".$classes[$n]['CourseName']."</option>");
					}
				?>
				</select>
			</td>
			<td><input type='submit' name='searchsubmit' value='View' /></td>
		</tr>
	</table>
</div>
</form>

<span style='position:relative; left:40px; top:8px; font-variant:small-caps;'>
	<? 	if ($_SESSION['admin'] <= -1) { ?>
    <a href='users.php'>Show all active users</a><br />
	<a href='users.php?inactive=1'>Show all inactive users</a><br />
	<? 	}
		if ($_SESSION['admin'] != 0)
			echo("<a href='javascript:addUser(true)'>Add a new user</a><br />");
	?>
	<br />
</span>
	
<table id='add' style='float:right; z-index:2; position:absolute; left:12em; top:6em; 
		   			   display:none; background:#FFFFCC; padding:5px;' 
	   border='1' cellpadding='5px'>
	<tr><td>
		<h3 style='position:relative; left:15px;'>Add New User</h3>
		<form id='adduserform' name='adduserform' submit='users.php' method='POST' onSubmit='return checkAddUser()'>
		<table>
			<tr>
				<td align='right' style='font-weight:bold;'>First Name:</td>
				<td align='left'><input type='text' id='fname' name='fname' /></td>
				<td align='left'><div id='noname' style='display:none; color:#FF3300'>Name fields required!</div></td>
			</tr>
			<tr>
				<td align='right' style='font-weight:bold;'>Last Name:</td>
				<td align='left'><input type='text' id='lname' name='lname'  /></td>
			</tr>
			<tr>
				<td align='right' style='font-weight:bold;'>Email:</td>
				<td align='left'><input type='text' id='email' name='email'  /></td>
				<td align='left'><div id='noemail' style='display:none; color:#FF3300;'>Invalid email!</div></td>
			</tr>
			<tr>
				<td align='right' style='font-weight:bold;'>Enroll in Class:</td>
				<td align='left'><select id='addtoclass' name='addtoclass' />
				<option value='0'>Do Not Enroll</option>
				<?
					if ($_SESSION['admin'] == 1)
						$classes = getStudentAdminClasses($_SESSION['user']);
					foreach($classes as $c)
						echo("<option value='".$c['ID']."'>".$c['CourseName']."</option>");
				?>
				</select></td>
			</tr>
			<tr>
				<td align='right' style='font-weight:bold;'>Admin:</td>
				<td align='left'>
					<select id='adminlevel' name='adminlevel'>
					<option value='0'>Student</option>
					<option value='-1'>Instructor</option>
					</select></td>
			</tr>
			<tr>
				<td colspan='3' style='font-weight:bold;'><b>Confirm your password to continue.</b></td>
			</tr>
			<tr>
				<td align='right' style='font-weight:bold;'>Password:</td>
				<td align='left'><input type='password' id='adduserpass' name='adduserpass' /></td>
			</tr>
			<tr>
				<td></td>
				<td align='left'><input type='submit' value='Add User' />
								 <input type='reset' value='Cancel' onclick='addUser(false)' /></td>
			</tr>
		</table>
		</form>
	</td></tr>

</table>

<div id='pageSelect' style='font-variant:small-caps; position:relative; left:25px; top:10px'></div>
<form id='enrollment' name='enrollment' submit='user.php' method='POST' onsubmit='return checkEnrollment()'>
	<input type='hidden' name='curUser' id='curUser' value='0' />
	<input type='hidden' name='selClass' id='selClass' value='0' />
<?
	for($j = 0; $j < $numPages; $j++) {
		echo("<div id='page".($j+1)."' style='display:none; position:relative; left:10px; top:10px'>");
		echo("<table cellpadding='6px'>");
		for ($i = 0; $i < $usersPerPage; $i++) {
			$index = ($usersPerPage*$j)+$i;
			if ($index == $total)
				break;
			echo("<tr><td>");
			echo("<b>".$myusers[$index]['FirstName']." ".$myusers[$index]['LastName']."</b> - ");
			$thisadmin = $myusers[$index]['IsAdmin'];
			if ($thisadmin == -2)
				echo("System Administrator");
			else if ($thisadmin == -1)
				echo("Instructor");
			else if ($thisadmin >= 0)
				echo("Student");
			echo("<br>Email: <a href='mailto:".$myusers[$index]['Email']."'>".$myusers[$index]['Email']."</a><br>");
			if ($thisadmin >= 0 && $_SESSION['admin'] == -2) {
				echo("Enroll in Class: ");
				$classes = getNotEnrolled($myusers[$index]['ID']); 
?>
		<select id='classlist' name='classlist' 
				onchange='enrollUser(this.options[this.selectedIndex].value,<? echo $myusers[$index]['ID']; ?>)' >
			<option value='0'>No Class</option>
<?
				foreach($classes as $c)
					echo("<option value='".$c['ID']."'>".$c['CourseName']."</option>");
?>
		</select> <input type='submit' value='Go' /><br />
<?	
			}
			if ($_SESSION['admin'] != 0 && ($_SESSION['admin'] < 0 || hasStudentAdmin($_SESSION['user'], $classid))) {
				echo("<a href='edituser.php?id=".$myusers[$index]['ID']."' style='font-variant:small-caps;'>Edit</a>");
				if ($_SESSION['admin'] < $thisadmin || $_SESSION['admin'] == -2) {
					if ($myusers[$index]['ID'] != $_SESSION['user']) {
						echo(" - <a href='javascript:deactivateUser(".$myusers[$index]['ID']);
						if (isActive($myusers[$index]['ID']))
							echo(", true)' style='font-variant:small-caps;'>Deactivate</a>");
						else
							echo(", false)' style='font-variant:small-caps;'>Activate</a>");
					}
				}
			}
			echo("</td></tr>\n");
		}
		echo("</table></div>\n");
	}
?>
</form>
<div id='pageSelect2' style='font-variant:small-caps; position:relative; left:25px; top:10px'></div>

<div id='confirm' style='position:absolute; z-index:2; display:none; background-color:#FFFFCC;'>
<table border='1'>
<tr><td>
	<form id='predelete' name='predelete'>
		<table cellpadding='2px'>
			<tr><td colspan='2';><b>
				<? if ($active) echo("Deactivate this user?");
				   else 		echo("Activate this user?"); ?>
				</b></td></tr>
			<tr>
				<td><input type='button' id='yes' name='yes' value='Yes' onclick='confirmDeletePass()' /></td>
				<td><input type='button' value='No' onclick='closeConfirm()' /></td>
			</tr>
		</table>
	</form>
</td></tr>
</table>
</div>
<div id='confirm2' style='position:absolute; z-index:3; display:none; background-color:#FFFFCC;'>
<table border='1'>
<tr><td>
	<form id='deleteconfirm' name='deleteconfirm' submit='users.php' method='POST'>
		<table cellpadding='2px'>
			<input type='hidden' id='deleteID' name='deleteID' />
			<tr>
				<td colspan='2'><b>Confirm password.</b></td>
			</tr>
			<tr>
				<td align='right' style='font-weight:bold'>Password:</td>
				<td align='left'><input type='password' id='deletepass' name='deletepass' /></td>
			</tr>
			<tr>
				<td></td>
				<td><input type='submit' id='yesdelete' name='yesdelete' value='Confirm' disabled="disabled" />
				    <input type='reset' value='Cancel' onclick='closeConfirm()' /></td>
			</tr>
		</table>
	</form>
</td></tr>
</table>
</div>
<br />
<? include("footer.php"); ?>
</html>
