<?php session_start(); ?>
<!doctype html>
<?php 
	$filename = 'db/idl_connect_data.php';
	if (file_exists($filename)) {
		include('db/idl_connect_data.php');
	}
	else {
		include('db/_idl_connect_data.php');
	}
	@include('db/idl_multi.php');
	@include('config.php');
	$bdd = @mysqli_connect($server, $user, $pwd);
	$query = "SHOW DATABASES LIKE '$base'";
	$result = mysqli_query($bdd, $query);
	$langDir = __DIR__ . '/include/lang/';
    $langFiles = scandir($langDir);
    $languages = [];
    foreach ($langFiles as $file) {
	    if (preg_match('/^([a-z]{2})\.php$/', $file, $matches)) {
	        $code = $matches[1];
	        $filePath = $langDir . $file;
	        $content = file_get_contents($filePath);

	        // Extraire le nom de la langue avec une expression régulière
	        if (preg_match('/define\(\s*\'LANG_VALID\'\s*,\s*true\s*\)/', $content) && preg_match('/\$lang_name\s*=\s*"([^"]+)"/', $content, $nameMatches)) {
	            $languages[$code] = $nameMatches[1];
	        }
	    }
	}
	$defaultLang = 'fr';
	// Vérifier si une langue a été passée dans l'URL
	if (isset($_GET['lang']) && preg_match('/^[a-z]{2}$/', $_GET['lang']) && array_key_exists($_GET['lang'], $languages)) {
	    $selectedLang = $_GET['lang'];
	    $_SESSION['lang'] = $selectedLang; // Mettre à jour la session
	} elseif (isset($_SESSION['lang']) && preg_match('/^[a-z]{2}$/', $_SESSION['lang']) && array_key_exists($_SESSION['lang'], $languages)) {
	    $selectedLang = $_SESSION['lang'];
	} else {
	    $selectedLang = $defaultLang;
	}
	$_SESSION['lang'] = $selectedLang;
	if(@$multi=='ON') {
		if(@$multipref!="1") {
			if(isset($_COOKIE['LANGM'])) {
				$_SESSION['lang'] = $_COOKIE['LANGM'];
			}
		}
	}
	if(!$bdd||mysqli_num_rows($result) == 0){
		if(!isset($_SESSION['lang'])) {
			$_SESSION['lang'] = 'fr';
			if(@$langue['valeur'] != "") {
				$_SESSION['lang'] = @$langue['valeur'];
			}
		}
		require_once('include/lang/'.$_SESSION['lang'].'.php');
	}
	else {
		require_once('db/idl_connect.php');
	}
?>

<html lang="<?php echo @htmlspecialchars($_SESSION['lang']); ?>">
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script>
        function changeLanguage(lang) {
            window.location.href = '?lang=' + lang;
        }
    </script>
	<title><?php echo ACCUEIL; ?> - InfodocLog</title>
	<link rel="stylesheet" type="text/css" href="css/idl_solo.css" />
	<link rel="stylesheet" type="text/css" href="css/idl_solo_resp.css" />
	<link rel="stylesheet" type="text/css" href="css/idl_print.css" media="print" />
	<link rel="stylesheet" href="include/fontawesome/css/all.css">
	<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
	<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
	<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
	<script language="javascript">
		function toggleDiv(divid){
			var element = document.getElementById(divid);
		    if (element.style.display === 'none') {
		        element.style.display = 'block';
		    } else {
		        element.style.display = 'none';
		    }
		}
	</script>
</head>

<body>
	
	<?php $page_header = 'index'; ?>
	<?php include('include/header.php'); ?>
	
	<section id="accueil">
		<?php 
		if(!$bdd){
			if(phpversion()<7.4&&phpversion()>=8.3) {
				echo '<p class="signal" style="text-align:center;">'.PHPVERS.'</p>';
			}
			if(@$multi=="OFF"&&$user!="root") {
				echo SQLERROR;
			}
			else {
				echo '<div class="center"><h1><a href="install.php">'.INSTALL.'</a></h1></div>';
			}			
		}
		else if(mysqli_num_rows($result) == 0){
			if(phpversion()<7.4&&phpversion()>=8.3) {
				echo '<p class="signal" style="text-align:center;">'.PHPVERS.'</p>';
			}
			if(@$multi=="OFF"&&$user!="root") {
				echo SQLERROR;
			}
			else {
				echo '<div class="center"><h1><a href="install.php">'.INSTALL.'</a></h1></div>';
			}
		}
		else {
			require_once('db/idl_connect.php');
			
			if(!isset($prefix)) { $prefix = 'idlog'; }
			if(isset($_SESSION['user_droits'])) {
				// Gestion des mises à jour de la base de données
				if($_SESSION['user_droits'][4]=="2")
				{
					$url = "http://iddocs.fr/infodoclog/log/version.txt";
					$vers_offbdd = "";
					$vers_offurl = fopen($url,"r");
					$vers_offbdd = @substr($vers_offurl, 5, strpos($vers_offurl,"/"));
					if($vers_offbdd!="") {
						$versinb = mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'version_bdd'");
						$versinb_info = mysqli_fetch_assoc($versinb);
						if($versinb_info['valeur']!=$vers_offbdd) {
							echo '<script language="Javascript">
							<!--
							document.location.replace("param.php?page=majlog");
							// -->
							</script>';
						}
					}
				}
				$redirect = array('','eval','edit','edt','freq','param','database');
				if($_SESSION['accueil']> 0&&$_SESSION['accueil']< 7) {
					echo '<script language="Javascript">
					<!--
					document.location.replace("'.$redirect[$_SESSION['accueil']].'.php");
					// -->
					</script>';
				}				
				else {
					$check_droits = $user_info['droits'];
					$check_eval = substr($check_droits, 0, 1);
					$check_edit = substr($check_droits, 1, 1);
					$check_edt = substr($check_droits, 2, 1);
					$check_freq = substr($check_droits, 3, 1);
					$check_param = substr($check_droits, 4, 1);
					$check_database = substr($check_droits, 5, 1);
					$redircheck = array('freq','edt','edit','eval','database','param');
					$checkedredir=0;
					foreach($redircheck as $suffix) {
						if(${'check_'.$suffix}==4||${'check_'.$suffix}==2) {
							echo '<script language="Javascript">
							<!--
							document.location.replace("'.$suffix.'.php");
							// -->
							</script>';
							$checkedredir=1;
						}
					}					
					if($checkedredir==0) {
						echo NOACCESS;
					}
				}
			}
			else {
				if(isset($_POST['mailp'])&&isset($_POST['loginp'])) {
					if(@$multi=="ON") {
						if(@$multipref==1) {
							$_SESSION['etabchoix'] = substr($_POST['loginp'],0,5);
						}
						else {
							$_SESSION['etabchoix'] = $_POST['etabchoix'];
						}
						include('db/idl_multi.php');
						require_once('db/idl_connect.php');
					}
					else {
						require_once('db/idl_connect.php');
					}
					$mailp = mysqli_real_escape_string($bdd,$_POST['mailp']);
					if(@$multi=="ON"&&@$multipref==1) {
						$loginp = mysqli_real_escape_string($bdd,substr($_POST['loginp'],5));
					}
					else {
						$loginp = mysqli_real_escape_string($bdd,$_POST['loginp']);
					}					
					if(mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_user WHERE login = '".$loginp."' AND mail = '".$mailp."'"))>0) {
						function genMDP($longueur = 12) {
						    $cars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
						    $chaine = '';
						    for ($i = 0; $i < $longueur; $i++) {
						        $chaine .= $cars[rand(0, strlen($cars) - 1)];
						    }
						    return $chaine;
						}
						do {
						    $sel = bin2hex(random_bytes(16));
						} while ($sel === '0');
						$mdp = genMDP(12);
						$mdp_avec_sel = $mdp.$sel;
						$hashed_password = hash('sha256', $mdp_avec_sel);
						$ident = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_user WHERE login = '".$loginp."' AND mail = '".$mailp."'"));
						$login = $loginp;
						mysqli_query($bdd,"UPDATE ".$prefix."_user SET mdp = '$hashed_password', sel = '$sel' WHERE id = '".$ident['id']."'");
						$mail = $mailp;
						include('db/proc/mailing/mail_mdp.php');
						echo '<div class="center"><p><b>'.NEWPASS.'</b></p></div>';
					}
					else {
						echo '<div class="center"><p><b>'.UNLOG.'</b></p></div>';
					}
				}

				echo '<form method="post" name="enter" action="db/droits.php" class="padd2"><div class="center">';

				if(@$multi=='ON') {
					if(@$multipref!="1") {
						echo '<br><div class="box"><select name="etabchoix" id="etabchoix" onchange="etab_resopt()">';
						foreach($multichoix as $choix) {
							echo '<option';
							if($choix==@$_COOKIE['LOGGED_ETAB']) {
								echo ' selected ';
							}
							echo '>'.$choix.'</option>';
						}
						echo '</select></div>';
					}
					else if(isset($_COOKIE['PREFIX'])) {
						$ibulle_could=@mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$_COOKIE['PREFIX']."_parametres WHERE param_nom = 'freq_connexion_infobulle'"));
						$ibulle_params =  @explode(";", $ibulle_could['valeur']);
					}
				}
				else {
					$ibulle_could=@mysqli_fetch_assoc(mysqli_query($bdd,"SELECT valeur FROM ".$prefix."_parametres WHERE param_nom = 'freq_connexion_infobulle'"));
					$ibulle_params = @explode(";", $ibulle_could['valeur']);
				}
				echo '<h1>'.IDENT1.'</h1>';
				if(isset($_SESSION['essai_con'])) {
					if($_SESSION['essai_con']>5) {
						echo $_SESSION['essai_con_mes'];
					}
				}
				echo '<script language="Javascript">
					function showPass() {
					  var x = document.getElementById("id_password");
					  var y = document.getElementById("eye");
					  if (x.type === "password") {
					    x.type = "text";
					    y.className = "fa-solid fa-eye-slash";
					  } else {
					    x.type = "password";
					    y.className = "fa-solid fa-eye";
					  }
					}
				</script>
				<input class="inptxti" type="text" id="loginform" name="login" maxlength="40" value="';
				if(@$multi=="ON"&&@$multipref=="1") {
					echo @$_COOKIE['LOGGED_ETAB'];
				}
				echo '" placeholder="'.IDENT2.'" style="margin-right:-6px;" />';
				echo '<span id="infoBulleContainer1"></span>';
				if(@$ibulle_params[0]=="1"&&@$ibulle_params[1]!="") { echo '&nbsp; &nbsp; <span title="'.$ibulle_params[1].'"><i class="fa-solid fa-circle-info" style="font-size:1.2em;"></i></span>'; }
				else if(@$ibulle_params[0]=="1"&&@$ibulle_params[2]!="") { echo '&nbsp; &nbsp; <i class="fa-regular fa-circle" style="font-size:1.2em;color:#fff;"></i>'; }
				echo '<br>
					<input class="inptxti" type="password" name="mdp" autocomplete="current-password" required="" maxlength="30" value="" placeholder="'.PW.'" id="id_password" /><i class="fa-solid fa-eye" id="eye" onclick="showPass()" style="margin-left: -26px; cursor: pointer;"></i>';
				echo '<span id="infoBulleContainer2"></span>';
				if(@$ibulle_params[0]=="1"&&@$ibulle_params[2]!="") { echo '&nbsp; &nbsp; <span title="'.$ibulle_params[2].'"><i class="fa-solid fa-circle-info" style="font-size:1.2em;"></i></span>'; }
				else if(@$ibulle_params[0]=="1"&&@$ibulle_params[1]!="") { echo '&nbsp; &nbsp; <i class="fa-regular fa-circle" style="font-size:1.2em;color:#fff;"></i>'; }
				echo '<br>
					<input class="bouton inptxti boutdb" type="submit" value="'.VALID.'" /></form>
					<br><a onmousedown="toggleDiv(\'mdpdiv\');"><input style="margin-top:20px;font-size:0.7em;" type="button" value="'.TONEWPW.'" /></a></div>
				<div class="center" id="mdpdiv" style="display:none;">'.NEWPW.' <form method="post" name="pass" action="" class="padd2"><input class="inptxti" type="text" name="loginp" maxlength="40" value="';
				if(@$multi=="ON"&&@$multipref=="1") {
					echo @$_COOKIE['LOGGED_ETAB'];
				}
				echo '" placeholder="'.IDENT2.'" /><br><input class="inptxti" type="text" name="mailp" maxlength="60" value="" placeholder="'.MAIL.'" /><br><input class="bouton inptxti boutdb" type="submit" value="'.VALID.'" /></form>';
			}
			?>
			<script>
			    const ERROR1 = "<?php echo ERROR1; ?>";
    			const ERROR2 = "<?php echo ERROR2; ?>";
			    // Déclaration de la variable JavaScript pour stocker le préfix
			    var prefixValue = '<?php echo $prefix; ?>';

			    function etab_resopt() {
			        var selectElement = document.getElementById("etabchoix");
			        var selectedValue = selectElement.value;

			        // Envoi de la valeur sélectionnée au script PHP via AJAX
			        var xhr = new XMLHttpRequest();
			        xhr.onreadystatechange = function() {
			            if (xhr.readyState === XMLHttpRequest.DONE) {
			                if (xhr.status === 200) {
			                    var prefix = xhr.responseText;
			                    console.log("Prefix:", prefix);
			                    prefixValue = prefix; 
			                    var response = xhr.responseText;
					            // Vérifiez si la réponse correspond à vos conditions
					            var ibulle_params = response.split(';');
					            // Vérifiez chaque partie de la réponse et effectuez les actions appropriées
					            if (ibulle_params.length >= 3) {
					                var infoBulleContainer1 = document.getElementById("infoBulleContainer1");
					                var infoBulleContainer = document.getElementById("infoBulleContainer2");
					                if (ibulle_params[0]==="1"&& ibulle_params[1]!=="") { 
					                	infoBulleContainer1.innerHTML = '&nbsp; &nbsp; <span title="' + ibulle_params[1] + '"><i class="fa-solid fa-circle-info" style="font-size:1.2em;"></i></span>';
					                } else if(ibulle_params[0]==="1"&& ibulle_params[2]!=="") { infoBulleContainer1.innerHTML =  '&nbsp; &nbsp; <i class="fa-regular fa-circle" style="font-size:1.2em;color:#fff;"></i>'; }
					                if (ibulle_params[0]==="1"&& ibulle_params[2]!=="") { 
					                	infoBulleContainer2.innerHTML = '&nbsp; &nbsp; <span title="' + ibulle_params[2] + '"><i class="fa-solid fa-circle-info" style="font-size:1.2em;"></i></span>';
					                } else if(ibulle_params[0]==="1"&& ibulle_params[1]!=="") { infoBulleContainer2.innerHTML =  '&nbsp; &nbsp; <i class="fa-regular fa-circle" style="font-size:1.2em;color:#fff;"></i>'; }
					                if(ibulle_params[0]==="0") {
					                    infoBulleContainer1.innerHTML = '';
					                    infoBulleContainer2.innerHTML = '';
					                }
					            } else {
					                console.error(ERROR1);
					            }
			                } else {
			                    console.error(ERROR2);
			                }
			            }
			        };
			        console.log(selectedValue);
			        xhr.open("GET", "db/get_prefix.php?value=" + selectedValue, true);
			        xhr.send();
			    }
			</script>
			<?php
			mysqli_close($bdd);
		}
		?>
	</section>
	<script>
        window.addEventListener('load', function() {
            var monInput = document.getElementById('loginform');
            monInput.focus();            
            // Positionne le curseur à la fin du texte dans le champ de texte
            monInput.setSelectionRange(monInput.value.length, monInput.value.length);
        });
    </script>
</body>
</html>
