<?php require('head.php');
if (@$infos_user['token'] == @$_SESSION['token'] && @$_SESSION['token'] != '') {
	if (@$_GET['action'] == 'logout') {
		$_SESSION['user'] = '';
		$_SESSION['token'] = '';
		header('Refresh:1; url=connexion.php');
		echo 'Vous êtes déconnecté!';
	} else {
		header('Refresh:1; url=index.php');
		echo 'Vous êtes connecté en tant que: <b>' . $_SESSION['user'] . '</b>';
	}
} elseif (@$_POST['user'] && @$_POST['pass']) {
	if ($result_infos_userCO = $connexion->query("SELECT * FROM  comptes WHERE pseudo='" . $_POST['user'] . "'")) {
		$infos_userCO = $result_infos_userCO->fetch();
		//if($infos_userCO['mdp1'] == md5($_POST['pass']))
		if ($infos_userCO['mdp1'] == $_POST['pass']) {
			$tokenCO = rand(100000, 999999);
			if ($connexion->query("UPDATE comptes SET token='" . $tokenCO . "' WHERE pseudo='" . $_POST['user'] . "'")) {
				$_SESSION['user'] = $_POST['user'];
				$_SESSION['token'] = $tokenCO;
				header('Refresh:1; url=index.php');
				echo 'Vous êtes connecté en tant que: <b>' . $_SESSION['user'] . '</b>';
			} else echo 'Erreur avec la BDD! 0x02';
		} else echo 'L\'utilisateur ou mot de passe incorrect!<br/><br/>-> <a href="connexion.php">On réésaye?</a>';
	} else echo 'Erreur avec la BDD! 0x01';
} else {
?>
	<h2>Connexion</h2>
	<form method="post">
		<div class="mb-3">
			<label for="username" class="form-label">Utilisateur :</label>
			<input type="text" name="user" class="form-control" id="username">
		</div>
		<div class="mb-3">
			<label for="password" class="form-label">Mot de passe :</label>
			<input type="password" name="pass" class="form-control" id="password">
		</div>
		<input type="submit" value="Se connecter" class="btn btn-primary">
	</form>
<?php
}
include('foot.php'); ?>