<?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 (!isset($_SESSION['user_droits'][5]) || $_SESSION['user_droits'][5] !== "2") {
		echo '<p class="noaccess">'.NOMODULE.'<br><a href="../index.php">'.ACCUEIL.'</a></p>';
	}
	else {
		?><style type="text/css">
		#mda6 { background-color: #fff; }
		#mda6 td { border: 3px #086A87 solid; }
		#mda5 td { border: 0; }
		</style><?php
		echo '<h1>'.DATANAV61.'</h1>
		<form method="POST" name="eleve" action="database.php?page=modifier" class="padd4" autocomplete="off">
			<table class="noborder">
				<tr>
					<td><label for="eleves">'.NAMECH.'</label></td>
					<td>
					  <input type="text" autocomplete="off" aria-autocomplete="none" class="inptxt" name="eleve" size="40" id="eleves" value="">
					</td>
				</tr>
			<tr><td colspan="2" style="text-align:right;">
				<input class="bouton boutdb" type="submit" value="'.MODIFY.'" name="modif" />
				<input class="bouton boutdb" type="submit" value="'.SUPPR.'" name="suppr" />
			</td></tr></table>
		</form>';
		
		$stmt = $pdo->prepare("
		    SELECT valeur
		    FROM {$prefix}_parametres
		    WHERE param_nom = :nom
		");

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

		$stmt->execute([':nom' => 'freq_resmodauth']);
		$auth_info = $stmt->fetch(PDO::FETCH_ASSOC);

		if(isset($_POST['modif'])||isset($_GET['id'])) {
			echo '<div style="overflow: auto;  white-space: nowrap;"><form method="POST" action="database.php?page=modifier" class="padd4">';
			//sélection de l'élève
			if (isset($_POST['modif'])) {
				$eleve_info = null;
			    include('./db/proc/eleve_select.php');
			    if (!$eleve_info || !is_array($eleve_info)) {
				    echo '<p class="signal">Aucun élève sélectionné.</p>';
				    exit;
				}
			    echo '<input type="hidden" name="eleve_id" value="' . (int)$eleve_info['eleves_id'] . '">';
			}
			else if(isset($_GET['id'])) {
				$stmt = $pdo->prepare("
				    SELECT *
				    FROM {$prefix}_eleves
				    WHERE eleves_id = :id
				");

				$stmt->execute([
				    ':id' => (int) $_GET['id']
				]);

				$eleve_info = $stmt->fetch();
				echo '<input type="hidden" name="eleve_id" value="'.htmlspecialchars($eleve_info['nom'], ENT_QUOTES, 'UTF-8').'" />';
				unset($_SESSION['eleves_id']);
			}
			if(isset($eleve_info['nom'])) {
				echo '
				<table class="noborder">
					<tr><td colspan="2"><b>'.OBLCASE.DOTS.'</b></td></tr>
					<tr><td>'.NAME.DOTS.'</td><td><input type="text" class="inptxt" name="nom" maxlength="30" value="'.htmlspecialchars($eleve_info['nom'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.FORNAME.DOTS.'</td><td><input type="text" class="inptxt" name="prenom" value="'.htmlspecialchars($eleve_info['prenom'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.DIV.DOTS.'</td><td><div class="box"><select name="division" value=""><option></option>';
					$stmt = $pdo->prepare("
					    SELECT DISTINCT division
					    FROM {$prefix}_eleves
					    WHERE categ = :categ
					    ORDER BY division ASC
					");

					$stmt->execute([':categ' => 1]);
					$liste_divisions = $stmt->fetchAll();
					foreach ($liste_divisions as $liste) {
					    $div = htmlspecialchars($liste['division'], ENT_QUOTES, 'UTF-8');

					    echo '<option value="'.$div.'"';

					    if ($eleve_info['division'] === $liste['division']) {
					        echo ' selected';
					    }

					    echo '>'.$div.'</option>';
					}
				echo '</select></div><i>'.DATAC_ADD5.'</i> <input type="text" name="div_new" style="width:5em;" maxlength="5" value="" /></td></tr>
					<tr><td>'.BDAY.DOTS.'</td>';
					echo '<td><input type="date" class="inptxt" name="naissance" value="'.$eleve_info['naissance'].'"/>
					</td></tr>
					<tr><td>'.SEX.DOTS.'</td><td>';
						$sexcode = array('F','M');
						$sexname = array(SEX2,SEX1);
						echo '<div class="box"><select name="sexe">';
						for($i=0;$i<count($sexcode);$i++) {
							echo '<option value="'.$sexcode[$i].'"';
							if($eleve_info['sexe']==$sexcode[$i]) {
								echo ' selected ';
							}
							echo '>'.$sexname[$i].'</option>';
						}
						echo '</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" name="code" maxlength="50" value="'.htmlspecialchars($eleve_info['code'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.MAIL2.DOTS.'</td><td><input type="text" class="inptxt" name="contact" maxlength="200" value="'.htmlspecialchars($eleve_info['mail'], ENT_QUOTES, 'UTF-8').'" autocomplete="off" /></td></tr>
					<tr><td>'.RESPNOM.DOTS.'</td><td><input type="text" class="inptxt" name="resp_nom" maxlength="200" value="'.htmlspecialchars($eleve_info['resp_nom'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.ADD1.DOTS.'</td><td><input type="text" class="inptxt" name="add1" maxlength="200" value="'.htmlspecialchars($eleve_info['add1'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.ADD2.DOTS.'</td><td><input type="text" class="inptxt" name="add2" maxlength="200" value="'.htmlspecialchars($eleve_info['add2'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.CPOSTAL.DOTS.'</td><td><input type="text" class="inptxt" name="cpostal" maxlength="200" value="'.htmlspecialchars($eleve_info['cpostal'], ENT_QUOTES, 'UTF-8').'" /></td></tr>
					<tr><td>'.VILLE.DOTS.'</td><td><input type="text" class="inptxt" name="ville" maxlength="200" value="'.htmlspecialchars($eleve_info['ville'], ENT_QUOTES, 'UTF-8').'" /></td></tr>';
					if ($reserv_could['valeur']==2) { 
						echo '<tr><td colspan="2"><b>'.IDENT4.DOTS.'</b></td></tr>';
						if($auth_info['valeur']!='code') {
							echo '<tr><td>'.IDENT2.DOTS.'</td><td>';
							if(@$multi=="ON"&&@$multipref==1) {
								echo $_SESSION['prefident'];
							}
							echo '<input type="text" class="inptxt" name="ident" maxlength="50"';
							if(@$multi=="ON"&&@$multipref==1) {
								echo 'size="16"';
							}
							echo ' value="';
							if($auth_info['valeur']=='perso') { echo $eleve_info['id_perso']; }
							else { echo $eleve_info['id_constr']; }
							echo '" /></td></tr>';
						}
						echo '<tr><td>'.PW.DOTS.'</td><td>
						<script language="Javascript">
							function showPass() {
							  var x = document.getElementById("id_password");
							  var y = document.getElementById("eye");
							  if (x.type === "password") {
							    x.type = "text";
							    y.className = "fa-solid fa-eye-slash";
							  } else {
							    x.type = "password";
							    y.className = "fa-solid fa-eye";
							  }
							}
						</script>
						<input type="text" class="inptxt" id="id_contact" name="mdp" maxlength="30" autocomplete="new-password" /><i class="fa-solid fa-eye" id="eye" onclick="showPass()" style="margin-left: -25px; cursor: pointer;"></i></td></tr>';
					}
					echo '<tr><td colspan="2" style="text-align:right;"><input type="hidden" name="divcheck" value="'.$eleve_info['division'].'" /><input class="bouton boutdb" type="submit" value="'.FREQJ_ORDER4.'" name="modif_confirm" /></td></tr>
				</table>
				<p class="maxwidth">* <i>'.DATAC_ADD6.'</p>';
			}
			echo '</form></div>';
			if (isset($_POST['mdpreinit'])) {

			    $mdp = mb_strtolower(substr($eleve_info['prenom'],0,1),'UTF-8')
			         . substr($eleve_info['naissance'],8,2)
			         . substr($eleve_info['naissance'],5,2)
			         . substr($eleve_info['naissance'],0,4);

			    $hashed_password = password_hash($mdp, PASSWORD_DEFAULT);

			    $stmt = $pdo->prepare("
			        UPDATE {$prefix}_eleves
			        SET mdp = :mdp,
			            sel = 0
			        WHERE eleves_id = :id
			    ");

			    $stmt->execute([
			        ':mdp' => $hashed_password,
			        ':id'  => (int) $_GET['id']
			    ]);

			    echo '<p class="signal">'.PW_REINIT4.'</p>';
			}
			echo '<form method="post" name="mdpreinit" action=""><p><input type="submit" name="mdpreinit" value="'.PW_REINIT5.'" /></p></form>';
		}
		
		if(isset($_POST['modif_confirm'])) {			
			function strtoupperFr($string) {
			    $string = mb_strtoupper($string, 'UTF-8');
			    $string = str_replace(
			        ['é','è','ê','ë','à','â','ç','î','ï','ô','ù','û'],
			        ['É','È','Ê','Ë','À','Â','Ç','Î','Ï','Ô','Ù','Û'],
			        $string
			    );
			    return $string;
			}

			$nom = strtoupperFr(trim($_POST['nom'] ?? ''));
			$prenom = trim($_POST['prenom'] ?? '');

			$division = !empty($_POST['division'])
			    ? trim($_POST['division'])
			    : trim($_POST['div_new'] ?? '');

			$naissance = $_POST['naissance'] ?? '';
			$sexe = $_POST['sexe'] ?? '';
			$eleve_id = (int)($_POST['eleve_id'] ?? 0);

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

			$resp_nom = strtoupperFr(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 {
				if ($reserv_could['valeur'] == 2) {

				    if ($auth_info['valeur'] != 'code') {

				        $login = trim($_POST['ident']);

				        $stmt = $pdo->prepare("
				            SELECT 1 FROM {$prefix}_eleves
				            WHERE (code = :login OR id_constr = :login OR id_perso = :login)
				            AND eleves_id <> :id
				        ");

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

				        $reserv_exist = $stmt->fetchColumn();

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

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

				        $checku = $stmt->fetchColumn();

				        if ($reserv_exist || $checku || $login === 'reserver') {
				            echo '<p class="signal">'.DATAC_MOD1.'</p>';
				            $chgtlogin = 0;
				        } else {
				            $chgtlogin = 1;
				        }

				        $mod = ($auth_info['valeur'] == 'perso') ? 'id_perso' : 'id_constr';
				    }

				    if (!empty($_POST['mdp'])) {
				        $hashed_password = password_hash($_POST['mdp'], PASSWORD_DEFAULT);
				        $chmdp = 1;
				    } else {
				        $chmdp = 0;
				    }

				} else {

				    $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);
				    $chmdp = 1;
				}
				
				$sql = "
				UPDATE {$prefix}_eleves SET
				    nom = :nom,
				    prenom = :prenom,
				    division = :division,
				    naissance = :naissance,
				    sexe = :sexe,
				    code = :code,
				    mail = :mail,
				    resp_nom = :resp_nom,
				    add1 = :add1,
				    add2 = :add2,
				    cpostal = :cpostal,
				    ville = :ville
				";

				$params = [
				    ':nom' => $nom,
				    ':prenom' => $prenom,
				    ':division' => $division,
				    ':naissance' => $naissance,
				    ':sexe' => $sexe,
				    ':code' => $code,
				    ':mail' => $mail,
				    ':resp_nom' => $resp_nom,
				    ':add1' => $add1,
				    ':add2' => $add2,
				    ':cpostal' => $cpostal,
				    ':ville' => $ville,
				    ':id' => $eleve_id
				];
				if ($chmdp == 1) {
				    $sql .= ", mdp = :mdp, sel = 0";
				    $params[':mdp'] = $hashed_password;
				}
				if (isset($chgtlogin) && $chgtlogin == 1) {
				    $sql .= ", {$mod} = :login";
				    $params[':login'] = strtolower($login);
				}

				$sql .= " WHERE eleves_id = :id";

				$stmt = $pdo->prepare($sql);
				$stmt->execute($params);
				
				
				if ($_POST['divcheck'] !== $division) {

				    $month = date("n");

				    $anneesco = ($month > 0 && $month < 9)
				        ? (date("Y") - 1) . '/' . date("Y")
				        : date("Y") . '/' . (date("Y") + 1);

				    $oldDiv = $_POST['divcheck'];
				    $newDiv = $division;

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

				    $stmt->execute([
				        ':annee' => $anneesco,
				        ':div' => $oldDiv
				    ]);

				    // +1 nouvelle division
				    $stmt = $pdo->prepare("
				        UPDATE {$prefix}_etab_effectifs
				        SET effectif = effectif + 1
				        WHERE anneesco = :annee AND division = :div
				    ");

				    $stmt->execute([
				        ':annee' => $anneesco,
				        ':div' => $newDiv
				    ]);
				}

				// Messages :
				$stmt = $pdo->prepare("
				    SELECT *
				    FROM {$prefix}_eleves
				    WHERE eleves_id = :id
				");

				$stmt->execute([':id' => $eleve_id]);
				$eleveupd_info = $stmt->fetch();
				function e($value) {
				    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
				}
				echo '<p><b>'.DATAC_MOD2.'</b></p><p><a href="database.php?page=modifier&id='.(int)$eleveupd_info['eleves_id'].'"><i class="fa-solid fa-screwdriver-wrench"></i> '.e($eleveupd_info['nom']).' '.e($eleveupd_info['prenom']).' - '.e($eleveupd_info['division']).'</a></p>';
				echo BDAY.DOTS.' ';
				echo ($eleveupd_info['naissance'] === '0000-00-00' || empty($eleveupd_info['naissance']))
				    ? DATAC_MOD3
				    : date("d/m/Y", strtotime($eleveupd_info['naissance']));
				   function showField($label, $value) {
				    echo '<br>'.$label.DOTS.' ';
				    echo empty($value) ? DATAC_MOD3 : htmlspecialchars($value, ENT_QUOTES, 'UTF-8').'.';
				}
				echo '<br>'.SEX.DOTS.' ';
				echo empty($eleveupd_info['sexe']) ? DATAC_MOD3 : e($eleveupd_info['sexe']).'.';

				echo '<br>'.CODE.DOTS.' ';
				echo empty($eleveupd_info['code']) ? DATAC_MOD3 : e($eleveupd_info['code']).'.';
				if ($reserv_could['valeur'] == 2 && $auth_info['valeur'] != 'code') {

				    echo '<br>'.LOGIN.DOTS.' ';

				    if (!empty($multi) && $multi === "ON" && !empty($multipref) && $multipref == 1) {
				        echo e($_SESSION['prefident']);
				    }

				    $loginValue = ($auth_info['valeur'] === 'perso')
				        ? $eleveupd_info['id_perso']
				        : $eleveupd_info['id_constr'];

				    echo e($loginValue);
				}
				echo '<br>'.MAIL2.DOTS.' ';
				if(!$eleveupd_info['mail']) {
					echo DATAC_MOD3;}
				else {
					echo ''.$eleveupd_info['mail'].'. ';
				}
				echo '<br> <br>'.RESPNOM.DOTS.' ';
				if(!$eleveupd_info['resp_nom']) {
					echo DATAC_MOD3;}
				else {
					echo $eleveupd_info['resp_nom'].'. ';
				}
				echo '<br>'.ADD1.DOTS.' ';
				if(!$eleveupd_info['add1']) {
					echo DATAC_MOD3;}
				else {
					echo $eleveupd_info['add1'].'. ';
				}
				echo '<br>'.ADD2.DOTS.' ';
				if(!$eleveupd_info['add2']) {
					echo DATAC_MOD3;}
				else {
					echo $eleveupd_info['add2'].'. ';
				}
				echo '<br>'.CPOSTAL.DOTS.' ';
				if(!$eleveupd_info['cpostal']) {
					echo DATAC_MOD3;}
				else {
					echo $eleveupd_info['cpostal'].'. ';
				}
				echo '<br>'.VILLE.DOTS.' ';
				if(!$eleveupd_info['ville']) {
					echo DATAC_MOD3;}
				else {
					echo $eleveupd_info['ville'].'. ';
				}
				if ($_POST['divcheck'] != $division && isset($checkdiv1['effectif'])) {

				    echo '<br>'.DATAC_ADD3.' '
				        . e($_POST['divcheck'])
				        .' '.EN.' '.$anneesco.' ('
				        . ($checkdiv1['effectif'] - 1).' '.ELEVS1.').';

				    echo '<br>'.DATAC_ADD3.' '
				        . e($division)
				        .' '.EN.' '.$anneesco.' ('
				        . ($checkdiv2['effectif'] + 1).' '.ELEVS1.').';
				}
				echo '</p>';
			}
			$_POST['modif'] = "";
		}
		
		if (isset($_POST['suppr'])) {

		    include('./db/proc/eleve_select.php');

		    if (isset($eleve_info['nom'])) {

		        echo '<p class="maxwidth">'.DATAC_MOD4.'<br><br>'
		            . htmlspecialchars($eleve_info['nom'], ENT_QUOTES, 'UTF-8')
		            . ', '
		            . htmlspecialchars($eleve_info['prenom'], ENT_QUOTES, 'UTF-8')
		            . ', '
		            . htmlspecialchars($eleve_info['division'], ENT_QUOTES, 'UTF-8')
		            . '<br>';

		        echo BDAY.DOTS.' ';

		        echo ($eleve_info['naissance'] == '0000-00-00')
		            ? DATAC_MOD3
		            : date("d/m/Y", strtotime($eleve_info['naissance']));

		        echo '<br>'.SEX.DOTS.' '
		            . ($eleve_info['sexe'] ?: DATAC_MOD3);

		        echo '<br>'.CODE.DOTS.' '
		            . ($eleve_info['code'] ?: DATAC_MOD3);

		        echo '</p>';
				}
				echo '<form method="POST" action="database.php?page=modifier" class="padd2">

				<input type="hidden" name="eleve_id" value="'.(int)$eleve_info['eleves_id'].'">
				<input type="hidden" name="divmaj" value="'.htmlspecialchars($eleve_info['division'], ENT_QUOTES, 'UTF-8').'">

				<input class="bouton boutdb" type="submit" value="'.DATAC_MOD5.'" name="suppr_confirm">
				<input class="bouton boutdb" type="submit" value="'.DATAC_MOD6.'" name="suppr_annule">

				</form>';
			    }
			}
		
		if (isset($_POST['suppr_confirm'])) {

		    $eleve_id = (int)$_POST['eleve_id'];
		    $divmaj = $_POST['divmaj'] ?? '';

		    // 1. suppression élève
		    $stmt = $pdo->prepare("
		        DELETE FROM {$prefix}_eleves
		        WHERE eleves_id = :id
		    ");
		    $stmt->execute([':id' => $eleve_id]);

		    // 2. mise à jour réservations
		    $stmt = $pdo->prepare("
		        UPDATE {$prefix}_freqres
		        SET statut = 1, eleves_id = 0
		        WHERE eleves_id = :id AND statut = 0
		    ");
		    $stmt->execute([':id' => $eleve_id]);

		    $stmt = $pdo->prepare("
		        UPDATE {$prefix}_freqres
		        SET eleves_id = 0
		        WHERE eleves_id = :id
		    ");
		    $stmt->execute([':id' => $eleve_id]);

		    // 3. suppressions liées
		    $stmt = $pdo->prepare("
		        DELETE FROM {$prefix}_freqresref WHERE eleves_id = :id
		    ");
		    $stmt->execute([':id' => $eleve_id]);

		    $stmt = $pdo->prepare("
		        DELETE FROM {$prefix}_savele WHERE eleves_id = :id
		    ");
		    $stmt->execute([':id' => $eleve_id]);

		    $stmt = $pdo->prepare("
		        DELETE FROM {$prefix}_groupele WHERE eleves_id = :id
		    ");
		    $stmt->execute([':id' => $eleve_id]);
			
			// Mise à jour des effectifs :
			$month = date("n");

			$anneesco = ($month > 0 && $month < 9)
			    ? (date("Y") - 1) . '/' . date("Y")
			    : date("Y") . '/' . (date("Y") + 1);

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

			$stmt->execute([
			    ':annee' => $anneesco,
			    ':div' => $divmaj
			]);

			echo '<p>'.DATAC_MOD7;

			if ($divmaj !== '' && isset($anneesco)) {
			    echo '<br>'.DATAC_ADD3.' '
			        . htmlspecialchars($divmaj, ENT_QUOTES, 'UTF-8')
			        .' '.EN.' '.$anneesco.' ('
			        . ($checkdiv['effectif'] - 1).' '.ELEVS1.').';
			}

			echo '</p>';
			
			$_POST['suppr'] = "";
			$_POST['suppr_confirm'] = "";
		}
		
		if (isset($_POST['suppr_annule'])) {
		    unset($_POST['suppr'], $_POST['suppr_confirm'], $_POST['suppr_annule']);
		}
		echo "<script type=\"text/javascript\">
				document.getElementById('eleves').focus();
			</script>";
	}
	
else {
	include('include/noaccess.php');
	echo '<a href="../index.php">'.ACCUEIL.'</a></p>';
}
?>
