<?php

/* displays user's account settings */

//delete user
if(isset($_POST['deleteUserId']))
{
	$iDeletedUserId = $_POST['deleteUserId'];
	if(isAdmin($iDeletedUserId))
	{
		echo getError('Il est impossible de supprimer un compte administrateur');
	}
	else
	{
		$sDeletedUserName = getTextFromId(USER_TABLE, $iDeletedUserId);
		deleteRow(USER_TABLE, $iDeletedUserId);
		addFeed('DELETE', $iDeletedUserId , USER_TABLE, $sDeletedUserName, '');
	}
}

//modify user account
$iSelectedUserId = isset($_POST['studentId'])?$_POST['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']));

//Admin menu : student selection
$sPromoteAdmin = '';
$bIsSelectedUserAdmin = isAdmin($iSelectedUserId);
if($bAdmin)
{
	$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>
	<form action="?page=account" method="post" name="getEleve">
		<table>
			<tr>
				<td class="top-left-rounded bottom-left-rounded">El&egrave;ve</td>
				<td class="top-right-rounded bottom-right-rounded">
					<select name="studentId" onchange="document.forms['getEleve'].submit();">
					<?php
					$asUsers = selectRows(array('from'=>USER_TABLE, 'orderBy'=>array('class'=>'asc', 'user_last_name'=>'asc')));
					foreach($asUsers as $asUser)
					{
						echo	'<option value="'.$asUser['id_'.USER_TABLE].'"'.(($iSelectedUserId==$asUser['id_'.USER_TABLE])?' selected="selected"':'').'>
									'.$asUser['grade'].GRADE_CLASS_SEPARATOR.$asUser['class'].' - '.ucwords($asUser['user_last_name'].' '.$asUser['user_first_name']).
								'</option>'."\n";
					}
					?>
					</select>
				</td>
			</tr>
			<tr>
				<td colspan="2" class="blank">
					<input type="button" value="Supprimer ce compte" onclick="if(confirm('Etes-vous sur de vouloir supprimer le compte de <?php echo $asSelectedUserInfo['user_last_name']." ".$asSelectedUserInfo['user_first_name']; ?> ?'))document.deleteUser.submit();" />
				</td>
			</tr>
		</table>
	</form>
	<?php
}

//forms display : info and password modifications
if((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');" value="Annuler">  <input type="submit" value="Changer le mot de passe">
				</td>
			</tr>
		</table>
	</form>
	<br />
<?php
}
else
{
?>
	<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 ucwords(isset($_POST['firstname'])?$_POST['firstname']:$asSelectedUserInfo['user_first_name']); ?>" /></td>
			</tr>
			<tr>
				<td>Nom de famille</td>
				<td><input type="text" name="login" value="<?php echo ucwords(isset($_POST['login'])?$_POST['login']:$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=logon');" 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
} 
?>