<?php
echo '<meta charset="utf-8" />';
if(isset($_SESSION['user_droits'])) {
	if($_SESSION['user_droits'][2]!=2)
	{
		echo '<p class="noaccess">'.NOMODULE.'<br><a href="./index.php">'.ACCUEIL.'</a></p>';
	}
	else {
		?><style type="text/css">
		#mdt3 { background-color: #fff; }
		#mdt3 td { border: 3px #E77015 solid; }
		#mdt2 td { border: 0; }
		</style><?php
		echo '<div class="edt_padding"><h1>'.EDTC_AGE1.'</h1>';
		
		echo '</div><h2>'.EDTC_AGE2.'</h2>';
		//Options : afaire (mis à faire sur l'EDT du user);fait (archivé);edtday(message sur l'edt : remplace l'ancien système !);edtaff (message sous l'EDT pdf);edtpageresa (info sur la page de réservation des élèves);modifiable (peut être modifié par tout utilisateur concerné)
		
		// Voir exemple dans /db/proc/edt_table.php pour la gestion des users, espaces et options
		
		//traitement
		function removeEventFromString($dataString, $eventIdToRemove) {
		    $parts = explode(";", $dataString);

		    // Vérifie qu'il y a bien une 4e partie avec les événements
		    if (count($parts) < 4) {
		        return $dataString;
		    }

		    $events = explode("-", $parts[3]);
		    $filtered = array_filter($events, function($e) use ($eventIdToRemove) {
		        return $e != $eventIdToRemove;
		    });

		    if (count($filtered) > 0) {
		        $parts[3] = implode("-", $filtered);
		    } else {
		        // Supprime complètement la 4e partie si plus d'événements
		        array_pop($parts);
		    }

		    return implode(";", $parts);
		}
		if(isset($_POST['validevent'])) {
			$note = isset($_POST['agenda_id']) ? $_POST['agenda_id'] : 0;
			$creator = $_SESSION['user_id'];
			// Prépare $users
			$users = '';
			$usrcs = mysqli_query($bdd,"SELECT id, login, nom, prenom FROM ".$prefix."_user ORDER BY login ASC");
			foreach($usrcs as $usrc) {
				if(isset($_POST[$note.'usr'.$usrc['id']])) { $users .= $usrc['id'].';'; }
			}
			// Prépare $espaces
			$espaces = '';
			if($espopt['valeur']=='1') {
				if(isset($_POST[$note.'esp0'])) { $espaces .= '0;'; }
				$espcs = mysqli_query($bdd,"SELECT espace_id, espace_nom FROM ".$prefix."_espaces ORDER BY espace_id ASC");
				foreach($espcs as $espc) {
					if(isset($_POST[$note.'esp'.$espc['espace_id']])) { $espaces .= $espc['espace_id'].';'; }
				}
			}
			else {
				$espaces = '0';
			}
			$titre = mysqli_real_escape_string($bdd,$_POST['titre'.$note]);
			$texte = mysqli_real_escape_string($bdd,$_POST['texte'.$note]);
			$notes = mysqli_real_escape_string($bdd,$_POST['notes'.$note]);
			// Prépare $date1
			$date1 = $_POST['date1'.$note];
			// Prépare $date2
			$date2 = $_POST['date2'.$note];
			// Prépare $options
			$afaire = isset($_POST['afaire'.$note]) ? '1' : '0';
		    $fait = isset($_POST['fait'.$note]) ? '1' : '0';
		    $edtday = isset($_POST['edtday'.$note]) ? '1' : '0';
		    $edtaff = isset($_POST['edtaff'.$note]) ? '1' : '0';
		    $edtpageresa = isset($_POST['edtpageresa'.$note]) ? '1' : '0';
		    $modifiable = isset($_POST['modifiable'.$note]) ? '1' : '0';
			$options = $afaire.';'.$fait.';'.$edtday.';'.$edtaff.';'.$edtpageresa.';'.$modifiable;
			// Insertion
			if ($note == 0) {
				mysqli_query($bdd,"INSERT INTO ".$prefix."_agenda (agenda_id, creator, users, espaces, titre, texte, notes, date1, date2, options) VALUES ('', '$creator', '$users', '$espaces', '$titre','$texte','$notes','$date1', '$date2', '$options')");
			}
			else {
				mysqli_query($bdd, "UPDATE ".$prefix."_agenda 
            	SET users='$users', espaces='$espaces', titre='$titre', texte='$texte', notes='$notes', date1='$date1', date2='$date2', options='$options'
            	WHERE agenda_id = '$note' LIMIT 1");
			}
			$edtmsgopt = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'edt_msgopt'"));
			$edtmsgopt_infos = explode(";",$edtmsgopt['valeur']);
			@$edtmsgopt_agenda = explode("-",@$edtmsgopt_infos[3]);
			if($edtaff=='1') {
				if ($note == 0) {
					$notelast = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT agenda_id FROM ".$prefix."_agenda ORDER BY agenda_id DESC LIMIT 1"));
					$note = $notelast['agenda_id'];
				}	
				if(!in_array($note,$edtmsgopt_agenda)) { 
					mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur = '".$edtmsgopt['valeur']."-".$note."' WHERE param_nom = 'edt_msgopt'");
				}
			}
			if($edtaff=='0') {
				// 1. Récupérer la valeur actuelle
			    $res = mysqli_query($bdd, "SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'edt_msgopt'");
			    $row = mysqli_fetch_assoc($res);
			    $currentValue = $row['valeur'];
			    // 2. Vérifie si $note est présent dans la dernière section
			    $parts = explode(";", $currentValue);
			    if (count($parts) >= 4 && in_array((string)$note, explode("-", $parts[3]))) {
			        // 3. Nettoyer la valeur
			        $newValue = removeEventFromString($currentValue, $note);
			        // 4. Mettre à jour la base seulement si la valeur a changé
			        if ($newValue !== $currentValue) {
			            mysqli_query($bdd, "UPDATE ".$prefix."_parametres SET valeur = '".mysqli_real_escape_string($bdd, $newValue)."' WHERE param_nom = 'edt_msgopt'");
			        }
			    }
			}
			if($afaire=='1') {
				?><script language="Javascript">
				<!--
				document.location.replace("edt.php?page=agenda");
				// -->
				</script>
				<?php
			}
		}
		if(isset($_POST['purgval'])) {
			$date_old = date('Y-m-d', strtotime('-5 year'));
			$msgs_old = mysqli_query($bdd,"SELECT * FROM ".$prefix."_agenda WHERE titre != '' AND date1 < '".$date_old."'");
			foreach($msgs_old as $msgs_old_supr) {
				mysqli_query($bdd,"DELETE FROM ".$prefix."_agenda WHERE agenda_id = '".$msgs_old_supr['agenda_id']."'");
			}
		}
		if(isset($_POST['supprevent'])) {
			$note = isset($_POST['agenda_id']) ? $_POST['agenda_id'] : 0;
			mysqli_query($bdd,"DELETE FROM ".$prefix."_agenda WHERE agenda_id = '".$note."'");
			// 1. Récupérer la valeur actuelle
		    $res = mysqli_query($bdd, "SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'edt_msgopt'");
		    $row = mysqli_fetch_assoc($res);
		    $currentValue = $row['valeur'];
		    // 2. Vérifie si $note est présent dans la dernière section
		    $parts = explode(";", $currentValue);
		    if (count($parts) >= 4 && in_array((string)$note, explode("-", $parts[3]))) {
		        // 3. Nettoyer la valeur
		        $newValue = removeEventFromString($currentValue, $note);
		        // 4. Mettre à jour la base seulement si la valeur a changé
		        if ($newValue !== $currentValue) {
		            mysqli_query($bdd, "UPDATE ".$prefix."_parametres SET valeur = '".mysqli_real_escape_string($bdd, $newValue)."' WHERE param_nom = 'edt_msgopt'");
		        }
		    }
		}
		
		//formulaire
		$note = 0;
		include('db/proc/edt_agenda_form.php');
		
		$blocnotes = mysqli_query($bdd,"SELECT * FROM ".$prefix."_agenda ORDER BY date1 DESC");
		echo '<br><h2>'.EDTC_AGE3.'</h2>';
		if(mysqli_num_rows($blocnotes)=='0') {
			echo '<p>'.NONE.'</p>';
		}
		else {
			echo '<p>'.mysqli_num_rows($blocnotes).' '.EDTC_AGE4.'</p>';
			$previousMonth = null;
			foreach($blocnotes as $blocnote) {
				$date = new DateTime($blocnote['date1']);
			    $currentMonth = $date->format('Y-m'); // Pour détecter les changements
			    $monthNameEn = $date->format('F');    // Mois en anglais
			    $year = $date->format('Y');
				if ($currentMonth !== $previousMonth) {
			        if ($previousMonth !== null) {
			            echo '<div style="margin-top:20px;"></div>';
			        }

			        // Traduction du mois
			        $monthNameFr = $months_lang[$monthNameEn] ?? $monthNameEn;
			        echo '<h4 style="margin:10px 0; color:#444;">' . $monthNameFr . ' ' . $year . '</h4>';

			        $previousMonth = $currentMonth;
			    }
			    echo '<a style="color:black;text-decoration:none;" onmouseover="this.style.textDecoration=\'underline\';" onmouseout="this.style.textDecoration=\'none\';" onmousedown="toggleDiv(\'note'.$blocnote['agenda_id'].'\');"><i class="fas fa-bullseye"></i> ';
				if($blocnote['date2']!='0000-00-00') {
					echo FROM21.' '.$blocnote['date1'].' '.TO2.' '.$blocnote['date2'].DOTS.' ';
				}
				else {
					echo LE.' '.$blocnote['date1'].DOTS.' ';
				}
				echo $blocnote['titre'];
				echo '</a><br>';
				echo '<div id="note'.$blocnote['agenda_id'].'" style="display:none;">';
				$note = intval($blocnote['agenda_id']);
				$opts = explode(";",$blocnote['options']);
				$uses = explode(";",$blocnote['users']);
				$esps = explode(";",$blocnote['espaces']);
				if($blocnote['creator']==$_SESSION['user_id']||($opts[5]=='1'&&in_array($_SESSION['user_id'],$uses))) {
					// Modifications possibles
					include('db/proc/edt_agenda_form.php');
				}
				else {
					// Consultation seulement
					echo '<table class="agenda_form">
					<tr><td>'.TITLE.DOTS.'</td><td><b>'.$blocnote['titre'].'</b></td></tr>
					<tr><td>'.FREQC_JOUR4.'</td><td>'.$blocnote['date1'].'</td></tr>';
					if($blocnote['date2']!='0000-00-00') {
						echo '<tr><td>'.PARAM_CAL2.'</td><td>'.$blocnote['date2'].'</td></tr>';
					}
					echo '<tr><td colspan="2">'.CREATOR.DOTS.' ';
					$creat = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT id, login, nom, prenom FROM ".$prefix."_user WHERE id = '".$blocnote['creator']."' LIMIT 1"));
					echo $creat['login']; 
					echo '<tr><td colspan="2">'.PARANAV2.DOTS;
					$usrcs = mysqli_query($bdd,"SELECT id, login, nom, prenom FROM ".$prefix."_user ORDER BY login ASC");
					foreach($usrcs as $usrc) {
						if(in_array($usrc['id'],$uses)) { echo ' '.$usrc['login']; }
					}
					echo '</td></tr>';
					if($espopt['valeur']=='1') {
						echo '<tr><td colspan="2">'.PARANAV8.DOTS;
						$espcs = mysqli_query($bdd,"SELECT espace_id, espace_nom FROM ".$prefix."_espaces ORDER BY espace_id ASC");
						$espfirst = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_parametres WHERE param_nom = 'espaces_first'"));
						if(in_array('0',$esps)) { echo ' '.$espfirst['valeur']; }
						foreach($espcs as $espc) {
							if(in_array($espc['espace_id'],$esps)) { echo ' '.$espc['espace_nom']; }		
						}
						echo '</td></tr>';
					}
					if($blocnote['texte']!='') {
						echo '<tr><td>'.TEXT.DOTS.'</td><td>'.$blocnote['texte'].'</td></tr>';
					}
					if($blocnote['notes']!='') {
						echo '<tr><td>'.NOTES.DOTS.'</td><td>'.$blocnote['notes'].'</td></tr>';
					}
					echo '<tr><td>'.OPTIONS.DOTS.'</td>
					<td>';
					if($opts[0]=='1') { echo EDTC_AGE6; }
					else { echo '<strike>'.EDTC_AGE6.'</strike>'; }
					echo '<br>';
					if($opts[1]=='1') { echo EDTC_AGE7; }
					else { echo '<strike>'.EDTC_AGE7.'</strike>'; }
					echo '<br>';
					if($opts[2]=='1') { echo EDTC_AGE8; }
					else { echo '<strike>'.EDTC_AGE8.'</strike>'; }
					echo '<br>';
					if($opts[3]=='1') { echo EDTC_AGE9; }
					else { echo '<strike>'.EDTC_AGE9.'</strike>'; }
					echo '<br>';
					if($opts[4]=='1') { echo EDTC_AGE10; }
					else { echo '<strike>'.EDTC_AGE10.'</strike>'; }
					echo '<br>';
					if($opts[5]=='1') { echo EDTC_AGE11; }
					else { echo '<strike>'.EDTC_AGE11.'</strike>'; }
					echo '</td></tr>';

					echo '</table><br>';
				}
				echo '</div>';
			}
			// Gestion des anciens messages
			$date_old = date('Y-m-d', strtotime('-5 year'));
			$msgs_old = mysqli_query($bdd,"SELECT * FROM ".$prefix."_agenda WHERE titre != '' AND date1 < '".$date_old."'");
			if(mysqli_num_rows($msgs_old)>0) {
				echo '<br><form action="#msg_id" method="POST" name="msgpurge"><input class="bouton boutparam" type="submit" name="purgval" value="'.EDTC_AGE5.'" /></form>';
			}
		}
		?>
		<script>			
			function decodeHtmlEntity(encodedStr) {
			    var txt = document.createElement('textarea');
			    txt.innerHTML = encodedStr;
			    return txt.value;
			}
			const idlog = "<?php echo $prefix; ?>";
			const idlog_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
			  const xhr = new XMLHttpRequest();
			  xhr.withCredentials = false;
			  xhr.open('POST', 'include/tinymce/upload.php');

			  xhr.upload.onprogress = (e) => {
			    progress(e.loaded / e.total * 100);
			  };

			  const formData = new FormData();
		        formData.append('file', blobInfo.blob(), blobInfo.filename());
		        formData.append('idlog', idlog);

			  xhr.onload = () => {
			    if (xhr.status === 403) {
			      reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
			      return;
			    }

			    if (xhr.status < 200 || xhr.status >= 300) {
			      reject('HTTP Error: ' + xhr.status);
			      return;
			    }

			    const json = JSON.parse(xhr.responseText);

			    if (!json || typeof json.location != 'string') {
			      reject('Invalid JSON: ' + xhr.responseText);
			      return;
			    }

			    resolve(json.location);
			  };

			  xhr.onerror = () => {
			    reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
			  };

			  xhr.send(formData);
			});
			document.addEventListener('DOMContentLoaded', function() {
			    document.querySelectorAll('textarea.tinymce').forEach(textarea => {
			        tinymce.init({
			            selector: '.tinymce',
			            relative_urls: false,
			            remove_script_host: false,
			            height: 300,
			            width: 600,
			            menubar: true,
			            plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table code help wordcount',
			            toolbar: 'undo redo | styleselect | bold italic underline | alignleft aligncenter alignright alignjustify | link image media | bullist numlist outdent indent | code fullscreen',
			            content_style: "body { font-family: Arial, sans-serif; font-size: 14px; }",
			            language: '<?php echo TINYMCE;?>',
			            license_key: 'gpl',
			            promotion: false,
					a11y_advanced_options: false,
			            images_upload_handler: idlog_image_upload_handler,
					setup: function(editor) {
		                		editor.on('init', function() {
		                   		 document.querySelectorAll('.tox-statusbar__help-text').forEach(el => el.remove());
		                	});
		            		}
			        });
			    });
			});
		</script>
		<?php
	}
}
	
else {
	include('include/noaccess.php');
	echo '<br><a href="./index.php">'.ACCUEIL.'</a></p>';
}
?>
