<?php require_once(dirname(__DIR__, 1) . '/config.php');
require_once(BASE_PATH . '/db/idl_connect.php');
echo '<meta charset="utf-8" />';
if(isset($_SESSION['user_droits'])) {
	if($_SESSION['user_droits'][5]<2)
	{
		echo '<p class="noaccess">'.NOMODULE.'<br><a href="../index.php">'.ACCUEIL.'</a></p>';
	}
	else {
		if(isset($_POST['mdpreinit'])) {
			function strToNoAccent($var) {
				$var = str_replace(
					array(
						'à', 'â', 'ä', 'á', 'ã', 'å',
						'î', 'ï', 'ì', 'í', 
						'ô', 'ö', 'ò', 'ó', 'õ', 'ø', 
						'ù', 'û', 'ü', 'ú', 
						'é', 'è', 'ê', 'ë', 
						'ç', 'ÿ', 'ñ',
						'À', 'Â', 'Ä', 'Á', 'Ã', 'Å',
						'Î', 'Ï', 'Ì', 'Í', 
						'Ô', 'Ö', 'Ò', 'Ó', 'Õ', 'Ø', 
						'Ù', 'Û', 'Ü', 'Ú', 
						'É', 'È', 'Ê', 'Ë', 
						'Ç', 'Ÿ', 'Ñ', '-', ' ', '\''
					),
					array(
						'a', 'a', 'a', 'a', 'a', 'a', 
						'i', 'i', 'i', 'i', 
						'o', 'o', 'o', 'o', 'o', 'o', 
						'u', 'u', 'u', 'u', 
						'e', 'e', 'e', 'e', 
						'c', 'y', 'n', 
						'a', 'a', 'a', 'a', 'a', 'a', 
						'i', 'i', 'i', 'i', 
						'o', 'o', 'o', 'o', 'o', 'o', 
						'u', 'u', 'u', 'u', 
						'e', 'e', 'e', 'e', 
						'c', 'y', 'n', '','', ''
					),$var);
				return $var;
			}
			$tabeleves = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves");
			foreach($tabeleves as $liste_eleves) {
				$mdp = mb_strtolower(substr(strToNoAccent($liste_eleves['prenom']),0,1),'UTF-8').substr($liste_eleves['naissance'],8,2).substr($liste_eleves['naissance'],5,2).substr($liste_eleves['naissance'],0,4);
				do {
				    $sel = bin2hex(random_bytes(16));
				} while ($sel === '0');
				$mdp_avec_sel = $mdp.$sel;
				$hashed_password = hash('sha256', $mdp_avec_sel);
				mysqli_query($bdd,"UPDATE ".$prefix."_eleves SET mdp = '".$hashed_password."', sel = '".$sel."' WHERE eleves_id = '".$liste_eleves['eleves_id']."'");
			}
			echo '<p class="signal">'.PW_REINIT.'</p>';
		}
		$verif_tabeleves = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves ORDER BY 
	replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
	replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
	replace(nom,'À','A'),'Á','A'),'Â','A'),'Ã','A'),'Ä','A'),'Å','A'),'Ç','C'),'È','E'),'É','E')
	,'Ê','E'),'Ë','E'),'Ì','I'),'Í','I'),'Î','I'),'Ï','I'),'Ò','O'),'Ó','O'),'Ô','O'),'Õ','O')
	,'Ö','O'),'Ù','U'),'Ú','U'),'Û','U'),'Ü','U'),'Ý','Y')");
		$nb_ele = mysqli_num_rows($verif_tabeleves);
		?><style type="text/css">
		#mda1 { background-color: #fff; }
		#mda1 td { border: 3px #086A87 solid; }
		</style><?php
		if($nb_ele==0) {
			echo '<a href="database.php?page=installer"><img src="img/nav/install_eleves.png" /></a>';
		}
		else {
			if(isset($_SESSION['import'])) {
				if($_SESSION['import']=="maj") {
					echo '<p class="signal">'.DATAC_CONS1.'</p>';
					echo '<p>'.$_SESSION['eleve_insert_nb'].' '.DATAC_CONS2.'</p>';
					echo '<p>'.$_SESSION['eleve_update_nb'].' '.DATAC_CONS3.'</p>';
					echo '<p>'.$_SESSION['eleve_delete_nb'].' '.DATAC_CONS4.'</p>';
					$_SESSION['import']="down";
					unset($_SESSION['eleve_insert_nb']);
					unset($_SESSION['eleve_update_nb']);
					unset($_SESSION['eleve_delete_nb']);
				}
				else if ($_SESSION['import']=="new") {
					echo '<p class="signal">'.DATAC_CONS5.'</p>';
					$_SESSION['import']="down";
				}
			}
			echo '<div style="overflow: auto;  white-space: nowrap;"><h1>'.$nb_ele.' '.DATAC_CONS6.'</h1>';
						
			$liste_division = mysqli_query($bdd,"SELECT division FROM ".$prefix."_eleves GROUP BY division ORDER BY division ASC");
			$liste_nb = mysqli_num_rows($liste_division);
			if($liste_nb>0) {
				// Vérification de la concordance entre divisions et configuration de l'établissement
				include('db/proc/etab_config_check.php');
				// Préparation de l'affichage de l'effectif de chaque classe :
				if(isset($_POST['div_modif'])) { echo '<form method="POST" action="" name="divchg2">'; }
				echo '<p /><table class="fleft"><thead><tr><th>'.DIV.'</th><th>'.EFFECTIF.'</th></tr></thead>
				<tbody>';
				$item=0;
				$liste_division = mysqli_query($bdd,"SELECT division FROM ".$prefix."_eleves GROUP BY division ORDER BY division ASC");
				foreach($liste_division as $liste) {
					$div = $liste['division'];
					if(isset($_POST['chg'.$item.''])) {
						$newdiv = mysqli_real_escape_string($bdd,$_POST['chg'.$item.'']);
						mysqli_query($bdd,"UPDATE ".$prefix."_edtbrik SET division = '".$newdiv."' WHERE division = '".$div."'");
						mysqli_query($bdd,"UPDATE ".$prefix."_eleves SET division = '".$newdiv."' WHERE division = '".$div."'");
						$month = date("n");
						if($month>0&&$month<9) {
							$anneesco = (date("Y")-1).'/'.date("Y");
						}
						else {
							$anneesco = date("Y").'/'.(date("Y")+1);
						}
						mysqli_query($bdd,"UPDATE ".$prefix."_etab_effectifs SET division = '".$newdiv."' WHERE anneesco = '".$anneesco."' AND division = '".$div."'");
						if(date('n')>7&&date('n')<=12) { $year=date('Y'); }
						else { $year=date('Y')-1; }
						mysqli_query($bdd,"UPDATE ".$prefix."_freq SET division = '".$newdiv."' WHERE division = '".$div."' AND date_freq > '".$year."-08-10'");
						mysqli_query($bdd,"UPDATE ".$prefix."_freqgrappes SET division = '".$newdiv."' WHERE division = '".$div."' AND date_freq > '".$year."-08-10'");
						echo '<script language="Javascript">
						<!--
						document.location.replace("database.php?page=consulter");
						// -->
						</script>';
					}
					$nbeleves_div = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE division = '".mysqli_real_escape_string($bdd,$div)."'");
					$nbeleves = mysqli_num_rows($nbeleves_div);
					echo '<tr>';
					if(isset($_POST['div_modif'])) {
						echo '<td class="center"><input size="10" name="chg'.$item.'" type="text" value="'.$liste['division'].'" /></td>';
					}
					else { echo '<td class="center">'.$liste['division'].'</td>'; }
					echo '<td class="center">'.$nbeleves.'</td></tr>';
					$item++;
				}
				if(isset($_POST['div_modif'])) { echo '<tr><td colspan="2"><p class="signal">'.DATAC_CONS7.'</p><input type="submit" class="bouton boutdb" value="'.DATAC_CONS8.'" name="div_modif" /></td></tr>'; }
				else { echo '<tr><td colspan="2"><form method="POST" action="" name="divchg1"><input type="submit" class="bouton boutdb" value="'.DATAC_CONS9.'" name="div_modif" /></td></tr>'; }
				echo '</tbody></table></form>';
			}
			$code_nb=mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE code != ''"));
			$mail_nb=mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE mail != ''"));
			$reserv_could=mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve'"));
			$auth_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_resmodauth'"));
			// Affichage des élèves :
			echo '<p /><table id="tablesorter" class="tablesorter margel1"><thead>
				<tr>
					<th>';
					if($_SESSION['user_droits'][5]=="2") {
						echo '<i class="fa-solid fa-screwdriver-wrench"></i> ';
					}
					echo NID.'</th>
					<th>'.NAME.'</th>
					<th>'.FORNAME.'</th>
					<th>'.DIV.'</th>
					<th>'.BDAY.'</th>
					<th>'.SEX.'</th>';
					if($code_nb>0) { echo '<th>'.CODE.'</th>'; }
					if ($reserv_could['valeur']==2&&$auth_info['valeur']!="code") { echo '<th>'.IDENT2.'</th>'; }
					if($mail_nb>0) { echo '<th>'.MAIL2.'<br>('.MAILCLIC.')</th>'; }
				echo '</tr></thead>
				<tbody>';
			$i=0;
			foreach($verif_tabeleves as $liste_eleves) {
				echo '<tr>
				<td>';
				if($_SESSION['user_droits'][5]=="2") {
					echo '<a href="database.php?page=modifier&id='.$liste_eleves['eleves_id'].'"><i class="fa-solid fa-screwdriver-wrench"></i> ';
				}
				echo $liste_eleves['eleves_id'];
				if($_SESSION['user_droits'][5]=="2") {
					echo '</a>';
				}
				if($_SESSION['user_droits'][5]=="2"&&($liste_eleves['sel']=='0'||$liste_eleves['sel']=='NULL')) {
					echo '<i class="fa-solid fa-triangle-exclamation" title="'.PW_REINIT2.'"></i> ';
				}
				echo '</td>
				<td>'.$liste_eleves['nom'].'</td>
				<td>'.$liste_eleves['prenom'].'</td>
				<td>'.$liste_eleves['division'].'</td>
				<td>'.$liste_eleves['naissance'].'</td>
				<td>'.$liste_eleves['sexe'].'</td>';
				if($code_nb>0) { echo '<td>'.$liste_eleves['code'].'</td>'; }
				if ($reserv_could['valeur']==2&&$auth_info['valeur']!="code") { 
					if($auth_info['valeur']=="perso") {
						echo '<td>';
						if(@$multi=="ON"&&@$multipref==1) {
							echo $_SESSION['prefident'];
						}
						echo $liste_eleves['id_perso'].'</td>'; 
					}
					else {
						echo '<td>';
						if(@$multi=="ON"&&@$multipref==1) {
							echo $_SESSION['prefident'];
						}
						echo $liste_eleves['id_constr'].'</td>'; 
					}
				}
				if($mail_nb>0) { 
					echo '<td>';
					if($liste_eleves['mail']!="") {
						echo '<center><span id="emailIcon'.$i.'" class="clicable"><i class="fa-solid fa-at" title="'.$liste_eleves['mail'].'
	'.MAILCLIC.'" onclick="copyEmailToClipboard(\''.$liste_eleves['mail'].'\', \'emailIcon'.$i.'\', \'copiedMessage'.$i.'\')"></i> <span id="copiedMessage'.$i.'" style="display:none;">'.MAILCOP.'</span></span></center>';
					}
					echo '</td>'; 
					$i++;
				}
				echo '</tr>';
			}
			echo '</tbody></table>';
			?><script>
			    function copyEmailToClipboard(emailAddress, iconId, messageId) {
			        var dummyElement = document.createElement("textarea");
			        document.body.appendChild(dummyElement);
			        dummyElement.value = emailAddress;
			        dummyElement.select();
			        document.execCommand("copy");
			        document.body.removeChild(dummyElement);
			        var copiedMessageElement = document.getElementById(messageId);
			        copiedMessageElement.style.display = 'inline'; // Affiche le message "copié"

			        // Cache le message "copié" après un délai de 2 secondes (2000 millisecondes)
			        setTimeout(function() {
			            copiedMessageElement.style.display = 'none';
			        }, 2000);
			    }
			</script>
			<?php
			if($_SESSION['user_droits'][5]=="2") {
				echo '<form method="post" name="mdpreinit" action=""><p><input type="submit" name="mdpreinit" value="'.PW_REINIT3.'" /></p></form></div>';
			}
		}
	}
}
else {
	include('include/noaccess.php');
	echo '<br><a href="../index.php">'.ACCUEIL.'</a></p>';
}
?>
