<?
	require_once("includes/config.php");
	
	// get the values from the post (use strip_tags on username because it can be used to prefill the form later on)
	$username = isset($_POST["username"]) ? strip_tags(trim($_POST["username"])): "";
	$password = isset($_POST["password"]) ? trim($_POST["password"]): "";
	
	// if the user provided both username and password, attempt to authenticate
	if(!empty($username) and !empty($password))
	{			
		// build the authentication query
		$sql = sprintf("SELECT id, username, first_name, last_name FROM users WHERE username='%s' AND password='%s'",
										mysql_real_escape_string($username),
										mysql_real_escape_string($password));

		// execute the query
		$result = mysql_query($sql);
		if($result === FALSE)
		{
			exit( "Could not query database: " . mysql_error() );
		}
		
		// check that query returned a row (thereby determining if authentication was successfull)
		if(mysql_num_rows($result) == 1)
		{
			// remember that the user is logged in by storing the result as an object in the session
			$_SESSION[BLOG_USER] = mysql_fetch_object($result);
			
			// use a cookie to remember the username between logins (for 1 week)
			setcookie("BlogUserCookie", $username, strtotime("+1 week"));

			// redirect the index
			blog_redirect("index.php");
		}
	}
	
	// credentials are invalid if we reached here AND the $_POST array contains elements (i.e. is not empty)
	$invalidCredentials = !empty($_POST);
?>

<? require_once("templates/begin.php"); ?>

	<div id="login">
		<h2>Sign In</h2>
		
		<? if($invalidCredentials) { ?>
		<div class="error">
			<p>Invalid credentials</p>
		</div>
		<? } ?>
		
		<form id="loginForm" action="<? echo $_SERVER["PHP_SELF"]; ?>" method="post">
			<p>Please provide your username and password to sign in to the blog.</p>
			<p><label for="username">Username</label> <input type="text" id="username" name="username" value="<? echo $username ? $username : $_COOKIE["BlogUserCookie"]; ?>" index="1" /></p>
			<p><label for="password">Password</label> <input type="password" id="password" name="password" index="2"/></p>
			<p><input type="submit" name="button" value="Sign In" index="3"/></p>
		</form>
	</div>

<? require_once("templates/end.php"); ?>
