<?php

include ('includes/header.html');

# This piece of javascript will default the cursor to the Edit input box.
echo "<script type=\"text/javascript\">
window.onload=function(){document.forms['edit'].elements['email'].focus();}
</script>";

# Only execute this block of code if the page ID is a number, then store it as a variable.
if (is_numeric($_GET['id'])) {
    $id = $_GET['id'];

    # Execute this block of code if the logged in user is viewing their own profile.
    if ($_SESSION['user'] == $id) {

        # This query is just to retrieve some pieces of information for public viewing.
        $q = "SELECT username, email, date FROM users WHERE user_id='$id'";
        $r = mysqli_query($dbc, $q);
        $userinfo = mysqli_fetch_array($r);

        # Echo a nav bar at the top.
        echo "<div id=\"nav\"><p><a href=\"/myboard/\">Index</a> > <a 
		href=\"user.php?id=$id\">" .
            ucwords($userinfo['username']) . " 's Profile</a></p></div>";

        # Echo a profile with an edit box so the user can change their information.
        echo "	
	<div id=\"title\">
	<h2>" . ucwords($userinfo['username']) . "</h2>
	</div>
	<div id=\"box\">
	<p>Registered Since:" . formatdate(null, $userinfo['date']) . "</p>
	<form action=\"edit.php?id=$id\" method=\"post\" name=\"edit\"> 
	<p>Email Address: <input type=\"text\" name =\"email\" length=\"8\" 
	maxlength=\"50\" value=\"{$userinfo['email']}\"/></p>
	<p><input type=\"submit\" name=\"submit\" value=\"Submit\"/></p>
	</div>
	";
	
	# Update the user's email address once they click Submit.
	if ($_POST['submit']) {
		$q2 = "UPDATE users SET email='{$_POST['email']}' WHERE user_id='$id'";
		if (mysqli_query($dbc, $q2)) {
			# Take the user back to their public profile.
			header("Location:user.php?id=$id");
		} else {
			echo "<p>There was a problem updating your details.</p>";
		}
	}
        # Take the user to the View User page if the ID is anything other than their own.
    } else {
        header("Location:user.php?id=$id");
    }

    # Echo an error if the page ID is not a number.
} else {
    echo "<p>User does not exist!</p>";
}

include ('includes/footer.html');

?>