<?php
$seq_id = $_GET['seq_id'];
echo EDIT_MODIF1;
// Vérification de la présence de grilles : EMI et PERSO
$verif_emi = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirs3 WHERE s3_id LIKE 'EMI%'");
$nb_sav_emi = mysqli_num_rows($verif_emi);
$verif_per = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirs6 WHERE s6_id LIKE 'PER%'");
$nb_sav_per = mysqli_num_rows($verif_per);

// Affichage du formulaire
echo EDIT_MODIF2;
if($nb_sav_emi>0) {
	echo EDIT_MODIF3;
}
if($nb_sav_per>0) {
	echo EDIT_MODIF4;
}
echo '</p>';

echo '<script language=javascript>
		function OuvrirPopup(page,nom,option) {
		  window.open(page,nom,option);
		}
		</script>';
if(isset($_POST['docsconfirm'])) {
	// Gestion des fichiers (suppression) :
	$seqdocs = mysqli_query($bdd,"SELECT * FROM ".$prefix."_seqdocs WHERE seq_id = '".$seq_id."' ORDER BY docname ASC");
	$seqdocs_nb = mysqli_num_rows($seqdocs);
	if($seqdocs_nb>0) {
		$h=1;
		while($liste_docs = mysqli_fetch_assoc($seqdocs)) {
			if($_POST[$h]=="") {
				//sélection et suppression des images
				$rep_img = 'seqfichiers/'.$prefix;
				$rep_img_open = opendir($rep_img);
				$chemin = $rep_img."/".$liste_docs['docurl'];
				unlink($chemin);
				mysqli_query($bdd,"DELETE FROM ".$prefix."_seqdocs WHERE doc_id = '".$liste_docs['doc_id']."'");
				closedir($rep_img_open);
			}
			$h++;
		}
	}
	// Gestion des fichiers (ajout) :
	include('db/proc/edit_newfiles.php');
}
$seq = mysqli_query($bdd,"SELECT * FROM ".$prefix."_sequences WHERE seq_id = '$seq_id'");
$seq_nb = mysqli_num_rows($seq);
if($seq_nb==0) {
	echo '<script language="Javascript">
	<!--
	document.location.replace("edit.php?page=consult");
	// -->
	</script>';
}
else {
	echo '<div class="fiche_consult">';
	echo '<script type="text/javascript">
			function selection(pDiv){
				var couleur = "red 2px solid";
				var couleurw = "white 2px solid";
				var color = "red";
				var colorw = "white";			    
	            document.getElementById(pDiv).style.border = couleur;
				document.getElementById(pDiv).style.color = color;
				setTimeout(() => {  
					document.getElementById(pDiv).style.color = colorw; 
					document.getElementById(pDiv).style.border = couleurw;
					}, 2000);
			}
			function validcolor(pDiv){
				var couleur = "green 2px solid";
				var couleurw = "white 2px solid";
				var color = "green";
				var colorw = "white";			    
	            document.getElementById(pDiv).style.border = couleur;
				document.getElementById(pDiv).style.color = color;
				setTimeout(() => {  
					document.getElementById(pDiv).style.color = colorw; 
					document.getElementById(pDiv).style.border = couleurw;
					}, 2000);
			}
			function checkchamps(divCheck){
				document.getElementById(divCheck).style.display = \'block\';
				document.getElementById("hidedocv").style.display = \'none\';
			}
		</script>';
	
	
	$seq_info = mysqli_fetch_array($seq);
	$_SESSION['seq_nom']=$seq_info['seq_nom'];
	$_SESSION['seq_niv']=$seq_info['niveau'];
	$txt_type = array('seq_nom', 'contexte', 'niveau', 'progression', 'date_crea', 'date_maj', 'intervs', 'enjeux', 'requis', 'notions', 'SAVOIRS', 'autres', 'production', 'calendrier', 'ressources', 'synopsis', 'outils1', 'outils2', 'eval', 'reinves', 'bilan', 'conseils', 'documents', 'auteur', 'licence', 'url', 'seq_complete');
	echo "<script language='javascript'>
		window.onmousedown = function (e) {
	    var el = e.target;
	    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
	        e.preventDefault();

	        if (el.hasAttribute('selected')) el.removeAttribute('selected');
	        else el.setAttribute('selected', '');

	        var select = el.parentNode.cloneNode(true);
	        el.parentNode.parentNode.replaceChild(select, el.parentNode);
	    }
	}
	</script>";
	for($i=0;$i<count($txt_type);$i++) {
		if($txt_type[$i]=='seq_nom') {
			echo '<br><hr class="hr1n"> <h3>'.IDENT4.'</h3>';
		}
		else if($txt_type[$i]=='enjeux') {
			echo '<br> <br><hr class="hr1n"> <h3>'.EDIT_TIT1.'</h3>';
		}
		else if($txt_type[$i]=='production') {
			echo '<br> <br><hr class="hr1n"> <h3>'.EDIT_TIT2.'</h3>';
		}
		else if($txt_type[$i]=='eval') {
			echo '<br> <br><hr class="hr1n"> <h3>'.EDIT_TIT3.'</h3>';
		}
		else if($txt_type[$i]=='documents') {
			echo '<a id="docs"></a>';
			echo '<br> <br><hr class="hr1n"> '.EDIT_DOCS;
			for($error=1;$error<6;$error++) {
				if(isset($_SESSION['alerte_taille'.$error])) {
					echo '<p class="signal">'.$_SESSION['alerte_taille'.$error].'</p>';
				}
				if(isset($_SESSION['alerte_ext'.$error])) {
					echo '<p class="signal">'.$_SESSION['alerte_ext'.$error].'</p>';
				}
			}
		}
		else if($txt_type[$i]=='auteur') {
			echo '<br> <br><hr class="hr1n"> <h3>'.EDIT_TIT4.'</h3>';
		}
		echo '<div class="seq_item" id="'.$txt_type[$i].'">';
			if($txt_type[$i]!='SAVOIRS'&&$txt_type[$i]!='documents') {
				echo '<br><hr class="hr2n"> <h4>'.$txt_typenm[$i].' :</h4>';
			}
			include('edit_modif_case.php');
		echo '</div>';
	}
	echo '</div>';
	echo '<div class="fiche_boutons">';
	$seq_id = $_GET['seq_id'];
	echo '<input class="bouton boutseq" type="button" onclick="window.location.href=\'edit.php?page=consult&seq_id='.$seq_id.'\';" value="'.EDIT_BUTTON7.'" />';
	echo '<form method="POST" action="edit.php?page=consult&seq_id='.$seq_id.'">
	<input class="bouton boutseq" type="submit" value="'.EDIT_BUTTON6.'" name="suppr" /></td></tr>
	</form>';
	echo '</div>';?>
	<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: 400,
	            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
}
?>