<?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']);
			$encodage = mb_detect_encoding($content, ['UTF-8','ISO-8859-1','ISO-8859-15','Windows-1252'], true);
			if ($encodage === false || $encodage === 'ASCII') {
			    $encodage = 'Windows-1252';
			}
			if ($encodage !== 'UTF-8') {
			    $content = iconv($encodage, 'UTF-8//IGNORE', $content);
			}
			// 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 6ème
				echo '<p style="text-align:center;font-size:1.4em;padding-top:5px;">'.INSTALLNIVSAV.' '.$tabNiveau[$i].')...</p>'; flush(); ob_flush();
				// récup des savoirs du niveau
				include('proc/param_maj_savper.php');
				$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();
			$sqlsup = mysqli_query($bdd,"DELETE FROM ".$prefix."_savoirsmaj");
					
			// Paramétrage des savoirs dans ".$prefix."_parametres pour activer la grille perso (sans toucher aux autres si besoin)
			$verif_param_sav = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'savoirs'");
			$verif_param_sav_info = mysqli_fetch_array($verif_param_sav);
			if($verif_param_sav_info['valeur'] == "A1E0P0")
			{
				mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur='A1E0P1' WHERE param_nom='savoirs'");
			}
			else if($verif_param_sav_info['valeur'] == "A0E1P0")
			{
				mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur='A0E1P1' WHERE param_nom='savoirs'");
			}
			else if($verif_param_sav_info['valeur'] == "A1E1P0")
			{
				mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur='A1E1P1' 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(NOSCV);
		}
	}
}
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);
?>
