<?php 
session_start();
// ----------------------
// CONFIG
// ----------------------
$configFile = file_exists('db/idl_connect_data.php')
    ? 'db/idl_connect_data.php'
    : 'db/_idl_connect_data.php';

require_once $configFile;

if (file_exists('db/idl_multi.php')) {
    require_once 'db/idl_multi.php';
}
if (file_exists('config.php')) {
    require_once 'config.php';
}

// ----------------------
// TEST CONNEXION PDO
// ----------------------
$dbAvailable = false;

require_once 'db/idl_connect.php';

if (isset($pdo) && $pdo instanceof PDO) {

    try {

        $pdo->query("SELECT 1");

        $dbAvailable = true;

    } catch (Throwable $e) {

        error_log("Erreur PDO : " . $e->getMessage());
    }
}

// ----------------------
// LANGUES DISPONIBLES
// ----------------------
$langDir = __DIR__ . '/include/lang/';
$languages = [];

if (is_dir($langDir)) {
    foreach (scandir($langDir) as $file) {
        if (preg_match('/^([a-z]{2})\.php$/', $file, $matches)) {
            $code = $matches[1];
            $filePath = realpath($langDir . $file);

            // sécurité : éviter sortie du dossier
            if ($filePath && strpos($filePath, realpath($langDir)) === 0) {

                $content = file_get_contents($filePath);

                if (
                    preg_match('/define\(\s*[\'"]LANG_VALID[\'"]\s*,\s*true\s*\)/', $content) &&
                    preg_match('/\$lang_name\s*=\s*"([^"]+)"/', $content, $nameMatches)
                ) {
                    $languages[$code] = $nameMatches[1];
                }
            }
        }
    }
}

// ----------------------
// GESTION LANGUE
// ----------------------
$defaultLang = 'fr';
$selectedLang = $defaultLang;

// GET
if (
    isset($_GET['lang']) &&
    preg_match('/^[a-z]{2}$/', $_GET['lang']) &&
    isset($languages[$_GET['lang']])
) {
    $selectedLang = $_GET['lang'];
}

// SESSION
elseif (
    isset($_SESSION['lang']) &&
    isset($languages[$_SESSION['lang']])
) {
    $selectedLang = $_SESSION['lang'];
}

// COOKIE sécurisé
elseif (
    isset($_COOKIE['LANGM']) &&
    isset($languages[$_COOKIE['LANGM']])
) {
    $selectedLang = $_COOKIE['LANGM'];
}

$_SESSION['lang'] = $selectedLang;

// MULTI LANG
if (!empty($multi) && $multi === 'ON' && (!isset($multipref) || $multipref !== "1")) {
    if (isset($_COOKIE['LANGM']) && isset($languages[$_COOKIE['LANGM']])) {
        $_SESSION['lang'] = $_COOKIE['LANGM'];
    }
}

// ----------------------
// CHARGEMENT LANGUE
// ----------------------
$langFile = __DIR__ . '/include/lang/' . $_SESSION['lang'] . '.php';

if (file_exists($langFile)) {
    require_once $langFile;
} else {
    require_once __DIR__ . '/include/lang/' . $defaultLang . '.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 (!isset($pdo)) {
			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>';
			}
			exit;	
		}
		if(!isset($prefix)) { $prefix = 'idlog'; }
		if (isset($_SESSION['user_droits_arr'][4]) && $_SESSION['user_droits_arr'][4] == "2") {
		    try {
		        $url = "http://iddocs.fr/infodoclog/log/version.txt";
		        $vers_offurl = @file_get_contents($url);

		        if ($vers_offurl !== false) {

		            $vers_offbdd = trim(substr($vers_offurl, 5));

		            $stmt = $pdo->prepare("
		                SELECT valeur 
		                FROM {$prefix}_parametres 
		                WHERE param_nom = 'version_bdd'
		            ");
		            $stmt->execute();
		            $dbVersion = $stmt->fetchColumn();

		            if ($dbVersion && $dbVersion !== $vers_offbdd) {
		                header("Location: param.php?page=majlog");
		                exit;
		            }
		        }

		    } catch (Exception $e) {
		        error_log("Version check error: " . $e->getMessage());
		    }
		}
		$redirect = [
		    1 => 'eval',
		    2 => 'edit',
		    3 => 'edt',
		    4 => 'freq',
		    5 => 'param',
		    6 => 'database'
		];
		if (!empty($_SESSION['accueil']) && isset($redirect[$_SESSION['accueil']])) {
		    header("Location: " . $redirect[$_SESSION['accueil']] . ".php");
		    exit;
		}		
		if(isset($_SESSION['user_droits_arr'])) {
			$droits = trim($_SESSION['user_droits_arr'] ?? '');
		    if (is_array($droits)) {
		        $droits = implode('', $droits);
		    }
		    $map = [
		        'eval' => $droits[0] ?? 0,
		        'edit' => $droits[1] ?? 0,
		        'edt'  => $droits[2] ?? 0,
		        'freq' => $droits[3] ?? 0,
		        'param'=> $droits[4] ?? 0,
		        'database' => $droits[5] ?? 0
		    ];
		    foreach ($map as $page => $value) {
		        if ($value == 4 || $value == 2) {
		            header("Location: {$page}.php");
		            exit;
		        }
		    }

		    echo NOACCESS;
		    exit;
		}
		if (isset($_POST['mailp'], $_POST['loginp'])) {
			$mailp = trim($_POST['mailp']);
		    $loginp = trim($_POST['loginp']);

		    $stmt = $pdo->prepare("
		        SELECT id 
		        FROM {$prefix}_user 
		        WHERE login = :login AND mail = :mail
		    ");
		    $stmt->execute([
		        ':login' => $loginp,
		        ':mail'  => $mailp
		    ]);

		    $user = $stmt->fetch();

		    if ($user) {

		        // Génération mot de passe sécurisé
		        $mdp = bin2hex(random_bytes(6)); // 12 chars

		        $hash = password_hash($mdp, PASSWORD_DEFAULT);

		        $stmt = $pdo->prepare("
		            UPDATE {$prefix}_user 
		            SET mdp = :mdp 
		            WHERE id = :id
		        ");
		        $stmt->execute([
		            ':mdp' => $hash,
		            ':id'  => $user['id']
		        ]);

		        // mail
		        $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>';
		    }
		}
		?>
		<div class="center"><?php
			echo '<form method="post" name="enter" action="db/droits.php" class="padd2"><div class="center">';
			$loggedEtab = $_COOKIE['LOGGED_ETAB'] ?? '';
			$loggedEtabSafe = htmlspecialchars($loggedEtab, ENT_QUOTES, 'UTF-8');

			$ibulle_params = ["0","",""];

			if (!empty($multi) && $multi === 'ON') {

			    if (!isset($multipref) || $multipref != "1") {

			        echo '<br><div class="box"><select name="etabchoix" id="etabchoix" onchange="etab_resopt()">';

			        foreach ($multichoix as $choix) {
			            $choixSafe = htmlspecialchars($choix, ENT_QUOTES, 'UTF-8');

			            echo '<option value="'.$choixSafe.'"';
			            if ($choix === $loggedEtab) {
			                echo ' selected';
			            }
			            echo '>'.$choixSafe.'</option>';
			        }

			        echo '</select></div>';

			    } elseif (!empty($_COOKIE['PREFIX'])) {

			        $prefixCookie = preg_replace('/[^a-zA-Z0-9_]/', '', $_COOKIE['PREFIX']);

			        try {
			            $stmt = $pdo->query("
			                SELECT valeur 
			                FROM {$prefixCookie}_parametres 
			                WHERE param_nom = 'freq_connexion_infobulle'
			            ");
			            $ibulle_could = $stmt->fetch();
			            $ibulle_params = explode(";", $ibulle_could['valeur'] ?? '');
			        } catch (Exception $e) {
			            error_log($e->getMessage());
			        }
			    }

			} else {

			    try {
			        $stmt = $pdo->query("
			            SELECT valeur 
			            FROM {$prefix}_parametres 
			            WHERE param_nom = 'freq_connexion_infobulle'
			        ");
			        $ibulle_could = $stmt->fetch();
			        $ibulle_params = explode(";", $ibulle_could['valeur'] ?? '');
			    } catch (Exception $e) {
			        error_log($e->getMessage());
			    }
			}

			// ======================
			// ERREURS LOGIN
			// ======================
			if (isset($_SESSION['logright']) && $_SESSION['logright'] === '0') {
			    echo '<p class="signal">'.IDENT_ERR.'</p>';
			}

			// ======================
			// TITRE
			// ======================
			echo '<h1>'.IDENT1.'</h1>';

			// ======================
			// BRUTE FORCE MESSAGE
			// ======================
			if (!empty($_SESSION['essai_con']) && $_SESSION['essai_con'] > 5) {
			    echo htmlspecialchars($_SESSION['essai_con_mes'], ENT_QUOTES, 'UTF-8');
			}

			// ======================
			// JS SHOW PASSWORD
			// ======================
			?>
			<script>
			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>
			<?php

			// ======================
			// LOGIN INPUT
			// ======================
			$loginValue = '';

			if (!empty($multi) && $multi === "ON" && !empty($multipref) && $multipref == "1") {
			    $loginValue = $loggedEtabSafe;
			}

			echo '<input class="inptxti" type="text" id="loginform" name="login" maxlength="40" value="'.$loginValue.'" placeholder="'.IDENT2;

			if (!empty($multi) && $multi === "ON" && !empty($multipref) && $multipref == "1") {
			    echo IDENT_PREF;
			}

			echo '" style="margin-right:-6px;" />';

			// ======================
			// INFO BULLE LOGIN
			// ======================
			echo '<span id="infoBulleContainer1"></span>';

			if (($ibulle_params[0] ?? "") == "1" && !empty($ibulle_params[1])) {
			    echo '&nbsp; &nbsp; <span title="'.htmlspecialchars($ibulle_params[1]).'"><i class="fa-solid fa-circle-info" style="font-size:1.2em;"></i></span>';
			} elseif (($ibulle_params[0] ?? "") == "1" && !empty($ibulle_params[2])) {
			    echo '&nbsp; &nbsp; <i class="fa-regular fa-circle" style="font-size:1.2em;color:#fff;"></i>';
			}

			// ======================
			// PASSWORD INPUT
			// ======================
			echo '<br>
			<input class="inptxti" type="password" name="mdp" autocomplete="current-password" required maxlength="30" placeholder="'.PW.'" id="id_password" />
			<i class="fa-solid fa-eye" id="eye" onclick="showPass()" style="margin-left: -26px; cursor: pointer;"></i>';

			// ======================
			// INFO BULLE PASSWORD
			// ======================
			echo '<span id="infoBulleContainer2"></span>';

			if (($ibulle_params[0] ?? "") == "1" && !empty($ibulle_params[2])) {
			    echo '&nbsp; &nbsp; <span title="'.htmlspecialchars($ibulle_params[2]).'"><i class="fa-solid fa-circle-info" style="font-size:1.2em;"></i></span>';
			} elseif (($ibulle_params[0] ?? "") == "1" && !empty($ibulle_params[1])) {
			    echo '&nbsp; &nbsp; <i class="fa-regular fa-circle" style="font-size:1.2em;color:#fff;"></i>';
			}

			// ======================
			// SUBMIT
			// ======================
			echo '<br>
			<input class="bouton inptxti boutdb" type="submit" value="'.VALID.'" />
			</form>';

			// ======================
			// RESET PASSWORD BUTTON
			// ======================
			echo '<br>
			<a onmousedown="toggleDiv(\'mdpdiv\');">
			    <input style="margin-top:20px;font-size:0.7em;" type="button" value="'.TONEWPW.'" />
			</a>
			</div>';

			// ======================
			// RESET PASSWORD FORM
			// ======================
			echo '<div class="center" id="mdpdiv" style="display:none;">
			<br>'.NEWPW.'<br><br>

			<form method="post" name="pass" action="" class="padd2">

			<input class="inptxti" type="text" name="loginp" maxlength="40" value="'.$loginValue.'" placeholder="'.IDENT2.'" />

			<br>

			<input class="inptxti" type="email" name="mailp" maxlength="60" placeholder="'.MAIL.'" />

			<br>

			<input class="bouton inptxti boutdb" type="submit" value="'.VALID.'" />

			</form>
			</div>';?>
		</div>
		<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>
