<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../index.php');
    exit;
}

// ======================
// MULTI CONFIG
// ======================
$multiFile = __DIR__ . '/idl_multi.php';

if (!file_exists($multiFile)) {
    if (file_exists(__DIR__ . '/_idl_multi.php')) {
        rename(__DIR__ . '/_idl_multi.php', $multiFile);
    }
}

// include propre (sans @)
if (file_exists($multiFile)) {
    require_once $multiFile;
}

// config globale
require_once dirname(__DIR__) . '/config.php';

// ======================
// GESTION MULTI ETABLISSEMENT
// ======================
if (!empty($multi) && $multi === "ON") {

    if (!empty($multipref) && $multipref == 1) {

        if (!empty($_POST['login'])) {
            $_SESSION['etabchoix'] = substr($_POST['login'], 0, 5);
        }

    } else {

        if (!empty($_POST['etabchoix'])) {
            // sécurité : nettoyer valeur
            $_SESSION['etabchoix'] = preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['etabchoix']);
        }
    }

    // recharge multi après choix
    if (file_exists($multiFile)) {
        require $multiFile;
    }

}

// ======================
// CONNEXION BDD (PDO)
// ======================
require_once BASE_PATH . '/db/idl_connect.php';

// ======================
// VALIDATION PREFIX
// ======================
if (empty($prefix) || !preg_match('/^[a-zA-Z0-9_]+$/', $prefix)) {

    $_SESSION['logright'] = '0';

    header('Location: ../index.php');
    exit;
}
else {

	$table_name = $prefix . "_parametres";

	try {
	    $stmt = $pdo->prepare("SHOW TABLES LIKE :table");
	    $stmt->execute([':table' => $table_name]);
	    $tableExists = $stmt->rowCount() > 0;
	} catch (Exception $e) {
	    $tableExists = false;
	}

	if ($tableExists) {
		// ======================
	    // RÉCUP LOGIN
	    // ======================
	    $log1 = '';
	    $log2 = '';

	    if (!empty($_POST['login']) && !empty($_POST['mdp'])) {

	        if (!empty($multi) && $multi === "ON" && !empty($multipref) && $multipref == 1) {
	            $log1 = substr($_POST['login'], 5);
	        } else {
	            $log1 = $_POST['login'];
	        }

	        $log2 = $_POST['mdp'];

	        $_SESSION['essai_con'] = 0;

	    } else {
	        $_SESSION['essai_con'] = ($_SESSION['essai_con'] ?? 0) + 1;
	    }

	    if (empty($prefix)) {
	        $prefix = 'idlog';
	    }

	    // ======================
	    // LIMIT BRUTE FORCE
	    // ======================
	    if ($_SESSION['essai_con'] >= 6) {
	        $_SESSION['logright'] = '0';
	        header('Location: ../index.php');
	        exit;
	    }
	    // CONTINUER AVEC l.121 et suiv.
		// ======================
	    // LOGIN NORMAL
	    // ======================
	    if (!empty($log1) && !empty($log2)) {

	        // Vérifie user
	        $stmt = $pdo->prepare("
	            SELECT * 
	            FROM {$prefix}_user 
	            WHERE login = :login
	        ");
	        $stmt->execute([':login' => $log1]);
	        $user = $stmt->fetch();

	        // ======================
	        // MODE RESERVER
	        // ======================
	        if (!$user) {

			    $stmt = $pdo->prepare("
			        SELECT valeur 
			        FROM {$prefix}_parametres 
			        WHERE param_nom = 'freq_reseleve'
			    ");
			    $stmt->execute();
			    $reserv_could = $stmt->fetch();

			    // =========================================================
			    // CAS 1 : MODE "reserver"
			    // =========================================================
			    if (($reserv_could['valeur'] ?? 0) == 1 && $log1 === 'reserver') {

			        $stmt = $pdo->prepare("
			            SELECT param_nom, valeur 
			            FROM {$prefix}_parametres 
			            WHERE param_nom IN ('freq_reseleve_mdp','freq_reseleve_mdpsel')
			        ");
			        $stmt->execute();
			        $params = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

			        $storedHash = $params['freq_reseleve_mdp'] ?? '';
			        $storedSel  = $params['freq_reseleve_mdpsel'] ?? '0';

			        $logincheck = false;

			        if ($storedSel === '0') {

			            // password_hash moderne
			            if (password_verify($log2, $storedHash)) {
			                $logincheck = true;

			                // migration auto
			                $newHash = password_hash($log2, PASSWORD_DEFAULT);

			                $stmt = $pdo->prepare("
			                    UPDATE {$prefix}_parametres 
			                    SET valeur = :val 
			                    WHERE param_nom = 'freq_reseleve_mdp'
			                ");
			                $stmt->execute([':val' => $newHash]);
			            }

			        } else {

			            // ancien SHA256 + sel
			            $hashed = hash('sha256', $log2 . $storedSel);

			            if (hash_equals($storedHash, $hashed)) {
			                $logincheck = true;
			            }
			        }

			        if (!$logincheck) {
			            $_SESSION['logright'] = '0';
			            header('Location: ../index.php');
			            exit;
			        }

			        session_regenerate_id(true);

			        $_SESSION['logright'] = '1';
			        $_SESSION['userres_droits'] = 1;

			        $_SESSION['etabchoix'] = (!empty($multipref) && $multipref == 1)
			            ? substr($_POST['login'], 0, 5)
			            : ($_POST['etabchoix'] ?? '');

			        $_SESSION['essai_res'] = 0;

			        header('Location: ../reserver.php');
			        exit;
			    }

			    // =========================================================
			    // CAS 2 : AUTH ELEVE
			    // =========================================================
			    elseif (($reserv_could['valeur'] ?? 0) == 2) {
			    	
			        // Détermination du champ identifiant
			        $stmt = $pdo->prepare("
		                SELECT valeur 
		                FROM {$prefix}_parametres 
		                WHERE param_nom = 'freq_resmodauth'
		            ");
		            $stmt->execute();
		            $auth_info = $stmt->fetch();

		            switch ($auth_info['valeur'] ?? '') {
		                case 'prenomnom':
		                case 'pnom':
		                    $identmod = 'id_constr';
		                    break;
		                case 'perso':
		                    $identmod = 'id_perso';
		                    break;
		                default:
		                    $identmod = 'code';
		            }

			        // Recherche utilisateur
			        $stmt = $pdo->prepare("
			            SELECT * 
			            FROM {$prefix}_eleves 
			            WHERE {$identmod} = :login
			        ");
			        $stmt->execute([':login' => $log1]);
			        $user_info = $stmt->fetch();

			        if ($user_info) {
			            $_SESSION['lang'] = $user_info['lang'] ?? '';

			            // ======================
			            // NOUVELLE METHODE
			            // ======================
			            $logincheck = false;

						$storedHash = $user_info['mdp'] ?? '';

						// ======================================================
						// 1. Vérification du mot de passe (ancien + nouveau)
						// ======================================================

						// CAS 1 : bcrypt / password_hash (MODERNE)
						if (str_starts_with($storedHash, '$2y$') || str_starts_with($storedHash, '$argon')) {

						    if (password_verify($log2, $storedHash)) {
						        $logincheck = true;
						    }

						// CAS 2 : ANCIEN SHA256 + sel
						} elseif (!empty($user_info['sel']) && $user_info['sel'] !== '0') {

						    $test = hash('sha256', $log2 . $user_info['sel']);

						    if (hash_equals($storedHash, $test)) {
						        $logincheck = true;

						        // 🔥 MIGRATION AUTO VERS password_hash
						        $newHash = password_hash($log2, PASSWORD_DEFAULT);

						        $stmt = $pdo->prepare("
						            UPDATE {$prefix}_eleves 
						            SET mdp = :mdp, sel = '0'
						            WHERE {$identmod} = :login
						        ");
						        $stmt->execute([
						            ':mdp' => $newHash,
						            ':login' => $log1
						        ]);
						    }

						// CAS 3 : ANCIEN SHA256 SANS sel (sécurité fallback)
						} elseif (strlen($storedHash) === 64) {

						    $test = hash('sha256', $log2);

						    if (hash_equals($storedHash, $test)) {
						        $logincheck = true;

						        // 🔥 MIGRATION AUTO
						        $newHash = password_hash($log2, PASSWORD_DEFAULT);

						        $stmt = $pdo->prepare("
						            UPDATE {$prefix}_eleves 
						            SET mdp = :mdp, sel = '0'
						            WHERE {$identmod} = :login
						        ");
						        $stmt->execute([
						            ':mdp' => $newHash,
						            ':login' => $log1
						        ]);
						    }

						// CAS 4 : MySQL PASSWORD() (legacy ultime)
						} else {

						    $stmt = $pdo->prepare("
						        SELECT 1 
						        FROM {$prefix}_eleves 
						        WHERE {$identmod} = :login 
						        AND mdp = PASSWORD(:pwd)
						        LIMIT 1
						    ");

						    $stmt->execute([
						        ':login' => $log1,
						        ':pwd' => $log2
						    ]);

						    if ($stmt->fetchColumn()) {
						        $logincheck = true;

						        // 🔥 MIGRATION AUTO
						        $newHash = password_hash($log2, PASSWORD_DEFAULT);

						        $stmt = $pdo->prepare("
						            UPDATE {$prefix}_eleves 
						            SET mdp = :mdp, sel = '0'
						            WHERE {$identmod} = :login
						        ");
						        $stmt->execute([
						            ':mdp' => $newHash,
						            ':login' => $log1
						        ]);
						    }
						}

						// ======================================================
						// 2. RESULTAT FINAL
						// ======================================================
						if (!$logincheck) {
						    $_SESSION['logright'] = '0';
						    header('Location: ../index.php');
						    exit;
						}

						// ======================================================
						// 3. LOGIN OK
						// ======================================================
						session_regenerate_id(true);

						$_SESSION['logright'] = '1';
						$_SESSION['userres_droits'] = 1;
						$_SESSION['coderes'] = $log1;
						$_SESSION['essai_res'] = 0;

						$_SESSION['etabchoix'] = (!empty($multipref) && $multipref == 1)
						    ? substr($_POST['login'], 0, 5)
						    : ($_POST['etabchoix'] ?? '');

						header('Location: ../reserver.php');
						exit;

			        } else {

			            $_SESSION['essai_con'] = ($_SESSION['essai_con'] ?? 0) + 1;

			            if ($_SESSION['essai_con'] > 5) {
			                $_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
			            }

			            $_SESSION['logright'] = '0';
			            header('Location: ../index.php');
			            exit;
			        }
			    }

			    // =========================================================
			    // CAS PAR DEFAUT
			    // =========================================================
			    else {

			        $_SESSION['essai_con'] = ($_SESSION['essai_con'] ?? 0) + 1;

			        if ($_SESSION['essai_con'] > 5) {
			            $_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
			        }

			        $_SESSION['logright'] = '0';
			        header('Location: ../index.php');
			        exit;
			    }
			}

	        // ======================
	        // UTILISATEUR NORMAL
	        // ======================
	        if ($user) {

			    $storedHash = $user['mdp'];
			    $storedSel  = $user['sel'] ?? '0';

			    $loginOK = false;

			    // ======================
			    // CAS 1 : NEW PASSWORD_HASH
			    // ======================
			    if (str_starts_with($storedHash, '$2y$')) {

			        if (password_verify($log2, $storedHash)) {
			            $loginOK = true;
			        }

			    }

			    // ======================
			    // CAS 2 : SHA256 + SEL (ancien système)
			    // ======================
			    else if ($storedSel !== '0' && $storedSel !== null) {

			        $hashed = hash('sha256', $log2 . $storedSel);

			        if (hash_equals($storedHash, $hashed)) {
			            $loginOK = true;

			            $newHash = password_hash($log2, PASSWORD_DEFAULT);

				        $upd = $pdo->prepare("
				            UPDATE {$prefix}_user 
				            SET mdp = :mdp, sel = '0'
				            WHERE login = :login
				        ");
				        $upd->execute([
				            ':mdp' => $newHash,
				            ':login' => $log1
				        ]);
			        }
			    }

			    // ======================
			    // CAS 3 : très ancien PASSWORD()
			    // ======================
			    else {

			        // ⚠️ seulement si encore utilisé en base
			        $stmt = $pdo->prepare("
			            SELECT id 
			            FROM {$prefix}_user 
			            WHERE login = :login 
			            AND mdp = PASSWORD(:mdp)
			        ");
			        $stmt->execute([
			            ':login' => $log1,
			            ':mdp'   => $log2
			        ]);

			        if ($stmt->fetch()) {
			            $loginOK = true;

			            // migration immédiate
			            $newHash = password_hash($log2, PASSWORD_DEFAULT);

			            $upd = $pdo->prepare("
			                UPDATE {$prefix}_user 
			                SET mdp = :mdp, sel = '0'
			                WHERE login = :login
			            ");
			            $upd->execute([
			                ':mdp' => $newHash,
			                ':login' => $log1
			            ]);
			        }
			    }

			    // ======================
			    // RESULTAT
			    // ======================
			    if ($loginOK) {

			        // ======================
				    // UTILISATEUR RÉCUPÉRÉ
				    // ======================
				    //$user_info = $verif_user->fetch();
				    $user_info = $user;

				    if (!$user_info) {
				        $_SESSION['logright'] = '0';
				        header('Location: ../index.php');
				        exit;
				    }

				    // ======================
				    // AUTH MODE CHECK
				    // ======================
				    $logincheck = false;

				    // ancien mode PASSWORD MySQL (obsolète mais conservé compat)
				    if (($cssbdd['valeur'] ?? 0) < 0.50) {

				        if (password_verify($log2, $user_info['mdp'])) {
				            $logincheck = true;
				        }

				    }
				    // migration + hash moderne
				    else if (($user_info['sel'] ?? '0') === '0') {

				        if (password_verify($log2, $user_info['mdp'])) {

				            $logincheck = true;

				            // migration automatique vers SHA fallback ou password_hash
				            $newHash = password_hash($log2, PASSWORD_DEFAULT);

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

				    }
				    // ancien SHA256 + sel
				    else {

				        $hashed = hash('sha256', $log2 . $user_info['sel']);

				        if (hash_equals($user_info['mdp'], $hashed)) {
				            $logincheck = true;
				        }
				    }				    

				    // ======================
				    // LOGIN OK
				    // ======================
				    session_regenerate_id(true);

				    $_SESSION['logright'] = '1';
				    $_SESSION['user_droits_arr'] = $user_info['droits'];
				    $_SESSION['user_id'] = $user_info['id'];
				    $_SESSION['login'] = $user_info['login'];
				    $_SESSION['lang'] = $user_info['lang'];
				    $_SESSION['accueil'] = $user_info['accueil'];
				    $_SESSION['auth_mail'] = $user_info['auth_mail'];
				    $_SESSION['auth_chat'] = $user_info['auth_chat'];
				    $_SESSION['freq_res_dureemax'] = $user_info['freq_res_dureemax'];

				    // ======================
				    // DROITS SPÉCIAUX
				    // ======================
				    $specdroits = explode(';', $user_info['droits_spe'] ?? '');

				    $keys = [
				        'minutes','nbcren','inscprec','crenchoix','classinscript',
				        'affgroupe','journalmodif','buttonsor','buttonexc',
				        'retardsaff1','retardsaff2','accesjournal','freqinscritsafter',
				        'inscriptallday','freqonlyresas','freqvalidmes',
				        'freqcodeonly','affresa_norights', 'nobuttonenleverresa'
				    ];

				    foreach ($keys as $i => $key) {
				        $_SESSION[$key] = $specdroits[$i] ?? null;
				        echo $_SESSION[$key];
				      }

				    // ======================
				    // URL BASE SAFE
				    // ======================
				    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
				        ? 'https://'
				        : 'http://';

				    $_SESSION['url_base'] = $scheme . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);

				    $_SESSION['connected_info'] = $user_info['connected_info'];
				    
				    // ======================
				    // MULTI
				    // ======================
				    if (!empty($multi) && $multi === "ON") {

				        if (!empty($multipref) && $multipref == 1) {
				            $_SESSION['etabchoix'] = substr($_POST['login'] ?? '', 0, 5);
				        } else {
				            $_SESSION['etabchoix'] = $_POST['etabchoix'] ?? '';
				        }
				    }

				    // ======================
				    // ONLINE USERS TABLE
				    // ======================
				    $stmt = $pdo->prepare("
				        SELECT user_id FROM {$prefix}_userconnect WHERE user_id = :id
				    ");
				    $stmt->execute([':id' => $user_info['id']]);

				    if ($stmt->rowCount() > 0) {

				        $stmt = $pdo->prepare("
				            UPDATE {$prefix}_userconnect 
				            SET connected = :time 
				            WHERE user_id = :id
				        ");
				        $stmt->execute([
				            ':time' => time(),
				            ':id' => $user_info['id']
				        ]);

				    } else {

				        $stmt = $pdo->prepare("
				            INSERT INTO {$prefix}_userconnect (user_id, connected)
				            VALUES (:id, :time)
				        ");
				        $stmt->execute([
				            ':id' => $user_info['id'],
				            ':time' => time()
				        ]);
				    }

				    // ======================
				    // DEFAULT SETTINGS
				    // ======================
				    if (!empty($user_info['espace_default'])) {
				        $_SESSION['espuser'] = $user_info['espace_default'];
				    }

				    $_SESSION['align_activ'] = $user_info['align_activ'];
				    $_SESSION['align_espace'] = $user_info['align_espace'];

				    // ======================
				    // VERSION CHECK SAFE
				    // ======================
				    $vers_offurl = @file_get_contents('../version.txt');
				    $vers_offic = substr($vers_offurl, 0, strpos($vers_offurl, "/"));

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

				    if ($dbVersion !== $vers_offic) {

				        $stmt = $pdo->prepare("
				            UPDATE {$prefix}_parametres 
				            SET valeur = :v 
				            WHERE param_nom = 'version_log'
				        ");
				        $stmt->execute([':v' => $vers_offic]);
				    }

				    // ======================
				    // REDIRECTION SAFE
				    // ======================
				    $redirect = ['', 'eval', 'edit', 'edt', 'freq', 'param', 'database'];

				    if (!empty($_SESSION['accueil']) && isset($redirect[$_SESSION['accueil']])) {
				        header("Location: ../" . $redirect[$_SESSION['accueil']] . ".php");
				        exit;
				    }

				    // ======================
				    // DROITS REDIRECTION
				    // ======================
				    $droits = str_split($user_info['droits'] ?? '');

				    $map = [
				        'freq', 'edt', 'edit', 'eval', 'database', 'param'
				    ];

				    foreach ($map as $i => $page) {

				        if (($droits[$i] ?? 1) == 0 || (($droits[$i] ?? 1) > 1 && ($droits[$i] ?? 1) < 7)) {
				            header("Location: ../{$page}.php");
				            exit;
				        }
				    }

				    echo NOACCESS;
				}
				else {

			        $_SESSION['logright'] = '0';
			        header('Location: ../index.php');
			        exit;
			    }

			    } else {

			        $_SESSION['logright'] = '0';
			        header('Location: ../index.php');
			        exit;
			    }
			}
	    }
	elseif (($reserv_could['valeur'] ?? 0) == 2) {

	    // ======================
	    // DÉTERMINER IDENTIFIANT
	    // ======================
	    if (($cssbdd['valeur'] ?? 0) > 0.47) {

	        $stmt = $pdo->prepare("
	            SELECT valeur 
	            FROM {$prefix}_parametres 
	            WHERE param_nom = 'freq_resmodauth'
	        ");
	        $stmt->execute();
	        $auth_info = $stmt->fetch();

	        switch ($auth_info['valeur'] ?? '') {
	            case 'prenomnom':
	            case 'pnom':
	                $identmod = 'id_constr';
	                break;
	            case 'perso':
	                $identmod = 'id_perso';
	                break;
	            default:
	                $identmod = 'code';
	        }

	    } else {
	        $identmod = 'code';
	    }

	    // sécurité nom colonne (IMPORTANT)
	    $allowedCols = ['id_constr', 'id_perso', 'code'];
	    if (!in_array($identmod, $allowedCols, true)) {
	        $identmod = 'code';
	    }

	    // ======================
	    // RECHERCHE UTILISATEUR
	    // ======================
	    $stmt = $pdo->prepare("
	        SELECT * 
	        FROM {$prefix}_eleves 
	        WHERE {$identmod} = :login
	        LIMIT 1
	    ");
	    $stmt->execute([':login' => $log1]);
	    $user_info = $stmt->fetch();

	    if ($user_info) {

	        $_SESSION['lang'] = $user_info['lang'] ?? 'fr';

	        $storedHash = $user_info['mdp'] ?? '';
	        $storedSel  = $user_info['sel'] ?? '0';

	        $logincheck = false;

	        // ======================
	        // NOUVELLE MÉTHODE
	        // ======================
	        if ($storedSel === '0' || $storedSel === null) {

	            if (password_verify($log2, $storedHash)) {
	                $logincheck = true;

	                // migration automatique vers hash moderne
	                $newHash = password_hash($log2, PASSWORD_DEFAULT);

	                $stmt = $pdo->prepare("
	                    UPDATE {$prefix}_eleves 
	                    SET mdp = :mdp, sel = '0'
	                    WHERE {$identmod} = :login
	                ");
	                $stmt->execute([
	                    ':mdp' => $newHash,
	                    ':login' => $log1
	                ]);
	            }

	        } else {

	            // ancienne méthode SHA256 + sel
	            $hashed = hash('sha256', $log2 . $storedSel);

	            if (hash_equals($storedHash, $hashed)) {
	                $logincheck = true;
	            }
	        }

	        // ======================
	        // ECHEC LOGIN
	        // ======================
	        if (!$logincheck) {

	            $_SESSION['essai_con'] = ($_SESSION['essai_con'] ?? 0) + 1;

	            if ($_SESSION['essai_con'] > 5) {
	                $_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
	            }

	            $_SESSION['logright'] = '0';

	            header('Location: ../index.php');
	            exit;
	        }

	        // ======================
	        // LOGIN OK
	        // ======================
	        session_regenerate_id(true);

	        $_SESSION['userres_droits'] = 1;
	        $_SESSION['coderes'] = $log1;
	        $_SESSION['essai_res'] = 0;
	        $_SESSION['logright'] = '1';

	        if (!empty($multi) && !empty($multipref) && $multipref == 1) {
	            $_SESSION['etabchoix'] = substr($_POST['login'], 0, 5);
	        } else {
	            $_SESSION['etabchoix'] = $_POST['etabchoix'] ?? '';
	        }

	        header('Location: ../reserver.php');
	        exit;

	    } else {

	        // ======================
	        // USER NON TROUVÉ
	        // ======================
	        $_SESSION['essai_con'] = ($_SESSION['essai_con'] ?? 0) + 1;

	        if ($_SESSION['essai_con'] > 5) {
	            $_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
	        }

	        $_SESSION['logright'] = '0';

	        header('Location: ../index.php');
	        exit;
	    }
	}
	else {

	    // ======================
	    // UTILISATEUR RÉCUPÉRÉ
	    // ======================
	    $user_info = $verif_user->fetch();

	    if (!$user_info) {
	        $_SESSION['logright'] = '0';
	        header('Location: ../index.php');
	        exit;
	    }

	    // ======================
	    // AUTH MODE CHECK
	    // ======================
	    $logincheck = false;

	    // ancien mode PASSWORD MySQL (obsolète mais conservé compat)
	    if (($cssbdd['valeur'] ?? 0) < 0.50) {

	        if (password_verify($log2, $user_info['mdp'])) {
	            $logincheck = true;
	        }

	    }
	    // migration + hash moderne
	    else if (($user_info['sel'] ?? '0') === '0') {

	        if (password_verify($log2, $user_info['mdp'])) {

	            $logincheck = true;

	            // migration automatique vers SHA fallback ou password_hash
	            $newHash = password_hash($log2, PASSWORD_DEFAULT);

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

	    }
	    // ancien SHA256 + sel
	    else {

	        $hashed = hash('sha256', $log2 . $user_info['sel']);

	        if (hash_equals($user_info['mdp'], $hashed)) {
	            $logincheck = true;
	        }
	    }

	    // ======================
	    // ECHEC LOGIN
	    // ======================
	    if (!$logincheck) {

	        $_SESSION['essai_con'] = ($_SESSION['essai_con'] ?? 0) + 1;

	        if ($_SESSION['essai_con'] > 5) {
	            $_SESSION['essai_con_mes'] = '<p class="signal">'.ESSAIS1.'</p>';
	        }

	        $_SESSION['logright'] = '0';

	        header('Location: ../index.php');
	        exit;
	    }

	    // ======================
	    // LOGIN OK
	    // ======================
	    session_regenerate_id(true);

	    $_SESSION['logright'] = '1';
	    $_SESSION['user_droits_arr'] = $user_info['droits'];
	    $_SESSION['user_id'] = $user_info['id'];
	    $_SESSION['login'] = $user_info['login'];
	    $_SESSION['lang'] = $user_info['lang'];
	    $_SESSION['accueil'] = $user_info['accueil'];
	    $_SESSION['auth_mail'] = $user_info['auth_mail'];
	    $_SESSION['auth_chat'] = $user_info['auth_chat'];
	    $_SESSION['freq_res_dureemax'] = $user_info['freq_res_dureemax'];

	    // ======================
	    // DROITS SPÉCIAUX
	    // ======================
	    $specdroits = explode(';', $user_info['droits_spe'] ?? '');

	    $keys = [
	        'minutes','nbcren','inscprec','crenchoix','classinscript',
	        'affgroupe','journalmodif','buttonsor','buttonexc',
	        'retardsaff1','retardsaff2','accesjournal','freqinscritsafter',
	        'inscriptallday','freqonlyresas','freqvalidmes',
	        'freqcodeonly','affresa_norights','nobuttonenleverresa'
	    ];

	    foreach ($keys as $i => $key) {
	        $_SESSION[$key] = $specdroits[$i] ?? null;
	    }

	    // ======================
	    // URL BASE SAFE
	    // ======================
	    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
	        ? 'https://'
	        : 'http://';

	    $_SESSION['url_base'] = $scheme . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);

	    $_SESSION['connected_info'] = $user_info['connected_info'];
	    
	    // ======================
	    // MULTI
	    // ======================
	    if (!empty($multi) && $multi === "ON") {

	        if (!empty($multipref) && $multipref == 1) {
	            $_SESSION['etabchoix'] = substr($_POST['login'] ?? '', 0, 5);
	        } else {
	            $_SESSION['etabchoix'] = $_POST['etabchoix'] ?? '';
	        }
	    }

	    // ======================
	    // ONLINE USERS TABLE
	    // ======================
	    $stmt = $pdo->prepare("
	        SELECT user_id FROM {$prefix}_userconnect WHERE user_id = :id
	    ");
	    $stmt->execute([':id' => $user_info['id']]);

	    if ($stmt->rowCount() > 0) {

	        $stmt = $pdo->prepare("
	            UPDATE {$prefix}_userconnect 
	            SET connected = :time 
	            WHERE user_id = :id
	        ");
	        $stmt->execute([
	            ':time' => time(),
	            ':id' => $user_info['id']
	        ]);

	    } else {

	        $stmt = $pdo->prepare("
	            INSERT INTO {$prefix}_userconnect (user_id, connected)
	            VALUES (:id, :time)
	        ");
	        $stmt->execute([
	            ':id' => $user_info['id'],
	            ':time' => time()
	        ]);
	    }

	    // ======================
	    // DEFAULT SETTINGS
	    // ======================
	    if (!empty($user_info['espace_default'])) {
	        $_SESSION['espuser'] = $user_info['espace_default'];
	    }

	    $_SESSION['align_activ'] = $user_info['align_activ'];
	    $_SESSION['align_espace'] = $user_info['align_espace'];

	    // ======================
	    // VERSION CHECK SAFE
	    // ======================
	    $vers_offurl = @file_get_contents('../version.txt');
	    $vers_offic = substr($vers_offurl, 0, strpos($vers_offurl, "/"));

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

	    if ($dbVersion !== $vers_offic) {

	        $stmt = $pdo->prepare("
	            UPDATE {$prefix}_parametres 
	            SET valeur = :v 
	            WHERE param_nom = 'version_log'
	        ");
	        $stmt->execute([':v' => $vers_offic]);
	    }

	    // ======================
	    // REDIRECTION SAFE
	    // ======================
	    $redirect = ['', 'eval', 'edit', 'edt', 'freq', 'param', 'database'];

	    if (!empty($_SESSION['accueil']) && isset($redirect[$_SESSION['accueil']])) {
	        header("Location: ../" . $redirect[$_SESSION['accueil']] . ".php");
	        exit;
	    }

	    // ======================
	    // DROITS REDIRECTION
	    // ======================
	    $droits = str_split($user_info['droits'] ?? '');

	    $map = [
	        'freq', 'edt', 'edit', 'eval', 'database', 'param'
	    ];

	    foreach ($map as $i => $page) {

	        if (($droits[$i] ?? 1) == 0 || (($droits[$i] ?? 1) > 1 && ($droits[$i] ?? 1) < 7)) {
	            header("Location: ../{$page}.php");
	            exit;
	        }
	    }

	    echo NOACCESS;
	}
}
?>
