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

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $connection->prepare('SELECT id, password  FROM admin WHERE username =?')) {
	// 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['username']);
	$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);
	$stmt->fetch();
	if ($_POST['password'] == $password)
	{
	
	// 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['username'] = $_POST['username'];
		$_SESSION['id'] = $id;

		header('location:../home.php');

	


	}
else
{
	$_SESSION['status'] = "<h4 style='padding:15px; background: #fe8b8e;'>Incorrect username or password!</h4>";
	header('location:../index.php');
}	
} 
else {
	// Incorrect username
	$_SESSION['status'] =  "<h4 style='padding:15px; background: #fe8b8e;'>Incorrect username or password!</h4>";
	header('location:../index.php');
}
 $stmt->close();
?>