<?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 {		
		?><style type="text/css">
		#mda5 { background-color: #fff; }
		#mda5 td { border: 3px #086A87 solid; }
		#mda4 td { border: 0; }
		</style><?php
		if(isset($_POST['go'])) {
			$nom = strtoupper(mysqli_real_escape_string($bdd,trim($_POST['nom'])));
			$prenom = mysqli_real_escape_string($bdd,trim($_POST['prenom']));
			if(!$_POST['division']) {
				if(isset($_POST['div_new'])) {
					if(!preg_match('#  #', $_POST['div_new'])){
						$division = mysqli_real_escape_string($bdd,trim($_POST['div_new'])); 
					}
				}
			}
			else { $division = mysqli_real_escape_string($bdd,$_POST['division']); }
			$naissance = $_POST['naissance'];
			$sexe = $_POST['sexe'];
			$code = mysqli_real_escape_string($bdd,$_POST['code']);
			if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_user WHERE login = '$code'"))>0||$code=='reserver') {
				$code=='';
			}
			$mail = mysqli_real_escape_string($bdd,$_POST['mail']);
			$resp_nom = strtoupper(mysqli_real_escape_string($bdd,trim($_POST['resp_nom'])));
			$add1 = mysqli_real_escape_string($bdd,trim($_POST['add1']));
			$add2 = mysqli_real_escape_string($bdd,trim($_POST['add2']));
			$cpostal = mysqli_real_escape_string($bdd,trim($_POST['cpostal']));
			$ville = mysqli_real_escape_string($bdd,trim($_POST['ville']));
			if($nom==""||$prenom==""||@$division==""||$naissance==""||$sexe=="") {
				echo '<p>'.ALERT3.'</p>';
			}
			else {
				//vérification dans la base:
				$eleve_verif = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE nom = '".$nom."' AND prenom = '".$prenom."' AND division = '".$division."'");
				$eleve_nb = mysqli_num_rows($eleve_verif);
				if($eleve_nb!=0) {
					echo '<p class="signal">'.DATAC_ADD1.'</p>';
				}
				else {
					function strtoupperFr($string) { // gestion des accents dans la requête
					   $string = strtoupper($string);
					   $string = str_replace(
						  array('é', 'è', 'ê', 'ë', 'à', 'â', 'ç', 'î', 'ï', 'ô', 'ù', 'û'),
						  array('É', 'È', 'Ê', 'Ë', 'À', 'Â', 'Ç', 'Î', 'Ï', 'Ô', 'Ù', 'Û'),
						  $string
					   );
						return $string;
					}
					
					// Insertion :
					$mdp = mb_strtolower(substr($prenom,0,1),'UTF-8').substr($naissance,8,2).substr($naissance,5,2).substr($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,"INSERT INTO ".$prefix."_eleves (eleves_id, nom, prenom, division, naissance, sexe, mail, code, mdp, sel, lang, resp_nom, add1, add2, cpostal, ville, categ) VALUES ('', '".strtoupperFr($nom)."', '".$prenom."', '".$division."', '".$naissance."', '".$sexe."', '".$mail."', '".$code."', '".$hashed_password."', '".$sel."', 'fr', '".strtoupperFr($resp_nom)."', '".$add1."', '".$add2."', '".$cpostal."', '".$ville."', '1')");
					
					$eleve_new = mysqli_query($bdd,"SELECT MAX(eleves_id), division FROM ".$prefix."_eleves");
					while($div_select = mysqli_fetch_assoc($eleve_new)) {
						$eleve_id = $div_select['MAX(eleves_id)'];
						$deb_division = substr($division, 0, 1);
					}

					// on crée l'identifiant id_constr si besoin :
					$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'"));
					if($reserv_could['valeur']==2&&($auth_info['valeur']=="prenomnom"||$auth_info['valeur']=="pnom")) {
						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;
						}
						function rand_nb($length = 8) {
						    $characters = '123456789';
						    $charactersLength = strlen($characters);
						    $randomString = '';
						    for ($i = 0; $i < $length; $i++) {
						        $randomString .= $characters[rand(0, $charactersLength - 1)];
						    }
						    return $randomString;
						}
						if($auth_info['valeur']=="prenomnom") {
							$ident = substr(strToNoAccent($prenom),0,20).'.'.substr(strToNoAccent($nom),0,20);
						}
						else if($auth_info['valeur']=="pnom") {
							$ident = substr(strToNoAccent($prenom),0,1).substr(strToNoAccent($nom),0,20);
						}
						$checke = mysqli_query($bdd,"SELECT id_constr FROM ".$prefix."_eleves WHERE id_constr = '".mysqli_real_escape_string($bdd,strtolower($ident))."' AND eleves_id <> '".$eleve_id."'");
						$checku = mysqli_query($bdd,"SELECT login FROM ".$prefix."_user WHERE login = '".mysqli_real_escape_string($bdd,strtolower($ident))."'");
						if(mysqli_num_rows($checke)>0||mysqli_num_rows($checku)>0||$ident=='reserver') {
							$ident = $ident.rand_nb(2);
						}
						mysqli_query($bdd,"UPDATE ".$prefix."_eleves SET id_constr = '".strtolower($ident)."' WHERE eleves_id = '".$eleve_id."'");
					}

					// Mise à jour des effectifs :
					$month = date("n");
					if($month>0&&$month<9) {
						$anneesco = (date("Y")-1).'/'.date("Y");
					}
					else {
						$anneesco = date("Y").'/'.(date("Y")+1);
					}
					$checkdiv = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_etab_effectifs WHERE anneesco = '".$anneesco."' AND division = '".$division."'"));
					@mysqli_query($bdd,"UPDATE ".$prefix."_etab_effectifs SET effectif = '".($checkdiv['effectif']+1)."' WHERE anneesco = '".$anneesco."' AND division = '".$division."'");
					
					// Message :
					echo '<p>'.DATAC_ADD2.' '.strtoupperFr($_POST['nom']).', '.$_POST['prenom'].', '.EN.' '.$division.'.';
					if($_POST['code']!="") { echo ' Code : '.$_POST['code'].'.';}
					if(isset($checkdiv['effectif'])) {
						echo '<br>'.DATAC_ADD3.' '.$division.' '.EN.' '.$anneesco.' ('.($checkdiv['effectif']+1).' '.ELEVS1.').</p>';
					}
				}
			}
		}
		
		echo '<div style="overflow: auto;  white-space: nowrap;"><h1>'.DATANAV5.'</h1>
		<form method="POST" name="eleve" action="database.php?page=ajouter" class="padd2">
		<table id="install" class="dbform noborder">
			<tr><td colspan="2"><b>'.OBLCASE.DOTS.'</b></td></tr>
			<tr><td>'.NAME.DOTS.'</td><td><input type="text" class="inptxt" name="nom" id="nom_e" maxlength="30" value="" /></td></tr>
			<tr><td>'.FORNAME.DOTS.'</td><td><input type="text" class="inptxt" name="prenom" value="" /></td></tr>
			<tr><td>'.DIV.DOTS.'</td><td><div class="box"><select name="division" value=""><option></option>';
			$liste_division = mysqli_query($bdd,"SELECT division FROM ".$prefix."_eleves GROUP BY division ORDER BY division ASC");
			while($liste = mysqli_fetch_assoc($liste_division)) {
				echo '<option>'.$liste['division'].'</option>';
			}
		echo '</select></div> <i>'.DATAC_ADD5.'</i> <input type="text" name="div_new" class="inptxt" style="width:5em;" maxlength="5" value="" /></td></tr>
			<tr><td>'.BDAY.DOTS.'</td>
				<td><input type="date" class="inptxt" name="naissance" />
			</td></tr>
			<tr><td>'.SEX.DOTS.'</td><td>
				<div class="box"><select name="sexe"><option></option><option value="F">'.SEX2.'</option><option value="M">'.SEX1.'</option></select></div>
			</td></tr>
			<tr><td colspan="2"><b>'.OPTCASE2.DOTS.'</b></td></tr>
			<tr><td>'.CODE.DOTS.'</td><td><input type="text" class="inptxt" maxlength="50" name="code" value="" /></td></tr>
			<tr><td>'.MAIL2.DOTS.'</td><td><input type="text" class="inptxt" name="mail" maxlength="200" value="" /></td></tr>
			<tr><td>'.RESPNOM.DOTS.'</td><td><input type="text" class="inptxt" name="resp_nom" maxlength="200" value="" /></td></tr>
			<tr><td>'.ADD1.DOTS.'</td><td><input type="text" class="inptxt" name="add1" maxlength="200" value="" /></td></tr>
			<tr><td>'.ADD2.DOTS.'</td><td><input type="text" class="inptxt" name="add2" maxlength="200" value="" /></td></tr>
			<tr><td>'.CPOSTAL.DOTS.'</td><td><input type="text" class="inptxt" name="cpostal" maxlength="200" value="" /></td></tr>
			<tr><td>'.VILLE.DOTS.'</td><td><input type="text" class="inptxt" name="ville" maxlength="200" value="" /></td></tr>
			<tr><td colspan="2" style="text-align:right;"><input class="bouton boutdb" type="submit" value="'.VALID.'" name="go" /></td></tr>
		</table>
		
		</form></div>
		
		<p class="maxwidth">* <i>'.DATAC_ADD6.'</i></p>';
		echo "<script type=\"text/javascript\">
				document.getElementById('nom_e').focus();
			</script>";
	}	
	
}
else {
	include('include/noaccess.php');
	echo '<br><a href="../index.php">'.ACCUEIL.'</a></p>';
}
	?>
