<?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(trim($_POST['nom'] ?? ''));
			$prenom = trim($_POST['prenom'] ?? '');

			$division = '';

			if (empty($_POST['division'])) {
			    if (!empty($_POST['div_new']) && !preg_match('#  #', $_POST['div_new'])) {
			        $division = trim($_POST['div_new']);
			    }
			} else {
			    $division = trim($_POST['division']);
			}

			$naissance = $_POST['naissance'] ?? '';
			$sexe = $_POST['sexe'] ?? '';

			$code = trim($_POST['code'] ?? '');
			$mail = trim($_POST['mail'] ?? '');

			$stmt = $pdo->prepare("
			    SELECT 1
			    FROM {$prefix}_user
			    WHERE login = :login
			");

			$stmt->execute([
			    ':login' => $code
			]);

			if ($stmt->fetch() || strtolower($code) === 'reserver') {
			    $code = '';
			}

			$resp_nom = strtoupper(trim($_POST['resp_nom'] ?? ''));
			$add1 = trim($_POST['add1'] ?? '');
			$add2 = trim($_POST['add2'] ?? '');
			$cpostal = trim($_POST['cpostal'] ?? '');
			$ville = trim($_POST['ville'] ?? '');
			if (
			    $nom === '' ||
			    $prenom === '' ||
			    $division === '' ||
			    $naissance === '' ||
			    $sexe === ''
			) {
			    echo '<p>' . ALERT3 . '</p>';
			}
			else {
				//vérification dans la base:
				$stmt = $pdo->prepare("
				    SELECT eleves_id
				    FROM {$prefix}_eleves
				    WHERE nom = :nom
				      AND prenom = :prenom
				      AND division = :division
				");

				$stmt->execute([
				    ':nom' => $nom,
				    ':prenom' => $prenom,
				    ':division' => $division
				]);

				if ($stmt->fetch()) {
				    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);
					$hashed_password = password_hash($mdp, PASSWORD_DEFAULT);
					$sel = '0';
					$stmt = $pdo->prepare("
					    INSERT INTO {$prefix}_eleves
					    (
					        nom,
					        prenom,
					        division,
					        naissance,
					        sexe,
					        mail,
					        code,
					        mdp,
					        sel,
					        lang,
					        resp_nom,
					        add1,
					        add2,
					        cpostal,
					        ville,
					        categ
					    )
					    VALUES
					    (
					        :nom,
					        :prenom,
					        :division,
					        :naissance,
					        :sexe,
					        :mail,
					        :code,
					        :mdp,
					        :sel,
					        'fr',
					        :resp_nom,
					        :add1,
					        :add2,
					        :cpostal,
					        :ville,
					        '1'
					    )
					");

					$stmt->execute([
					    ':nom' => strtoupperFr($nom),
					    ':prenom' => $prenom,
					    ':division' => $division,
					    ':naissance' => $naissance,
					    ':sexe' => $sexe,
					    ':mail' => $mail,
					    ':code' => $code,
					    ':mdp' => $hashed_password,
					    ':sel' => 0,
					    ':resp_nom' => strtoupperFr($resp_nom),
					    ':add1' => $add1,
					    ':add2' => $add2,
					    ':cpostal' => $cpostal,
					    ':ville' => $ville
					]);

					$eleve_id = $pdo->lastInsertId();
					$deb_division = substr($division, 0, 1);

					// on crée l'identifiant id_constr si besoin :
					$stmt = $pdo->prepare("
					    SELECT valeur
					    FROM {$prefix}_parametres
					    WHERE param_nom = :nom
					");

					$stmt->execute([':nom' => 'freq_reseleve']);
					$reserv_could = $stmt->fetch();

					$stmt->execute([':nom' => 'freq_resmodauth']);
					$auth_info = $stmt->fetch();
					if (
					    $reserv_could === '2'
					    && ($auth_info === "prenomnom" || $auth_info === "pnom")
					) {
						function strToNoAccent($string) {
						    return iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
						}
						function rand_nb($length = 8) {
						    $characters = '123456789';
						    $result = '';

						    for ($i = 0; $i < $length; $i++) {
						        $result .= $characters[random_int(0, strlen($characters) - 1)];
						    }

						    return $result;
						}
						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);
						}
						$stmt = $pdo->prepare("
						    SELECT 1
						    FROM {$prefix}_eleves
						    WHERE id_constr = :ident
						      AND eleves_id <> :id
						    LIMIT 1
						");

						$stmt->execute([
						    ':ident' => strtolower($ident),
						    ':id' => $eleve_id
						]);

						$checke = $stmt->fetchColumn();
						$stmt = $pdo->prepare("
						    SELECT 1
						    FROM {$prefix}_user
						    WHERE login = :login
						    LIMIT 1
						");

						$stmt->execute([
						    ':login' => strtolower($ident)
						]);

						$checku = $stmt->fetchColumn();
						if ($checke || $checku || $ident === 'reserver') {
						    $ident .= rand_nb(2);
						}
						$stmt = $pdo->prepare("
						    UPDATE {$prefix}_eleves
						    SET id_constr = :ident
						    WHERE eleves_id = :id
						");

						$stmt->execute([
						    ':ident' => strtolower($ident),
						    ':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);
					}
					$stmt = $pdo->prepare("
					    SELECT effectif
					    FROM {$prefix}_etab_effectifs
					    WHERE anneesco = :anneesco
					      AND division = :division
					");

					$stmt->execute([
					    ':anneesco' => $anneesco,
					    ':division' => $division
					]);

					$checkdiv = $stmt->fetch();
					$newEffectif = ($checkdiv['effectif'] ?? 0) + 1;

					$stmt = $pdo->prepare("
					    UPDATE {$prefix}_etab_effectifs
					    SET effectif = :effectif
					    WHERE anneesco = :anneesco
					      AND division = :division
					");

					$stmt->execute([
					    ':effectif' => $newEffectif,
					    ':anneesco' => $anneesco,
					    ':division' => $division
					]);
					
					// Message :
					echo '<p>'
					    . DATAC_ADD2 . ' '
					    . strtoupperFr(htmlspecialchars($_POST['nom'] ?? '')) . ', '
					    . htmlspecialchars($_POST['prenom'] ?? '') . ', '
					    . EN . ' ' . $division . '.';

					if (!empty($_POST['code'])) {
					    echo ' Code : ' . htmlspecialchars($_POST['code']) . '.';
					}

					if (isset($checkdiv['effectif'])) {
					    echo '<br>' . DATAC_ADD3 . ' '
					        . $division . ' '
					        . EN . ' '
					        . $anneesco . ' ('
					        . $newEffectif . ' ' . 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">';
			$stmt = $pdo->prepare("
			    SELECT DISTINCT division
			    FROM {$prefix}_eleves
			    WHERE categ = :categ
			    ORDER BY division ASC
			");

			$stmt->execute([':categ' => 1]);
			$liste_divisions = $stmt->fetchAll();

			echo '<select name="division">';
			echo '<option value=""></option>';

			foreach ($liste_divisions as $liste) {
			    $div = htmlspecialchars($liste['division'], ENT_QUOTES, 'UTF-8');

			    echo '<option value="'.$div.'">'.$div.'</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>';
}
	?>
