<?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['password']) )
{
	// Could not get the data that should have been sent.
	exit('Please fill both the email  and password fields!');
	header('location:../../login.php');
}

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $connection->prepare('SELECT id, password, verified FROM users WHERE email =?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), in our case the email 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, $password, $verified);
	$stmt->fetch();
	if ($_POST['password'] == $password)
	{
	if($verified == "1"){
	// Account exists, now we verify the password.
	// Note: remember to use password_hash in your registration file to store the hashed passwords.
	
		// 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;
		header('location:../index.php');

	
}
else{
    $_SESSION['status'] = '<p class="alert alert-danger d-flex align-items-center" role="alert">
                               
                                Please Verify Your Account An email Was Sent To You!
                              
                            </p>';
		$_SESSION['email'] = $_POST['email'];
		header('location:../../verify.php');
}
	}
else
{
	$_SESSION['status'] = '<p class="alert alert-danger d-flex align-items-center" role="alert">
                                Incorrect Email or Password
                               </p>';
	header('location:../../login.php');
}	
} 
else {
	// Incorrect email
	$_SESSION['status'] = '<p class="alert alert-danger d-flex align-items-center" role="alert">
                                 Incorrect Email or Password
                              </p>';
	header('location:../../login.php');
}
 $stmt->close();
?>