<?php
echo '<meta charset="utf-8" />';
if(isset($_SESSION['user_droits'])) {
	if($_SESSION['user_droits'][4]!="2")
	{
		echo '<p class="noaccess">'.NOMODULE.'<br><a href="../index.php">'.ACCUEIL.'</a></p>';
	}
	else {
		?><style type="text/css">
		#mpa5 { background-color: #fff; }
		#mpa5 td { border: 3px #7D7777 solid; }
		#mpa4 td { border: 0; }
		</style><?php	
		$hor_temps = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'hor_temps'"));
		$crecode = explode(';',$hor_temps['valeur']);
		echo '<h1>'.PARAC_HOR1.'</h1>';
		echo '<h2>'.PARAC_HOR2.'</h2>';
		
		if(isset($_POST['fuseau'])) {
			$newfuseau = $_POST['bigzone'].'/'.$_POST['fuseau'];
			if($newfuseau!=$fuseau) {
				mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur = '".$newfuseau."' WHERE param_nom = 'fuseau'");
			}
			echo '<script language="Javascript">
			<!--
			document.location.replace("param.php?page=horaires");
			// -->
			</script>';
		}
		
		echo '<p>Fuseau : <b>'.$fuseau.'</b> - '.date("d/m/Y").' - <b>'.date("H:i").'</b>.</p>';
		$bizones = array('Africa','America','Antarctica','Arctic','Asia','Atlantic','Australia','Europe','Indian','Pacific');
		echo '<form method="POST" action="">
		<table class="noborder">
			<tr><td colspan="2">'.PARAC_HOR3.'</td></tr>
			<tr><td>Zone :</td><td><div class="box"><select name="bigzone" id="bigzone" onchange=\'zone()\'><option></option>';
			foreach($bizones as $bizone) {
				echo '<option';
				echo '>'.$bizone.'</option>';
			}echo '</select></div>
			</td></tr>
			<tr><td>Fuseau :</td><td><div id=\'fuseau\' style=\'display:inline\'>
				<div class="box"><select name=\'fuseau\'>
					<option value=\'-1\'></option>
				</select></div>
			</div></td></tr>
			<tr><td colspan="2" class="right"><input class="bouton boutparam" type="submit" value="'.VALID.'" name="fusvalid" /></td></tr>	
		</table></form>';
		
		echo '<h2 id="hor">'.PARAC_HOR4.'</h2>'.PARAC_HOR5;
		echo PARAC_HOR19;
		// traitement
		if (isset($_POST['moment']) && is_array($_POST['moment'])) {
		    // 1. Nettoyer et convertir en chaîne : M;A;P;R
		    $moments = array_map('trim', $_POST['moment']); // Trim chaque valeur
		    $momentStr = implode(';', $moments); // Convertit en chaîne "M;A;P;R"
		    // 2. Échapper la chaîne pour éviter les injections
		    $momentStrSafe = mysqli_real_escape_string($bdd, $momentStr);
		    // 3. Mise à jour en base de données
		    $sql = "UPDATE {$prefix}_parametres SET valeur = '$momentStrSafe' WHERE param_nom = 'hor_temps'";
		    $result = mysqli_query($bdd, $sql);	
		    $hor_temps = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'hor_temps'"));
			$crecode = explode(';',$hor_temps['valeur']);	   
		}
		// formulaire
		echo '<form method="post">';
	    foreach (MOMENT as $key => $label): 
	        echo '<input type="checkbox" name="moment[]" value="'.$key.'" id="moment_'.$key.'"';
	        if(in_array($key, $crecode)) { echo ' checked '; }
	        echo '><label for="moment_'.$key.'">'.$key.' - '.$label.'</label> ';
	        
	    endforeach;
	    echo '<input class="bouton boutparam" type="submit" value="'.VALID.'" name="hor_temps" />
		</form>';
		echo PARAC_HOR20;
		if(isset($_POST['horaires'])) {
			$checkt = array();
			for($i=1;$i<21;$i++) {
				$deb_hor_name = $_POST['cren'.$i.'']; // M, A, P, R
				$fin_hor_name = $_POST['nb'.$i.'']; // numéro pour chaque temps
				if($deb_hor_name!='') {
					array_push($checkt,$deb_hor_name.$fin_hor_name);
				}
			}
			if(count(array_unique($checkt))<count($checkt)) {
			    echo '<p class="signal">'.PARAC_HOR6;
			}
			else {
			   	// Création de la boucle pour inscrire ou modifier les horaires :
				for($i=1;$i<21;$i++) {
					$creneau = mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires WHERE num_creneau = '".$i."'");
					$creneau_nb = mysqli_num_rows($creneau);
					$creneau_info = mysqli_fetch_assoc($creneau);
					
					// Récupération des infos des champs :
					$deb_hor_name = $_POST['cren'.$i.'']; // M, A, P, R
					$fin_hor_name = $_POST['nb'.$i.'']; // numéro pour chaque temps
					$debut = $_POST['debut'.$i.''].':00';
					$fin = $_POST['fin'.$i.''].':00';

					if($i<20) { $debut_suiv = $_POST['debut'.($i+1).''].':00'; }
					
					// Transformation des champs pour la BDD :
					$num_creneau = $i;
					$hor_name = $deb_hor_name . $fin_hor_name;
					$crename = $moment1;
					$key = array_search($deb_hor_name,$crecode);
					$period = $crename[$key];

					echo '<p class="signal">';							
					// Gestion des insert et update pour chaque créneau :
					if($deb_hor_name==""||$fin_hor_name==""||$debut=="::00"||$fin=="::00") {
						// suppression de futurs events si le créneau est supprimé
						if(isset($creneau_info['hor_id'])) {
							$check_events = mysqli_query($bdd,"SELECT * FROM ".$prefix."_edtevent WHERE hor_id = '".$creneau_info['hor_id']."' AND week >= '".date('oW')."'");
							foreach ($check_events as $check_event) {
								mysqli_query($bdd,"DELETE FROM ".$prefix."_userevent WHERE uid = '".$check_event['uid']."'");
								mysqli_query($bdd,"DELETE FROM ".$prefix."_espaces_event WHERE uid = '".$check_event['uid']."'");
							}
							mysqli_query($bdd,"DELETE FROM ".$prefix."_edtevent WHERE hor_id = '".$creneau_info['hor_id']."'");
							// suppression du créneau
							mysqli_query($bdd,"DELETE FROM ".$prefix."_horaires WHERE num_creneau = '".$num_creneau."'");
						}
					}
					else if($debut_suiv!=":00"&&$fin!=$debut_suiv) { 
						echo PARAC_HOR7.' '.$period.' '.$fin_hor_name.PARAC_HOR8.'<br>';
					} 
					else if(isset($_SESSION['chev'])&&$debut!=$_SESSION['chev']) { 
						echo PARAC_HOR7.' '.$period.' '.$fin_hor_name.PARAC_HOR9.'<br>';
					} // vérification de début et fin du créneau
					else if($creneau_nb==0) {
						mysqli_query($bdd,"INSERT INTO ".$prefix."_horaires (hor_id, hor_name, num_creneau, debut, fin, hor_freq, hor_resa, quota_freq, quota_resa) VALUES ('', '".$hor_name."', '".$num_creneau."', '".$debut."', '".$fin."', '001', '001', '000', '000')");
						if($deb_hor_name=="P") {
							mysqli_query($bdd,"UPDATE ".$prefix."_horaires SET hor_freq='000', hor_resa='000' WHERE num_creneau = '".$num_creneau."'");
						}
					}
					else {
						$infos_cren = mysqli_fetch_assoc(mysqli_query($bdd, "SELECT * FROM ".$prefix."_horaires WHERE num_creneau='".$num_creneau."'"));
			            $hf = $infos_cren['hor_freq'];
			            $hr = $infos_cren['hor_resa'];
			            $hqf = $infos_cren['quota_freq'];
			            $hqr = $infos_cren['quota_resa'];
						if(isset($_POST['hf'.$i.''])) { $hf = substr_replace($hf,"001",0,3); } 
						else { $hf = substr_replace($hf,"000",0,3); }
						if(isset($_POST['hr'.$i.''])) { $hr = substr_replace($hr,"001",0,3); } 
						else { $hr = substr_replace($hr,"000",0,3); }
						$hqf = substr_replace($hqf,str_pad($_POST['hqf'.$i.''],3,"0", STR_PAD_LEFT),0,3);
						$hqr = substr_replace($hqr,str_pad($_POST['hqr'.$i.''],3,"0", STR_PAD_LEFT),0,3);
									            
						mysqli_query($bdd,"UPDATE ".$prefix."_horaires SET hor_name='".$hor_name."', debut='".$debut."', fin='".$fin."', hor_freq='".$hf."', hor_resa='".$hr."', quota_freq='".$hqf."', quota_resa='".$hqr."' WHERE num_creneau = '".$num_creneau."'");
					}
					echo  '</p>';
					// Gestion des chevauchements :
					$_SESSION['chev'] = $fin;
					$_SESSION['plage'] = $hor_name;
				}
			}			
			unset($_SESSION['chev']);
			unset($_SESSION['plage']);
		}
		echo '<div style="overflow: auto;  white-space: nowrap;"><form method="POST" action="param.php?page=horaires#hor" class="padd4">
		<table id="install" class="paramform">
		<tr style="text-align:center;"><th>N°</th><th>'.PARAC_HOR10.'</th><th>'.PARAC_HOR11.'</th><th>'.PARAC_HOR12.'</th><th>'.PARAC_HOR13.'</th><th>'.PARAC_HOR15.'<br>'.PARAC_HOR13.'</th><th>'.PARAC_HOR14.'</th><th>'.PARAC_HOR15.'<br>'.PARAC_HOR14.'</th></tr>';
			for($i=1;$i<21;$i++) {
				$creneau = mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires WHERE num_creneau = $i");
				$creneau_nb = mysqli_num_rows($creneau);
				$creneau_info = mysqli_fetch_assoc($creneau);
				if($i<20) { 
					$suivant = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires WHERE num_creneau = '".($i+1)."'"));
				}
				echo '<tr>
				<td style="text-align:right;">'.$i.'</td>
				<td>
					<div class="box"><select name="cren'.$i.'"><option></option>';
					$crename = $moment1;
					for($nuchor=0;$nuchor<count($crecode);$nuchor++) {
						echo '<option value="'.$crecode[$nuchor].'"';
						if(@substr($creneau_info['hor_name'], 0, 1)==$crecode[$nuchor]) {
							echo ' selected ';
						}
						echo '>'.MOMENT[$crecode[$nuchor]].'</option>';
					}
					echo'</select></div>
					<div class="box boxh"><select name="nb'.$i.'"><option></option>';
					$cren_num = range('1','10');
					for($nuc=0;$nuc<10;$nuc++) {
						echo '<option';
						if(@substr($creneau_info['hor_name'], 1, 1)==$cren_num[$nuc]) {
							echo ' selected ';
						}
						echo '>'.$cren_num[$nuc].'</option>';
					}
					echo '</select></div>
				</td>
				<td>
					<input type="time" class="inptxt time"';
					if(isset($_SESSION['finprec'])&&isset($creneau_info['debut'])&&substr($creneau_info['debut'],0,5)!=$_SESSION['finprec']) {
						echo ' style="color:red;" ';
					}
					echo ' name="debut'.$i.'" value="'.@substr($creneau_info['debut'],0,5).'" />
				</td>
				<td>
					<input type="time" class="inptxt time" name="fin'.$i.'"';
					if(@$suivant['debut']!=""&&@substr($suivant['debut'],0,5)!=@substr($creneau_info['fin'],0,5)) {
						echo ' style="color:red;" ';
					}
					echo ' value="'.@substr($creneau_info['fin'],0,5).'" />
				</td>
				<td class="horparam">';
					if($creneau_nb>0) {
						echo '<input type="checkbox" class="inptxt" name="hf'.$i.'"';
						if(substr($creneau_info['hor_freq'],0,3)=="001") { echo 'checked'; }
						echo ' />';
					}
				echo '</td>
				<td class="horparam">';
					if($creneau_nb>0) {
						echo '<input type="number" class="inptxt horparam" min="0" max="999" maxlength="3" name="hqf'.$i.'" value="'.@intval($creneau_info['quota_freq']).'" />';
					}
				echo '</td>
				<td class="horparam">';
					if($creneau_nb>0) {
						echo '<input type="checkbox" class="inptxt" name="hr'.$i.'"';
						if(substr($creneau_info['hor_resa'],0,3)=="001") { echo 'checked'; }
						echo ' />';
					}
				echo '</td>
				<td class="horparam">';
					if($creneau_nb>0) {
						echo '<input type="number" class="inptxt horparam" min="0" max="999" maxlength="3" name="hqr'.$i.'" value="'.@intval($creneau_info['quota_resa']).'" />';
					}
				echo '</td>
				</tr>';
				if(isset($creneau_info['fin'])) {
					$_SESSION['finprec'] = substr($creneau_info['fin'],0,5);
				}
			}
			if(isset($_SESSION['finprec'])) {
				unset($_SESSION['finprec']);
			}
			
			echo '<tr><td colspan="8" style="border:0;"><p class="right"><input class="bouton boutparam" type="submit" value="'.VALID.'" name="horaires" /></p></td></tr>
			
		</table>
		
		</form></div>';

		echo '<h2 id="jourscren">'.PARAC_HOR16.'</h2>';
		if(isset($_POST['activesp'])) {
			mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur = '1' WHERE param_nom = 'freq_gestion_jourscren'");
		}
		if(isset($_POST['desactivesp'])) {
			mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur = '0' WHERE param_nom = 'freq_gestion_jourscren'");			
		}
		$edtesp_param = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'edt_espmulti'"));
		$verif_nivs = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_gestion_jourscren'");
		$verif_nivs_info = mysqli_fetch_assoc($verif_nivs);
		if($verif_nivs_info['valeur']==0) {
			echo '<form action="#jourscren" name="activesp" method="POST"><p><input type="checkbox" id="activesp" name="activesp" /><label for="activesp"> '.PARAC_HOR17.'</label></p><p class="paddvalid1"><input class="bouton boutparam" type="submit" value="'.VALID.'" name="activesp_valid" /></p></form>';
		}
		else if($verif_nivs_info['valeur']==1) {
			$nombre_cren = mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires"));
			$dayfrommon_part1 = array_slice(JOUR, 3, null, true); // Du lundi au jeudi
			$dayfrommon_part2 = array_slice(JOUR, 0, 3, true);   // Du vendredi au dimanche
			$dayfrommon = $dayfrommon_part1 + $dayfrommon_part2;
			if(isset($_POST['quotasj'])) {
				// Création de la boucle pour inscrire ou modifier les horaires :
				for($i=1;$i<=$nombre_cren;$i++) {					
					$num_creneau = $i;
					$ex = mysqli_fetch_assoc(mysqli_query($bdd, "SELECT * FROM ".$prefix."_horaires WHERE num_creneau = '".$num_creneau."'"));
			        $hf_exist = substr($ex['hor_freq'],0,3);
			        $hqf_exist = substr($ex['quota_freq'],0,3);
			        $hr_exist = substr($ex['hor_resa'],0,3);
			        $hqr_exist = substr($ex['quota_resa'],0,3);

			        foreach ($dayfrommon as $stkey => $stvalue){ 
						if(isset($_POST['hf_'.$stkey.'_'.$i])) { $hf_exist .= $stkey."001"; } 
						else { $hf_exist .= $stkey."000"; }
						if(isset($_POST['hr_'.$stkey.'_'.$i])) { $hr_exist .= $stkey."001"; } 
						else { $hr_exist .= $stkey."000"; }		
						$hqf_exist .= $stkey.str_pad($_POST['hqf_'.$stkey.'_'.$i.''],3,"0", STR_PAD_LEFT);
						$hqr_exist .= $stkey.str_pad($_POST['hqr_'.$stkey.'_'.$i.''],3,"0", STR_PAD_LEFT);
					}
					mysqli_query($bdd,"UPDATE ".$prefix."_horaires SET hor_freq='".$hf_exist."', hor_resa='".$hr_exist."', quota_freq='".$hqf_exist."', quota_resa='".$hqr_exist."' WHERE num_creneau = '".$num_creneau."'");
				}	
			}

			echo '<div style="overflow: auto;  white-space: nowrap;"><form method="POST" action="param.php?page=horaires" class="padd4">
			<table id="install" class="paramform">
			<tr style="text-align:center;"><th rowspan="2">'.CREN1.'</th>';
			foreach ($dayfrommon as $stkey => $stvalue){ 
				echo '<th colspan="4">'. $stvalue.'</th>'; 
			}
			echo '</tr>';
			echo '<tr>';
			for ($i = 0; $i < count(JOUR); $i++) {
			   echo '<th>'.PARAC_HOR13.'</th><th>'.PARAC_HOR15.'<br>'.PARAC_HOR13.'</th><th>'.PARAC_HOR14.'</th><th>'.PARAC_HOR15.'<br>'.PARAC_HOR14.'</th>';
			    
			}
			echo '</tr>';
				for($i=1;$i<=$nombre_cren;$i++) {
					$creneau = mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires WHERE num_creneau = $i");
					$creneau_nb = mysqli_num_rows($creneau);
					$creneau_info = mysqli_fetch_assoc($creneau);
					if($i<20) { 
						$suivant = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_horaires WHERE num_creneau = '".($i+1)."'"));
					}
					echo '<tr>
					<td style="text-align:right;"><b>'.@substr($creneau_info['hor_name'], 0, 1).@substr($creneau_info['hor_name'], 1, 1).'</b> '.@substr($creneau_info['debut'],0,5).' - '.@substr($creneau_info['fin'],0,5).'</td>';
					
					foreach ($dayfrommon as $cle => $jour) {
						echo '<td class="horparam">';
							
					if($creneau_nb>0) {
							echo '<input type="checkbox" class="inptxt" name="hf_'.$cle.'_'.$i.'"';
							if(substr($creneau_info['hor_freq'], strpos($creneau_info['hor_freq'], $cle) + strlen($cle), 3)=="001") { echo ' checked'; }
							echo ' />';
						}
						echo '</td>
						<td class="horparam">';
							if($creneau_nb>0) {
								echo '<input type="number" class="inptxt horparam" min="0" max="999" maxlength="3" name="hqf_'.$cle.'_'.$i.'" value="'.@intval(substr($creneau_info['quota_freq'], strpos($creneau_info['quota_freq'], $cle) + strlen($cle), 3)).'" />';
							}							
						echo '</td>
						<td class="horparam">';
							if($creneau_nb>0) {
								echo '<input type="checkbox" class="inptxt" name="hr_'.$cle.'_'.$i.'"';
								if(substr($creneau_info['hor_resa'], strpos($creneau_info['hor_resa'], $cle) + strlen($cle), 3)=="001") { echo ' checked'; }
								echo ' />';
							}
						echo '</td>
						<td class="horparam">';
							if($creneau_nb>0) {
								echo '<input type="number" class="inptxt horparam" min="0" max="999" maxlength="3" name="hqr_'.$cle.'_'.$i.'" value="'.@intval(substr($creneau_info['quota_resa'], strpos($creneau_info['quota_resa'], $cle) + strlen($cle), 3)).'" />';
							}
						echo '</td>';
					}
					echo '</tr>';
				}
			echo '<tr><td colspan="8" style="border:0;"><p class="right"><input class="bouton boutparam" type="submit" value="'.VALID.'" name="quotasj" /></p></td></tr>
				
			</table>
			
			</form>';			

			echo '</div>';		

			echo '<p><b>'.PARAC_ETAB40.'</b></p>';
			echo '<form action="#jourscren" name="desactivesp" method="POST"><p><input type="checkbox" id="desactivesp" name="desactivesp" /><label for="desactivesp"> '.PARAC_HOR18.'</label></p><span class="paddvalid1 right"><input class="bouton boutparam" type="submit" value="'.VALID.'" name="desactivesp_valid" /></span></p></form>';
			}	
		}
	}
else {
	include('include/noaccess.php');
	echo '<br><a href="../index.php">'.ACCUEIL.'</a></p>';
}
?>