<?php

include ('includes/header.html');

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

# Only let the user post if their user session is set and their HTTP_USER_AGENT matches
# the one which they signed in with.
if (isset($_SESSION['user']) && $_SESSION['agent'] == md5($_SERVER['HTTP_USER_AGENT'])) {
	
	# Only execute this block of code if the page ID matches the thread which the user replied to.
    if ($_GET['id'] == $_SESSION['thread']) {
    	$id = $_GET['id'];
    	
    	# A form for the user to post the reply.
        echo '
	<form action="reply.php?id=' . $id . '" method="post" name="post">
	<p>Message: <textarea name="message" cols="60" rows="10"></textarea></p>
	<p><input type="submit" name="submit" value="Post" /><input type="submit" name="cancel" value="Cancel" /></p>
	</form>
	';
		
		# Execute this block of code if the user presses the Post button.
        if ($_POST['submit']) {
			# Validate that a message has been entered.
            if (empty($_POST['message'])) {
                echo "Please enter a message.";
            } else {
            	# Message must be under 1000 characters.
            	if ((strlen($_POST['message']) < 10000)) {
            		$message = htmlentities($_POST['message']);
            	} else {
            		echo "Your message is too long! Please keep it under 1000 characters.";
            		exit();
            	}
                                
                $username = $_SESSION['user'];
				
				# Enter the row into the database using all the details provided so far.
                $q = "INSERT into posts (in_thread, post_content, post_date, post_author) VALUES ('$id', '$message', NOW(), '$username')";
				
				# If the row was inserted successfully, take the user to the thread they created.
                if ($r = mysqli_query($dbc, $q)) {
                    header("Location:thread.php?id=$id");
                    # Echo an error if the row was not inserted.
                } else {
                    echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
                }
            }
        }

    } else {
    	# Echo an error if there is an invalid page ID.
        echo "Please click \"Reply\" to reply to a thread.";
    }

	# Take the user back to the thread they were reading if they hit Cancel.
    if ($_POST['cancel']) {
        header("Location:thread.php?id=$id");
    }

# Return the user to the login screen if they are not logged in.
} else {
    unset($_SESSION['user']);
    unset($_SESSION['agent']);
    header("Location:login.php");
}

include ('includes/footer.html');

?>