<?php
session_start();
include_once("dbConnect.php");
if(version_compare('5.5.0', PHP_VERSION) >= 0) {
	include_once("includes/password.php");
}

// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['login_name'], $_POST['password']) ) {
	// Could not get the data that should have been sent.
	die ('<meta http-equiv="refresh" content="5;url=index.php"/>Please fill both the username and password field!');
}

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, lang, password, user_name, last_login FROM accounts WHERE disabled=0 AND login_name = ?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
	$stmt->bind_param('s', $_POST['login_name']);
	$stmt->execute();
	// Store the result so we can check if the account exists in the database.
	$stmt->store_result();
	
	if ($stmt->num_rows > 0) {
		$stmt->bind_result($id, $lang, $password, $user_name, $last_login);
		$stmt->fetch();
		// Account exists, now we verify the password.
		// Note: remember to use password_hash in your registration file to store the hashed passwords.
		if (password_verify($_POST['password'], $password)) {
			include_once("includes/system_user.php");
			// Verification success! User has loggedin!
			// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
			// session_regenerate_id();
			$_SESSION['loggedin'] = TRUE;
			$_SESSION['login_name'] = $_POST['login_name'];
			$_SESSION['user_name'] = $user_name;
			$_SESSION['lang'] = $lang;
			$_SESSION['id'] = $id;
			
			if($last_login == '0000-00-00 00:00:00') {
				$_SESSION['change_pwd'] = $_POST['password'];
			} else {
				$_SESSION['previous_login'] = $last_login;
				update_last_login($id);
			}
			
			header('Location: index.php');
		} else {
			echo '<meta http-equiv="refresh" content="5;url=index.php"/>';
			echo 'Incorrect password or wrong username!';
		}
	} else {
		echo '<meta http-equiv="refresh" content="5;url=index.php"/>';
		echo 'Incorrect username!';
	}
	$stmt->close();
}


?>