<?php
session_start();
include ('database.php');
if( mysqli_connect_errno() ) {
	// If there is an error with the connection, stop the script and display the error.
	exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if(!isset($_POST['email'], $_POST['code']) )
{
	// Could not get the data that should have been sent.
	exit('Please fill both the email  and code fields!');
	header('location:sign-in.php');
}

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $connection->prepare('SELECT id, code FROM users WHERE email =?')) {
	// 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['email']);
	$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, $code);
	$stmt->fetch();
	if ($_POST['code'] == $code)
	{
	// Account exists, now we verify the code.
	// Note: remember to use code_hash in your registration file to store the hashed codes.
	
		// 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['email'] = $_POST['email'];
		$_SESSION['id'] = $id;
		echo 'Welcome' .$_SESSION['name'] . '!';
		header('location:../home.php');

	


	}
else
{
	$_SESSION['status'] = "<h5 style='padding:8px; background: #fe8b8e; border-radius: 10px; color: #fff; text-align: center;'>Wrong code!</h5>";
	header('location:../login.php');
}	
} 
else {
	// Incorrect username
	$_SESSION['status'] =  "<h5 style='padding:8px; background: #fe8b8e; border-radius: 10px; color: #fff; text-align: center;'>Incorrect username or code!</h5>";
	header('location:../login.php');
}
 $stmt->close();
?>