<?php

/* displays user's account settings */

define('DEL_USER_TAG', 'deluser');

//delete users
//TODO plusieurs eleves � la fois
if(isset($_GET['action']) && $_GET['action']=='delusers')
{
	$asDeletedUserNames = array();
	foreach($_POST as $sKey=>$sValue)
	{
		list($DelUserTag, $iUserId) = explode('_', $sKey);
		//pre($DelUserTag.' '.$iUserId, '',true);
		if($DelUserTag==DEL_USER_TAG && is_numeric($iUserId))
		{
			$sDeletedUserName = ucwords(getTextFromId(USER_TABLE, $iUserId));
			if(isAdmin($iUserId))
			{
				addMessage(getError('Il est impossible de supprimer un compte administrateur ('.$sDeletedUserName.')'));
			}
			else
			{	
				deleteRow(USER_TABLE, $iUserId);
				$asDeletedUserNames[] = $sDeletedUserName;
				addFeed('DELETE', $iUserId , USER_TABLE, $sDeletedUserName, '');
			}
		}
	}
	if(count($asDeletedUserNames)>0)
	{
		addMessage(getSuccess('Les comptes suivants ont &eacute;t&eacute; supprim&eacute;s : '.implode(', ', $asDeletedUserNames)));
	}
}


//modify user account
$iSelectedUserId = isset($_REQUEST['studentId'])?$_REQUEST['studentId']:$_SESSION['user'];
$asSelectedUserInfo = selectRow(USER_TABLE, array($iSelectedUserId));

//modifications submit
$bfailedPassModif = false;
if(isset($_POST['submit']))
{
	if($_GET['type']=='pass' && $_POST['pass']!='' && $_POST['oldpass']!='')
	{
		$sErrorMessage = checkPassword($_POST['oldpass'],$asSelectedUserInfo['pass'])?"":'Mot de passe incorrect';
		$sErrorMessage .= ($_POST['pass']==$_POST['pass2'])?"":'Les mots de passe ne sont pas les m&ecirc;mes';
		$bfailedPassModif = ($sErrorMessage!='');
		if($bfailedPassModif)
		{
			echo getError($sErrorMessage);
		}
		else
		{
			updateRow(USER_TABLE, $iSelectedUserId, array('pass'=>encryptPassword($_POST['pass'])));
			echo getSuccess('Mot de passe modifi&eacute;');
		}
	}
	elseif($_GET['type']=='info' && $_POST['login']!='' && $_POST['firstname']!='')
	{
		$sLastName = strtolower($_POST['login']);
		$sFirstName = strtolower($_POST['firstname']);
		
		//Check if someone has already been registered by that name
		$asChangedUserInfo = getUserFromLogin($sLastName, $sFirstName); 
		$bUserAvailable = !$asChangedUserInfo || $iSelectedUserId==$asChangedUserInfo['id_user'];
		if($bUserAvailable)
		{
			$asUserModif = array(	'user_first_name'=>$sFirstName,
									'user_last_name'=>$sLastName,
									'grade'=>$_POST['grade'], 
									'class'=>$_POST['class']);
			if($bAdmin)
			{
				$asUserModif['admin'] = isset($_POST['admin'])?'1':'0';
			}
			
			$asUserInfo = selectRow(USER_TABLE, array($iSelectedUserId));
			updateRow(USER_TABLE, $iSelectedUserId, $asUserModif);
			
			//feed
			$sModifiedUserName = $asUserInfo[USER_TABLE.'_first_name'].' '.$asUserInfo[USER_TABLE.'_last_name'];
			if($sModifiedUserName != $sFirstName.' '.$sLastName)
			{
				addFeed('MODIFY', $sModifiedUserName, USER_TABLE.'_name', $sModifiedUserName, $sFirstName.' '.$sLastName);
			}
			if($asUserInfo['grade']!=$_POST['grade'] || $asUserInfo['class']!=$_POST['class'])
			{
				addFeed('MODIFY', $sModifiedUserName, USER_TABLE.'_class', $asUserInfo['grade'].GRADE_CLASS_SEPARATOR.$asUserInfo['class'], $_POST['grade'].GRADE_CLASS_SEPARATOR.$_POST['class']);
			}
			
			echo getSuccess('Coordonn&eacute;es modifi&eacute;es');
			
			if($iSelectedUserId==$_SESSION['user'])
			{
				setSession($_SESSION['user']);
				if($sLastName!=$asSelectedUserInfo['user_last_name'] || $sFirstName!=$asSelectedUserInfo['user_first_name'])
				{
					echo getWarning(array('Changement de login pour l\'authentification', 'Votre nouveau login est :', 'Nom : '.$sLastName, 'Pr&eacute;nom : '.$sFirstName));
				}
			}
			
		}
		else
		{
			echo getError('Ce nom existe d&eacute;j&agrave; dans la base de donn&eacute;es');
		}
	}
	else
	{
		echo getError('Champs incomplets');
		$bfailedPassModif = ($_GET['type']=="pass");
	}
}

//student class selection / teacher
$sTeacherClass = 'Professeur<input type="hidden" name="grade" value="0"><input type="hidden" name="class" value="0">';
$sStudentClass = getClasses(array('grade' => isset($_POST['grade'])?$_POST['grade']:$asSelectedUserInfo['grade'], 'class' =>  isset($_POST['class'])?$_POST['class']:$asSelectedUserInfo['class']));

//forms display : info and password modifications
if(isset($_GET['type']) && $_GET['type']=="modif" && !isset($_POST['submit']))
{
	$sPromoteAdmin = '';
	$bIsSelectedUserAdmin = isAdmin($iSelectedUserId);
	$asSelectedUserInfo = selectRow(USER_TABLE, array($iSelectedUserId));
	$sPromoteAdmin = 	'<tr>
							<td>Admin</td>
							<td><input type="checkbox" name="admin" '.($bIsSelectedUserAdmin?'CHECKED ':'').' onclick="switchClassType();" /></td>
						</tr>';
?>
	<script type="text/javascript">
		function switchClassType()
		{
			if(document.forms['modif'].elements['admin'].checked)
			{
				replaceInnerText('studentTeacher', '<?php echo $sTeacherClass; ?>');
			}
			else
			{
				replaceInnerText('studentTeacher', '<?php echo $sStudentClass; ?>');
			}
		}
	</script>
	<br />
	<form action="?page=account&type=info" method="post" name="modif">
		<table>
			<tr><th colspan="2" class="top-left-rounded top-right-rounded">Modification de compte</th></tr>
			<tr>
				<td>Pr&eacute;nom</td>
				<td><input type="text" name="firstname" value="<?php echo $asSelectedUserInfo['user_first_name']; ?>" /></td>
			</tr>
			<tr>
				<td>Nom de famille</td>
				<td><input type="text" name="login" value="<?php echo $asSelectedUserInfo['user_last_name']; ?>" /></td>
			</tr>
			<tr>
				<td>Classe</td>
				<td id="studentTeacher">
				<?php echo $bIsSelectedUserAdmin?$sTeacherClass:$sStudentClass; ?>
				</td>
			</tr>
			<?php echo $sPromoteAdmin; ?>
			<tr>
				<td class="bottom-left-rounded">Mot de passe</td>
				<td class="bottom-right-rounded"><input type="button" value="Changer le mot de passe" onclick="pass.submit();" /></td>
			</tr>
			<tr>
				<th colspan="2" class="blank">
					<input type="hidden" value="ok" name="submit" />
					<input type="hidden" value="<?php echo $iSelectedUserId; ?>" name="studentId" />
					<input type="button" name="annuler" onclick="goTo('?page=account_admin');" value="Annuler">&nbsp;&nbsp;<input type="submit" value="Changer les param&egrave;tres" />
				</th>
			</tr>
		</table>
	</form>
	<form action="?page=account&type=pass" method="post" name="pass">
		<input type="hidden" name="studentId" value="<?php echo $iSelectedUserId; ?>" />
	</form>
	<form action="?page=account" method="post" name="deleteUser">
		<input type="hidden" name="deleteUserId" value="<?php echo $iSelectedUserId; ?>" />
	</form>
	<?php
}
elseif((isset($_GET['type']) && $_GET['type']=="pass" && !isset($_POST['submit'])) || $bfailedPassModif)
{
?>
	<br />
	<form action="?page=account&type=pass" method="post" name="updateAccount">
		<table>
			<tr><th colspan="2" class="top-left-rounded top-right-rounded">Changer de mot de passe</th></tr>
			<tr>
				<td>Ancien mot de passe</td>
				<td><input type="password" name="oldpass" /></td>
			</tr>
			<tr>
				<td>Nouveau mot de passe</td>
				<td><input type="password" name="pass" /></td>
			</tr>
			<tr>
				<td class="bottom-left-rounded">Nouveau mot de passe (une nouvelle fois)</td>
				<td class="bottom-right-rounded"><input type="password" name="pass2" /></td>
			</tr>
			<tr>
				<td colspan="2" class="blank">
					<input type="hidden" value="ok" name="submit" />
					<input type="hidden" value="<?php echo $iSelectedUserId; ?>" name="studentId" />
					<input type="button" name="annuler" onclick="goTo('?page=account_admin');" value="Annuler">  <input type="submit" value="Changer le mot de passe">
				</td>
			</tr>
		</table>
	</form>
	<br />
<?php
}
else
{
	$asPreviousEntries = array();
	$asConstraints = array('admin'=>'0');
	$asConstraintsSigns = array('admin'=>'=');
	$sGradeClass = 'Toutes les classes';
	if(isset($_POST['gradeClass']))
	{
		$sGradeClass = $_POST['gradeClass'];
		list($iGrade, $iClass) = explode(GRADE_CLASS_SEPARATOR, $sGradeClass);
		if($iGrade!=0 && $iClass!=0)
		{
			$asConstraints['grade'] = $iGrade;
			$asConstraints['class'] = $iClass;
		}
	}
	
	$asUsers = selectRows(array(
							'from'=>USER_TABLE, 
							'constraint'=>$asConstraints, 
							'orderBy'=>array('class'=>'asc', 'user_last_name'=>'asc')));
	$asStudents = array();
	foreach($asUsers as $asUser)
	{
		if($asUser['class']==0 || $asUser['grade']==0){continue;}
		$asStudents[] = '<tr>
							<td style="text-align:left;"><strong>'.ucwords($asUser['user_last_name']).'</strong> '.ucwords($asUser['user_first_name']).'</td>
							<td>'.$asUser['grade'].GRADE_CLASS_SEPARATOR.$asUser['class'].'</td>
							<td><a href="?page=account_admin&type=modif&studentId='.$asUser['id_'.USER_TABLE].'">Modifier</a></td>
							<td><input type="checkbox" name="'.DEL_USER_TAG.'_'.$asUser['id_'.USER_TABLE].'" /></td>
						</tr>';
	}
	
	$iStudentCount = count($asStudents);
	$sStudents = ($iStudentCount>0)?implode("\n", $asStudents):'<tr><td colspan="4">Aucun utilisateur dans cette classe</td></tr>';
	
	
	//Classes selection
	$asClasses = getListe(array('select'=>array( "CONCAT(grade, '".GRADE_CLASS_SEPARATOR."', class) AS gradeClass", 'grade', 'class'), 
								'from'=>USER_TABLE,
								'constraint'=>"admin=0 AND class<>0 AND grade<>0",
								'groupBy' => 'gradeClass',
								'orderBy'=>array('grade', 'class')));
	$sSelectClasses = getSelect($asClasses, 'gradeClass', '', array('0'.GRADE_CLASS_SEPARATOR.'0'=>'Toutes'), isset($_POST['gradeClass'])?$_POST['gradeClass']:'', 'classSelect');
?>
	<form name="classSelect" method="post" action="?page=<?php echo $sPage;?>">
		<p style="text-align:center;margin-top:30px;">Classe : <?php echo $sSelectClasses; ?></p>
	</form>
	<form method="post" name="deleteUsers" action="?page=<?php echo $sPage;?>&action=delusers">
		<table>
			<tr>
				<th class="top-left-rounded" style="padding:2px 10px;">El&egrave;ve</th>
				<th style="padding:2px 10px;">Classe</th>
				<th style="padding:2px 10px;">Modifier</th>
				<th class="top-right-rounded" style="padding:2px 10px;">Supprimer</th>
			</tr>
			<?php echo $sStudents; ?>
			<tr><th colspan="4" class="bottom-rounded"><?php echo $iStudentCount; ?> &eacute;l&egrave;ve(s) (<?php echo $sGradeClass; ?>)</th></tr>
		</table>
		<div style="text-align:center;margin-top:10px;"><input type="submit" value="Supprimer" /></div>
	</form>
<?php
}
?>