<?php
if($droits==2||$droits==6||$droits==4) {
	if(isset($_SESSION['ccren'])) {
		$birthday = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_birthday_img'"));
		$ajustauto = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'freq_res_actesp_autochange'"));
		// récupération de l'ordre d'affichage souhaité
		$ordreaff = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_ordreaff'");
		$ordreaff_info = mysqli_fetch_assoc($ordreaff);
		if($ordreaff_info['valeur']=="div"||$ordreaff_info['valeur']=="act") {
			$ordre = "ORDER BY eleves.division ASC, eleves.nom ASC, eleves.prenom ASC";
		}
		else if($ordreaff_info['valeur']=="nom") {
			$ordre = "ORDER BY eleves.nom ASC, eleves.prenom ASC";
		}
		else if($ordreaff_info['valeur']=="hor") {
			$ordre = "ORDER BY freqres.freqres_id DESC";
		}
		else if($ordreaff_info['valeur']=="esp") {
			$ordre = "ORDER BY espaces.espace_nom ASC, eleves.division ASC, eleves.nom ASC, eleves.prenom ASC";
		}
		else if($ordreaff_info['valeur']=="act"&&($res_activ['valeur']==1||($reseleve_could['valeur']==1&&$reseleve_activ['valeur']==1))) {
			$ordre = "ORDER BY activites.nom_activ ASC, eleves.division ASC, eleves.nom ASC, eleves.prenom ASC";
		}
		else { $ordre = "ORDER BY eleves.division ASC, eleves.nom ASC, eleves.prenom ASC"; }
		// affichage des réservations
		$dday = date("Y-m-d");
		$ccren = $dday.$_SESSION['ccren'];
		$reserve_select = "SELECT freqres.eleves_id, freqres.date_freqres, freqres.freqres_id, freqres.code_freqres, freqres.hor_name, freqres.user_id, freqres.statut, freqres.code_activ AS fcodeactiv, espaces.espace_id, espaces.espace_nom, eleves.nom, eleves.prenom, eleves.division, eleves.naissance, activites.activ_id, activites.code_activ AS acodeactiv, activites.nom_activ 
		FROM (
			SELECT * 
			FROM ".$prefix."_freqres
			WHERE code_freqres LIKE '".$ccren."%' AND statut = '0' 
		) freqres
		INNER JOIN ".$prefix."_eleves eleves
		ON freqres.eleves_id = eleves.eleves_id
		LEFT JOIN ".$prefix."_espaces espaces
		ON espaces.espace_id = freqres.espace_id 
		LEFT JOIN ".$prefix."_freqactiv activites
		ON activites.activ_id = freqres.activ_id 
		LEFT JOIN ".$prefix."_user user
				ON user.id = freqres.user_id 
		".$ordre."";
		$reserve = mysqli_query($bdd,$reserve_select);
		$nb_reserve = mysqli_num_rows($reserve);
						
		if($nb_reserve != 0) {
			echo '<div name="reserve"><h3><i class="fas fa-angle-double-right"></i> '.RESA6.' (<span id="reservs_nb">'.$nb_reserve.'</span>)'.DOTS.'</h3>';
			echo '<table name="form">';
			echo '<thead><tr><th></th><th>'.DIV_TINY.'</th><th>'.ELEVS4.'</th><th>'.ACTIV.'</th>';
			if($espopt['valeur']==1) { echo '<th>'.ZONE.'</th>'; }
			echo '<th></th></tr></thead>
				<tbody>';
			foreach($reserve as $validation) {
				echo '<tr id="tr'.$validation['eleves_id'].'v'.$validation['freqres_id'].'">';
				$reserv_could=mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_reseleve'"));
				if ($reserv_could['valeur']!=0) {
					if ($validation['user_id']==0) {
						echo '<td><i class="fa-regular fa-star" title="'.RESA5.'"></i></td> ';
					}
					else {
						$users_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT nom, prenom, login FROM ".$prefix."_user WHERE id = '".$validation['user_id']."'"));
						echo '<td><i class="fa-solid fa-star" title="Réservation par ';
						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></td> ';
					}
				}
				echo '<td>'.$validation['division'].'</td><td>'.$validation['nom'].' '.$validation['prenom'].'</td><td>';
				$activd = mysqli_query($bdd,"SELECT * FROM ".$prefix."_freqactiv WHERE default_activ = 1");
				$nom_activd = mysqli_fetch_assoc($activd);
				echo '<div class="box"><select id="selectactiv'.$validation['freqres_id'].'" name="selectact">';
				echo '<option value="ZERO"></option>';
				$liste_activ = mysqli_query($bdd,"SELECT code_activ, nom_activ FROM ".$prefix."_freqactiv WHERE activ_activ = 1 AND code_activ <> 'ZERO' ORDER BY nom_activ ASC");
				foreach($liste_activ as $liste) {
					echo '<option value="'.$liste['code_activ'].'"';
					if($res_activ['valeur']==1||($reseleve_could['valeur']==1&&$reseleve_activ['valeur']==1)) {
						if($validation['fcodeactiv']==$liste['code_activ']) {
							echo ' selected ';
						}
					}
					else if(isset($_SESSION['code_activ'])&&$verrtest['valeur']==0) {
						if($_SESSION['code_activ']==$liste['code_activ']) {
							echo ' selected ';
						}
					}
					else {
						if(@$nom_activd['code_activ']==$liste['code_activ']) {
							echo ' selected ';
						}
					}
					echo '>'.$liste['nom_activ'].'</option>';
				}
				echo '</select></div>';
				echo '</td>';
				if($espopt['valeur']==1) {
					echo '<td>
					<div class="box"><select id="espace'.$validation['freqres_id'].'" name="espace" value="">';
					$liste_activ = mysqli_query($bdd,"SELECT espace_id, espace_nom FROM ".$prefix."_espaces ORDER BY espace_nom ASC");
					echo '<option value="0">'.$esp0['valeur'].'</option>';
					foreach($liste_activ as $liste) {
						echo '<option value="'.$liste['espace_id'].'"';
						if($validation['espace_id']==0) { 
							if($liste['espace_id']==0) { echo ' selected '; }
						}
						else { 
							if($validation['espace_id']==$liste['espace_id']) { 
								echo ' selected '; }
						}
						echo '>'.$liste['espace_nom'].'</option>';
					}
					echo '</select></box></td>';
				}
				echo '<td>';
				//gestion du seuil
				$dday = date("Y-m-d");
				$ccren = $dday.$_SESSION['ccren'];
				if($espopt['valeur']==0) {
					$inscrits_select = "SELECT freq.eleves_id, freq.date_freq, freq.hor_name, freq.cas, freq.h_inscription, eleves.nom, eleves.prenom, eleves.division 
					FROM (
						SELECT * 
						FROM ".$prefix."_freq
						WHERE date_freq = '".$dday."' AND hor_name = '".$_SESSION['ccren']."' AND cas NOT IN ('sor', 'exc')
					) freq 
					INNER JOIN ".$prefix."_eleves eleves
					ON freq.eleves_id = eleves.eleves_id
					ORDER BY eleves.division ASC, eleves.nom DESC, eleves.prenom ASC";
					$inscrits = mysqli_query($bdd,$inscrits_select);
					$nb_inscrits = mysqli_num_rows($inscrits);
					$sin_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_seuilnbi'"));
					$sin_valeur = $sin_info['valeur'];
					$sir_info = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_seuilreaci'"));
					$sir_valeur = $sir_info['valeur'];
				}
				if($espopt['valeur']==1||$sin_valeur==0||$nb_inscrits<$sin_valeur) {
					echo '<input class="boutontab" type="submit" value="Inscrire" onclick="ok'.$validation['eleves_id'].'v'.$validation['freqres_id'].'(this);" name="ok'.$validation['eleves_id'].'v'.$validation['freqres_id'].'" /> ';
				}
				else if($sir_valeur=='stopp') {
					echo FREQ_RESA1.' ';
				}				
				if($_SESSION['nobuttonenleverresa']!='0') { echo '<input class="boutontab" type="submit" value="'.OTER.'" onclick="no'.$validation['eleves_id'].'v'.$validation['freqres_id'].'(this);" name="no'.$validation['eleves_id'].'v'.$validation['freqres_id'].'" />'; }
				echo '</td><td class="noborder">';
				$retards = mysqli_query($bdd,"SELECT * FROM ".$prefix."_retards WHERE eleves_id = '".$validation['eleves_id']."' AND retour_date < '".date('Y-m-d')."' ORDER BY retour_date ASC");
				$retards_nb = mysqli_num_rows($retards);
				$ret='';
				if($retards_nb!=0) {
					$ret = '<span style="font-size: 1.5em; color: #D90606;"><i class="fa-solid fa-stopwatch" title="';
					if($retards_nb>1) { $i=1; }
					while($retards_info = mysqli_fetch_assoc($retards)) {
						if($retards_nb>1) { $ret .= ''.$i.'. '; }
						if($retards_info['titre']!="") {
							$ret .= $retards_info['titre'].'. ';
						}
						if($retards_info['retour_date']!="0000-00-00") {
							$date = date('d/m/Y', strtotime(str_replace("/","-",$retards_info['retour_date'])));
							$ret .= 'Retour le '.$date.'. ';
						}
						if($retards_info['niv_alerte']!=0) {
							$ret .= 'Action effectuée : ';
							if($retards_info['niv_alerte']=="1") { $ret .= 'Premier rappel'; }
							else if($retards_info['niv_alerte']=="2") { $ret .= 'Deuxième rappel'; }
							else if($retards_info['niv_alerte']=="3") { $ret .= 'Facturation'; }
							$ret .= '. ';
						}
						if($retards_nb>1) { $ret .= ''; $i++; }
					}
					$ret .= '"></i></span>';
					echo $ret;
				}
				echo '</td><td class="noborder" name="noprint">';
				$exclusion = mysqli_query($bdd,"SELECT * FROM ".$prefix."_exclusions exclusions LEFT JOIN ".$prefix."_exclucauses causes ON exclusions.exclucause_id = causes.exclucause_id WHERE eleves_id = '".$validation['eleves_id']."' AND (date_info >= '".date('Y-m-d')."' OR date_fin >= '".date('Y-m-d')."')");
				$exc_nb = mysqli_num_rows($exclusion);
				$exctxt='';
				if($exc_nb!=0) {
					$exc_info = mysqli_fetch_assoc($exclusion);
					$exctxt = '<span style="font-size: 1.5em; color: #D90606;"><i class="fa-solid fa-ban" title="';
					$exctxt .= FREQT2.' '.FROM2.' '.substr($exc_info['date_exclusion'],8,2).'/'.substr($exc_info['date_exclusion'],5,2).'/'.substr($exc_info['date_exclusion'],0,4).' '.TO2.' '.substr($exc_info['date_fin'],8,2).'/'.substr($exc_info['date_fin'],5,2).'/'.substr($exc_info['date_fin'],0,4).'.';
					$exctxt .= '"></i></span>';
					echo $exctxt;
				}
				echo '</td><td class="noborder" name="noprint">';
				$limits = mysqli_query($bdd,"SELECT * FROM ".$prefix."_limits limits LEFT JOIN ".$prefix."_limitstxt txt ON limits.limittxt_id = txt.limittxt_id WHERE eleves_id = '".$validation['eleves_id']."' AND date_fin >= '".date('Y-m-d')."'");
				$limits_nb = mysqli_num_rows($limits);
				$limtxt='';
				if($limits_nb!=0) {
					$limtxt = '<td class="noborder" name="noprint"><span style="font-size: 1.5em; color: #D90606;"><i class="fa-solid fa-hand" title="';
					if($limits_nb>1) { $i=1; }
					foreach($limits as $limit_info) {
						if($limits_nb>1) { if($i>1) { $limtxt .= ' '; } $limtxt .= $i.'. '; }
						$limtxt .= $limit_info['limits_txt'].' '.FROM3.' '.substr($limit_info['date_debut'],8,2).'/'.substr($limit_info['date_debut'],5,2).'/'.substr($limit_info['date_debut'],0,4).'';
						if($limit_info['date_fin']>=date('Y-m-d')) {
							$limtxt .= ' '.TO3.' '.substr($limit_info['date_fin'],8,2).'/'.substr($limit_info['date_fin'],5,2).'/'.substr($limit_info['date_fin'],0,4).'.';
						}
						if($limits_nb>1) { $limtxt .= ''; $i++; }
					}
					$limtxt .= '"></i></span>';
					echo $limtxt;
				}
				echo '</td><td class="noborder" name="noprint">';
				$birtxt='';
				if($birthday['valeur']==1&&(substr($validation['naissance'],5,5)==date('m-d'))) {
					$naissance = $validation['naissance'];
					$annee = substr($naissance, 0, -6);
					$mois = substr($naissance, 5, -3);
					$jour = substr($naissance, -2);
					$date = $jour.'/'.$mois.'/'.$annee;							
					$age = Age($date);
					$birtxt = '<span style="font-size: 1.5em; color: #D90606;"><i class="fa-solid fa-cake-candles" title="'.$age.' ans"></i></span>';
					echo $birtxt;
				}
				$to1 = $ret.' '.$exctxt.' '.$limtxt.' '.$birtxt;
				$to2 = str_replace("<", "&lt;", $to1);
				$to3 = str_replace("\"", "'", $to2);
				$toins = str_replace(">", "&gt;", $to3);
				echo '<input type="hidden" name="infos'.$validation['freqres_id'].'" id="infos'.$validation['freqres_id'].'" value="'.$toins.'" /></td>';

				echo '</tr>';
				echo '<script type="text/javascript">
					function ok'.$validation['eleves_id'].'v'.$validation['freqres_id'].'(param) {
					var param = "inscrire";
					document.getElementById("tr'.$validation['eleves_id'].'v'.$validation['freqres_id'].'").style.display = "none";
					var eleve_id = "'.$validation['eleves_id'].'"; 
					var code_freqres = "'.$validation['code_freqres'].'"; 
					var freqres_id = "'.$validation['freqres_id'].'";
					var date_freqres = "'.$validation['date_freqres'].'";
					var sel = document.getElementById("selectactiv'.$validation['freqres_id'].'");
					var selectactiv = sel.value;
					var selectedind = sel.selectedIndex;
					var selectactivtxt = sel.options[sel.selectedIndex].text; 
					var typa = document.getElementsByName("selectact");';              
		            // condition freq_res_actesp_auto :
		            if($ajustauto['valeur']=='1') {
			            echo 'for(i = 0; i < typa.length; i++) {
			                typa[i].selectedIndex = selectedind;
			            } ';
			        }
					if($espopt['valeur']==1) {
						echo 'var esp = document.getElementById("espace'.$validation['freqres_id'].'");
						var espace = esp.value; 
						var espaceind = esp.selectedIndex; 
						var espacetext = esp.options[esp.selectedIndex].text;
						var espid = "nb_tresp" + espace; 
						var typ = document.getElementsByName("espace");  ';              
			            // condition freq_res_actesp_auto :
			            if($ajustauto['valeur']=='1') {
				            echo 'for(i = 0; i < typ.length; i++) {
				                typ[i].selectedIndex = espaceind;
				            }	';
				        }
					}
					else {
						echo 'var espace = ""; ';
					}
					echo 'var rnr = document.getElementById("reservs_nb").textContent;
					var new_rnr = rnr-1;
					document.getElementById("reservs_nb").textContent = new_rnr;
					var rnv = document.getElementById("inscrits_nb").textContent;
					var new_rnv = parseInt(rnv)+1;
					document.getElementById("inscrits_nb").textContent = new_rnv; ';
					if($espopt['valeur']==1) {
						echo 'var rne_id = document.getElementById(espid);
						if(rne_id!=null) {
							var rne = rne_id.textContent;
							var new_rne = parseInt(rne)+1;
							document.getElementById(espid).textContent = new_rne; 
						} ';						
					}
					echo 'var table = document.getElementById("listeinscrits");
					var trnew = document.createElement("tr");
					var td = document.createElement("td");
					td.innerHTML = "'.$validation['division'].' - '.$validation['nom'].' '.$validation['prenom'].'";
					trnew.appendChild(td); ';
					if($droits==3&&$check_consultactiv_opt['valeur']==0) { }
					else {
						echo 'var td = document.createElement("td");
						td.innerHTML = selectactivtxt;
						trnew.appendChild(td); ';
					}
					if($espopt['valeur']==1) {
						echo 'var td = document.createElement("td");
						td.innerHTML = espacetext;
						trnew.appendChild(td); ';
					}
					if($droits==2||($droits==4&&$buttonchoix['valeur']==1)||$droits==6&&$buttonchoix['valeur']==1) {
						echo 'var td = document.createElement("td");
						td.innerHTML = "<a href=\'freq.php\'>'.FREQ_RESA2.'</a>";
						trnew.appendChild(td);
						var td = document.createElement("td");
						var val = document.getElementById("infos'.$validation['freqres_id'].'").value;
						var val1 = val.replace("&lt;","<");
						var val2 = val.replace("&gt;",">");
						td.innerHTML = val2;
						trnew.appendChild(td); ';
					}
					echo 'table.appendChild(trnew);					
					$.ajax({
					    type: "POST",
					    data: { param: param, eleve_id: eleve_id, code_freqres: code_freqres, selectactiv: selectactiv, freqres_id: freqres_id, date_freqres: date_freqres, espace: espace, val: val },
					    url: "js/idl/freq_ind_syn.php",
					   });
					}
				</script>';
				echo '<script type="text/javascript">
					function no'.$validation['eleves_id'].'v'.$validation['freqres_id'].'(param) {
					var param = "enlever";
					document.getElementById("tr'.$validation['eleves_id'].'v'.$validation['freqres_id'].'").style.display = "none";
					var element = document.getElementById("aucun");
					if(element) {
						element.style.display = "none";
					}
					var eleve_id = "'.$validation['eleves_id'].'"; 
					var freqres_id = "'.$validation['freqres_id'].'";
					var rnr = document.getElementById("reservs_nb").textContent;
					var new_rnr = rnr-1;
					document.getElementById("reservs_nb").textContent = new_rnr;
					$.ajax({
					    type: "POST",
					    data: { param: param, eleve_id: eleve_id, freqres_id: freqres_id },
					    url: "js/idl/freq_ind_syn.php",
					   });
					}
				</script>';							
			}
			echo '</tbody></table></div>';
		}
	}		
}
?>