<?php
session_start();

require('Account.php');

//Test variables
//$_POST['userid'] = "greg";
//$_POST['password'] = "123gmn12u";

if (isset($_POST['userid']) && isset($_POST['password']))
{
	// if the user has just tried to log in
	$userid = $_POST['userid'];
	$password = $_POST['password'];
	
	/* Read through accounts file and check if the username and password match an existing account */
	$fp = fopen("Accounts.txt", 'rb');
	if (!$fp) {
        echo "<b>Could not open/read Accounts.txt<p>";
		/*session_unset($_SESSION['valid_user']);*/
        exit;
    }
	
	while (!feof($fp)) {
        $temp = fgets($fp, 999);
        if (!$temp)
            break;
		
        $account = new Account();
        $account->fillFromJSON($temp);
		
		if ($userid == $account->username && password_verify($password, $account->passHash)){
			$_SESSION['valid_user'] = $userid;
			$_SESSION['meta_data'] = '';
			break;
		}
    }
	fclose($fp);
	
	
}
?>

<html>
<head>
	<meta charset= "utf-8">
	<meta name= "viewport" content= "width=device-width, initial-scale= 1.0">
	<link rel="stylesheet" href="session.css">
    <title>Login</title>
</head>

<body>
<div id="sessionContainer">

<center>
<h1>Home page</h1>
<?php 
  if (isset($_SESSION['valid_user']))
  {
    //echo 'You are logged in as: '.$_SESSION['valid_user'].' <br />';
    //echo '<a href="logout.php">Log out</a><br />';
	echo '<script>window.location.href = "../liveIndex.php"</script>';
  }
  else
  {
    if (isset($userid))
    {
      // if they've tried and failed to log in
      echo 'Could not log you in.<br />';
    }
    else 
    {
      // they have not tried to log in yet or have logged out
      echo 'You are not logged in.<br />';
    }
	
    // provide form to log in 
    echo '<form method="post" action="login.php">';
    echo '<table>';
    echo '<tr><td>Userid:</td>';
    echo '<td><input type="text" name="userid"></td></tr>';
	echo '<tr><td>Password:</td>';
    echo '<td><input type="password" name="password"></td></tr>';
	echo '<tr><td colspan="2" align="center">';
    echo '<input type="submit" value="Log in"></td></tr>';
    echo '</table></form>';
  }
?>

<br />
<a href="createAccount.php">Create an Account</a>
<br />
<a href="logout.php">Return</a>
</center>

</div>
</body>
</html>