<?php
session_start();
require_once(dirname(__DIR__, 1) . '/config.php');
require_once(BASE_PATH . '/db/idl_connect.php');
// UPLOAD DU FICHIER CSV, vérification et insertion en BASE

echo '<meta charset="utf-8" />';
if(isset($_SESSION['user_droits'])) {
	if($_SESSION['user_droits'][5]!="2")
	{ echo '<p style="text-align:center;font-size:1.4em;padding-top:20px;">'.NOMODULE.'<br><a href="../index.php">'.ACCUEIL.'</a></p>'; }
	
	else {
	
		$mimes = array('text/csv',
		'text/plain',
		'application/csv',
		'text/comma-separated-values',
		'application/excel',
		'application/vnd.ms-excel',
		'application/vnd.msexcel',
		'text/anytext',
		'application/octet-stream',
		'application/txt',);

		if(in_array($_FILES['file']['type'],$mimes)){
			// Recherche de l'encodage
			$content = file_get_contents($_FILES['file']['tmp_name']);
			$enclist = array(
			    'UTF-8', 'ASCII',
			    'ISO-8859-1', 'ISO-8859-15',
			    'Windows-1252'
			);
			$encodage = mb_detect_encoding($content,$enclist,TRUE);
			if ($encodage === false) {
				echo '<p style="text-align:center;font-size:1.4em;padding-top:5px;">'.PBFILE1.'<br><a href="../../freq.php?page=retards">'.BACK.'</a></p>';
			}
			// Si l'encodage est gérable
			else {
				// Conversion en UTF-8 si nécessaire
				if ($encodage !== 'UTF-8') {
				    $content = mb_convert_encoding($content, 'UTF-8', $encodage);
				}

				// Suppression d'une éventuelle BOM UTF-8
				$content = preg_replace('/^\xEF\xBB\xBF/', '', $content);

				// Création d’un fichier temporaire avec le contenu converti
				$tmp_utf8_file = tempnam(sys_get_temp_dir(), 'utf8_');
				file_put_contents($tmp_utf8_file, $content);
				// Intégration dans la table ".$prefix."_savoirsmaj
				echo '<p style="text-align:center;font-size:1.4em;padding-top:5px;">'.INSTALLSAVOIRS.'</p>'; flush(); ob_flush();
				if (($handle = fopen($tmp_utf8_file, "r")) !== false) {
					while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
						$att0 = mysqli_real_escape_string($bdd,$data[0]);
						if($encoding==1) {
							$att1 = mb_convert_encoding(mysqli_real_escape_string($bdd,$data[1]),"UTF-8",$encodage);
						}
						else {
							$att1 = mysqli_real_escape_string($bdd,$data[1]);
						}
						$att2 = mysqli_real_escape_string($bdd,$data[2]);
						if(isset($data[3])) {
							$att3 = mysqli_real_escape_string($bdd,$data[3]);
							$att3 = preg_replace('/[^a-zA-Z0-9_-]/', '', $att3);
						}
						else { $att3 = "PER1"; }
						if(isset($data[4])) {
							if($encoding==1) {
								$att4 = mb_convert_encoding(mysqli_real_escape_string($bdd,$data[4]),"UTF-8",$encodage);
							}
							else {
								$att4 = mysqli_real_escape_string($bdd,$data[4]);
							}
						}
						else { $att4 = ""; }
						if(isset($data[5])) {
							$att5 = mysqli_real_escape_string($bdd,$data[5]);
						}
						else { $att5 = "1"; }
						
						mysqli_query($bdd,"INSERT INTO ".$prefix."_savoirsmaj (s_id, nom_savoir, niveau, champs_id, notions, base) VALUES ('" . $att0 . "', '" . $att1 . "', '" . $att2 . "', '" . $att3 . "', '" . $att4 . "', '" . $att5 . "')");
					}
					fclose($handle);
					unlink($tmp_utf8_file);
				}
				
				$tabDebniveau = array('6', '5', '4', '3', '2', '1', 't');
				$tabNiveau = array('6ème', '5ème', '4ème', '3ème', '2nde', '1re', 'Tale');
				$i=0;
				foreach($tabDebniveau as $divdeb) {
					// Intégration dans la table ".$prefix."_savoirs* des savoirs pour le niveau
					echo '<p style="text-align:center;font-size:1.4em;padding-top:5px;">'.INSTALLNIVSAV.' '.$tabNiveau[$i].')...</p>'; flush(); ob_flush();
					$sql = mysqli_query($bdd,"SELECT * FROM ".$prefix."_savoirsmaj WHERE niveau = '".$divdeb."e'");
					while($sql_info=mysqli_fetch_assoc($sql)) {
						$att0 = mysqli_real_escape_string($bdd,$sql_info['s_id']);
						$att1 = mysqli_real_escape_string($bdd,$sql_info['nom_savoir']);
						$att2 = mysqli_real_escape_string($bdd,$sql_info['niveau']);
						$att3 = mysqli_real_escape_string($bdd,$sql_info['champs_id']);
						$att4 = mysqli_real_escape_string($bdd,$sql_info['notions']);
						$att5 = mysqli_real_escape_string($bdd,$sql_info['base']);
						
						mysqli_query($bdd,"INSERT INTO ".$prefix."_savoirs".$divdeb." (s".$divdeb."_id, nom_savoir, niveau, champs_id, notions, base) VALUES ('" . $att0 . "', '" . $att1 . "', '" . $att2 . "', '" . $att3 . "', '" . $att4 . "', '" . $att5 . "')");
					}
					$i++;
				}
						
				// Gestion des champs dans ".$prefix."_savchamps
				$champs = mysqli_query($bdd,"SELECT champs_id FROM ".$prefix."_savoirsmaj GROUP BY champs_id ORDER BY champs_id ASC");
				$champs_nb = mysqli_num_rows($champs);
				if($champs_nb == 0) {
					mysqli_query($bdd,"INSERT INTO ".$prefix."_savchamps (champs_id, champs_nom, bgcolor) VALUES ('PER1', '', '#E3CEF6')");
				}
				else {
					while($champs_info = mysqli_fetch_assoc($champs)) {
						$cid = $champs_info['champs_id'];
						mysqli_query($bdd,"INSERT INTO ".$prefix."_savchamps (champs_id, champs_nom, bgcolor) VALUES ('$cid', '', '#E3CEF6')");
					}
				}
						
				// Suppression des lignes de la table temporaire ".$prefix."_savoirsmaj
				echo '<p style="text-align:center;font-size:1.4em;padding-top:5px;">'.TEMPSUPPR.'</p>'; flush(); ob_flush();
				mysqli_query($bdd,"DELETE FROM ".$prefix."_savoirsmaj");
						
				// Paramétrage des savoirs dans ".$prefix."_parametres pour activer la seule grille perso
				mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur='A0E0P1' WHERE param_nom='savoirs'");
						
				// Fin de l'installation
				echo '<p style="text-align:center;font-size:1.4em;padding-top:5px;">'.INSTALLFINI.' <a href="../param.php?page=savoirs">'.BACKPARAM.'</a></p>';
			}
		}
		else {
			die(NOCSV);
		}
	}
}
else {
	echo '<p style="text-align:center;font-size:1.4em;padding-top:20px;">'.NOACC2.'<br><a href="../param.php?page=savoirs">'.BACKPARAM.'</a></p>';
}
mysqli_close($bdd);
?>
