<section>
	<article id="art_freq" class="t40l">
	
	<?php
	$freq_gestion_jourscren = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_gestion_jourscren'"));
	
	$freqres_raison_opt = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freqres_raison_opt'"));
	$freqres_max = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freqres_max'"));
	$freq_res_minutesmax = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_res_minutesmax'"));
	$freqres_max_origin = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freqres_max_origin'"));
	$freq_res_nbmaxday = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_res_nbmaxday'"));

	echo '<h1 name="noprint">'.RESA2.'</h1>';
	
	$res_activ = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_resactiv'"));
	$espopt = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'espaces_gestion'"));
	$esp0 = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'espaces_first'"));
	$nb_espedt = mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_espaces WHERE edtoptresa = '1'"));

	if($reserv_could['valeur']==2&&isset($_SESSION['userres_droits'])) {
		$cssbdd = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'version_bdd'"));
		if($cssbdd['valeur']>0.47) {
			$auth_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_resmodauth'"));
			if($auth_info['valeur']=="prenomnom"||$auth_info['valeur']=="pnom") {
				$identmod = "id_constr";
			}
			else if($auth_info['valeur']=="perso") {
				$identmod = "id_perso";
			}
			else {
				$identmod = "code";
			}
		}
		else {
			$identmod = "code";
		}
		$eleve = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE ".$identmod." = '".$_SESSION['coderes']."'");
		$eleve_info = mysqli_fetch_assoc($eleve);
		$eleve_id = $eleve_info['eleves_id'];
		$eleve_div = $eleve_info['division'];
		$eleve_sex = $eleve_info['sexe'];
		echo '<p><b>'.$eleve_info['prenom'].' '.$eleve_info['nom'].' ('.$eleve_info['division'].')</b></p>';
		$specific_res=1;
		$rescheck = mysqli_query($bdd,"SELECT * FROM (SELECT * FROM ".$prefix."_freqres WHERE eleves_id = '$eleve_id') freqres INNER JOIN ".$prefix."_horaires hor ON freqres.hor_name = hor.hor_name LEFT JOIN ".$prefix."_freqactiv fa ON freqres.activ_id = fa.activ_id LEFT JOIN ".$prefix."_espaces esp ON esp.espace_id = freqres.espace_id WHERE freqres.statut ='0' ORDER BY date_freqres ASC, num_creneau ASC");
		if(mysqli_num_rows($rescheck)>0) {
			echo '<br><p>'.RESA3;
			if(mysqli_num_rows($rescheck)>1) { echo PLURIEL; }
			echo ' '.ENCOURS;
			if(mysqli_num_rows($rescheck)>1) { echo ' ('.mysqli_num_rows($rescheck).')'; }
			echo ' :</p>';
			foreach($rescheck as $liste) {
				echo '<form method="POST" name="supprres" action="">';
				echo '<p>';
				if ($liste['user_id']==0) {
					echo '<i class="fa-regular fa-star" title="'.RESA5.'"></i> ';
				}
				else {
					$users_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT nom, prenom, login FROM ".$prefix."_user WHERE id = '".$liste['user_id']."'"));
					echo '<i class="fa-solid fa-star" title="'.RESA4.' ';
					if($users_info['prenom']!='') {
						echo $users_info['prenom'].' ';
					}
					if($users_info['nom']!='') {
						echo $users_info['nom'];
					}
					if($users_info['nom']==''&&$users_info['prenom']=='') {
						echo $users_info['login'];
					}
					echo '"></i> ';
				}
				if($espopt['valeur']==1) { 
					if($liste['espace_id']==0) { echo $esp0['valeur'].'. '; }
					else { echo $liste['espace_nom'].'. '; }
				}
				if($res_activ['valeur']==1||($reserv_could['valeur']==1&&$reseleve_activ['valeur']==1)) {
					if($liste['code_activ']!=""&&$liste['code_activ']!=0) {
						echo $liste['nom_activ'].'. ';
					}
				}
				echo LE.' ';
				echo date('d/m/Y', strtotime(str_replace("/","-",$liste['date_freqres'])));
				$creneau = $liste['hor_name'];
				$hor = mysqli_query($bdd,"SELECT debut, fin FROM ".$prefix."_horaires WHERE hor_name = '".$creneau."'");
				$hor_info = mysqli_fetch_assoc($hor);
				$deb_cren = substr($creneau, 0, 1);
				$fin_cren = substr($creneau, 1, 1);
				echo ' '.$deb_cren.$fin_cren.' : '.FROM.' ';
				$deb = $hor_info['debut'];
				$dh = substr($deb, 0, 2);
				$dm = substr($deb, 3, 2);
				echo ''.$dh.'h'.$dm.' '.TO.' ';
				$fin = $hor_info['fin'];
				$fh = substr($fin, 0, 2);
				$fm = substr($fin, 3, 2);
				echo ''.$fh.'h'.$fm;
				if ($liste['user_id']==0) {
					echo ' - <input class="boutontab" type="submit" value="'.SUPPR.'" name="suppr'.$liste['freqres_id'].'" />';
				}
				if ($liste['raison']!="") {
					echo '<br><i>'.RESAREASON2.' '.$liste['raison'].'</i>';
				}
				echo '</p></form>';
				if(isset($_POST['suppr'.$liste['freqres_id'].''])) {
					$eleve_id = $liste['eleves_id'];
					mysqli_query($bdd,"DELETE FROM ".$prefix."_freqres WHERE eleves_id = '".$eleve_id."' AND freqres_id = '".$liste['freqres_id']."'");
					echo '<script language="Javascript">
					<!--
					document.location.replace("reserver.php");
					// -->
					</script>';
				}
			}
		}
	}

	$espopt = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'espaces_gestion'"));
	$reseleve_creneau = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_creneau'"));
	$reseleve_activ = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_activ'"));
	$reseleve_esp = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_esp'"));
	$verresp = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_verrespace'"));
	
	$hor = mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires");
	
	echo '<h2 name="noprint">'.date("d/m/Y").' - '.date("H:i").'</h2>';
	$heureh = date("H:i:s");
	$soluce = 0;
	$dday = date("Y-m-d");
	$date = new DateTime($dday);
	$datemax = new DateTime($dday);
	$freq_reseleve_dureemax = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_dureemax'"));
	$datemax = new DateTime($dday);
	$dateplus = new DateTime($dday);
	$freq_res_dureemax = $freq_reseleve_dureemax['valeur'];
	$calplus=0;
	$inttest = intval($freq_res_dureemax);
	if($inttest!=0) {
		for($cal=1;$cal<=($inttest-1+$calplus);$cal++) {
			$dateplus = new DateTime($dday);
			$dateplus->modify('+'.$cal.' day');	
			if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_calendrier WHERE date = '".date_format($dateplus, 'Y-m-d')."' AND statut = 0"))>0) {
				$calplus+=1;
			}
		}
		$datemax->modify('+'.($inttest+$calplus).' day');
	}
	else {
		if (preg_match('/^[a-zA-Z]/', $freq_res_dureemax)) {
	        // La variable commence par une lettre
		    $startDay = strtolower(substr($freq_res_dureemax, 0, 3));
			$endDay = strtolower(substr($freq_res_dureemax, 3));
			$currentDay = strtolower(date('D')); // Jour actuel en minuscules
			// Nombre de jours jusqu'au jour d'arrivée à partir du jour actuel
			$currentDayNumber = $daysOfWeek[$currentDay];
			$endDayNumber = $daysOfWeek[$endDay];

			$diffDays = ($endDayNumber - $currentDayNumber + 7) % 7;

			// Ajouter la différence de jours au $datemax
			$datemax->modify('+' . $diffDays . ' day');
	    } else {
	        $datemax->modify('+'.($inttest+$calplus).' day');
	    }
	}
	$num_cren = 0;
	$_SESSION['num_cren'] = $num_cren;

	// Boucle pour définir le créneau actuel :
	while($creneau_info = mysqli_fetch_assoc($hor)) {
		if($heureh >= $creneau_info['debut']&&$heureh < $creneau_info['fin']) {
			$soluce = 1;
			$num_cren = $creneau_info['num_creneau'];
			$_SESSION['num_cren'] = $num_cren;
			break;
		}
	}

	$individu=1;
	include('./db/proc/freq_res_options.php');
	$freq_reseleve_cgtmdp = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve_cgtmdp'"));
	if($freq_reseleve_cgtmdp['valeur']==1&&$_SESSION['reserv_could']==2) {
		if(isset($_POST['mdp2'])) {
			$mdp = mysqli_real_escape_string($bdd,$_POST['mdp2']);
			$hashed_password = password_hash($mdp, PASSWORD_DEFAULT);
			$sel = '0';
			mysqli_query($bdd,"UPDATE ".$prefix."_eleves SET mdp='".$hashed_password."', sel = '".$sel."' WHERE eleves_id = '".$eleve_id."'");
		}
		if(isset($_POST['language'])) {
			$lang = htmlspecialchars($_POST['language']);
			mysqli_query($bdd,"UPDATE ".$prefix."_eleves SET lang = '".$lang."' WHERE eleves_id = '".$eleve_id."'");
			$_SESSION['lang'] = $lang;
			echo '<script language="Javascript">
				<!--
				document.location.replace("reserver.php");
				// -->
				</script>';
		}
		echo '<br><a onmousedown="toggleDiv(\'mdpdiv\');"><input style="margin-top:20px;font-size:0.7em;" type="button" value="'.PWCHG.'" /></a>
		<div id="mdpdiv" style="display:none;"> <form method="post" name="pass" action="" class="padd2"><input class="inptxti" type="password" name="mdp1" minlength="12" maxlength="40" value="" placeholder="'.NEWPASS2.'" id="id_password1" /><i class="fa-solid fa-eye" id="eye1" onclick="showPass1()" style="margin-left: -26px; cursor: pointer;"></i><br><input class="inptxti" type="password" name="mdp2" minlength="12" maxlength="40" value="" placeholder="'.NEWPASS3.'" id="id_password2" onBlur="checkPass()" /><i class="fa-solid fa-eye" id="eye2" onclick="showPass2()" style="margin-left: -26px; cursor: pointer;"></i><br><div id="divcomp"><input class="bouton inptxti boutfreq" type="button" value="'.VALID.'" /></div></form></div>';
				
		echo '<script language="Javascript">
			function showPass1() {
			  var x = document.getElementById("id_password1");
			  var y = document.getElementById("eye1");
			  if (x.type === "password") {
			    x.type = "text";
			    y.className = "fa-solid fa-eye-slash";
			  } else {
			    x.type = "password";
			    y.className = "fa-solid fa-eye";
			  }
			}
			function showPass2() {
			  var x = document.getElementById("id_password2");
			  var y = document.getElementById("eye2");
			  if (x.type === "password") {
			    x.type = "text";
			    y.className = "fa-solid fa-eye-slash";
			  } else {
			    x.type = "password";
			    y.className = "fa-solid fa-eye";
			  }
			}
			function checkPass() {
				var champA = document.getElementById("id_password1").value;
				var champB = document.getElementById("id_password2").value;
				var div_comp = document.getElementById("divcomp");
				if(champA == champB) {
					divcomp.innerHTML = "<input class=\'bouton inptxti boutfreq\' type=\'submit\' value=\''.NEWPASS4.'\' />";
				}
				else {
					divcomp.innerHTML = "'.NEWPASS5.'";
					setTimeout(() => {  
						divcomp.innerHTML = "<input class=\'bouton inptxti boutfreq\' type=\'button\' value=\''.VALID.'\' />";
						}, 2000);
					}
			}
		</script>';
		if (count($languages) > 1): ?>
		<br> <br><form method="post" id="language-form">
            <select name="language" id="language-select">
                <?php
                // Générer les options du sélecteur
                foreach ($languages as $code => $name) {
                    echo '<option value="' . htmlspecialchars($code) . '"' . ($code === $eleve_info['lang'] ? ' selected' : '') . '>' . htmlspecialchars($name) . '</option>';
                }
                ?>
            </select> <input name="langval" type="submit" value="<?php echo VALID; ?>" />
        </form>
		<?php endif;		
	}
	include('db/proc/reserver_sigb.php');
	include('db/proc/reserver_archives.php');
	echo '</article>';

	// affichage EDT si option activée :
	$crprechoix_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_resprintedt'"));
	if ($crprechoix_info['valeur']==2) {
		echo '<article class="t40r">
		<div name="noprint" class="preins paddr1"><br><h3>'.EDT0.'</h3>';
		include('db/proc/edt_aff_blocnotes.php');
		$check_imgmode_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'edt_imgmode'"));
		if($dossier = scandir('./img/edt/'.$prefix, SCANDIR_SORT_DESCENDING)) {
			$tab_save = array();
			foreach($dossier as $fichier) {
				if($fichier != '.' && $fichier != '..' && substr($fichier,0,5) != 'nbins') {
					if(substr($fichier,0,6) == 'idlog_'||substr($fichier,0,4) == 'cdi_') {
						$line = '<img width="500" src="./img/edt/'.$prefix.'/' . $fichier . '?'.date('Ymd').date('His').'" /><br>';
						array_push ($tab_save,$line);
					}
					if($nb_espedt>0) {
						$espaces = mysqli_query($bdd,"SELECT espace_id, espace_nom, edtopt, edtoptresa FROM ".$prefix."_espaces WHERE edtoptresa = 1");
						foreach($espaces as $espaces_info) {
							$testl = strlen(str_replace(' ','_', $espaces_info['espace_nom']));
							if(substr($fichier,0,$testl) == str_replace(' ','_', $espaces_info['espace_nom'])) {
								$line = '<img width="500" src="./img/edt/'.$prefix.'/' . $fichier . '?'.date('Ymd').date('His').'" /><br>';
								array_push ($tab_save,$line);
							}
						}
					}
				}
			}
			arsort($tab_save);
			$count = count($tab_save);
			if($count>0){
				if ($check_imgmode_info['valeur']=="gen") {
					for($i=($count-1);$i>-1;$i--) {
						echo $tab_save[$i];
					}
					echo '<br>';
				}
				else if ($check_imgmode_info['valeur']=="spe") {
					rsort($tab_save);
					for($i=0;$i<$count;$i++) {
						echo $tab_save[$i];
					}
					echo '<br>';
				}

			}
		}
	}
	else if ($crprechoix_info['valeur']==1) {
		echo '<article class="edt_affres"><h3>'.EDT0.'</h3>';
		include('db/proc/edt_aff_blocnotes.php');
		include('db/proc/edt_res_affiches.php');
	}
	?>
	</article>
</section>