<?php
include("resources/dbconnect.php");

function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

ob_start();

// Connect to server and select database.
$mysqli = dbconnect();

// Define variables
$myusername = $mypassword = $error = "";
$posted = False;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $myusername=clean_input($_POST['myusername']);
  $mypassword=clean_input($_POST['mypassword']);
  $posted = True;
}

$qry = "SELECT password, id, administrator FROM users WHERE username=?";

if (!($stmt = $mysqli->prepare($qry))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$stmt->bind_param("s", $myusername);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($pw, $id, $admin);
$stmt->fetch();
$count = $stmt->num_rows;
$stmt->close();

if($count == 1 && $pw == crypt($mypassword, $pw)) {
  // Register $myusername and redirect to file "evaluate.php"
  session_start();
  $_SESSION['user'] = $myusername;
  $_SESSION['uid'] = $id;
  $_SESSION['admin'] = $admin;
  header("location:evaluate.php");
}
else {
  $error = "Username/Password Error";
}

ob_end_flush();

?>

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="loginform" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>User Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername" value="<?php echo $myusername ?>"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" id="mypassword"></td>
</tr>
<?php
  if($error != "" && $posted) {
    echo "<tr><td style ='color:red; text-align:center' colspan=3> $error </td></tr>";
  }
?>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
<tr>
<td colspan=3>Not registered yet? <a href="register.php">Create an account</a></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
