<?php 

include "db.inc";

#######################################################################################
# This script splits the operation of a form down in to logical sections of code.
# 
# First part of the code deals with GET requests. As such, all HTML is contained 
# within this part.

# Second part deals with POST reqeusts and contains not HTML. Instead it ends with
# a simple redirect.
#
# Jake Howlett, http://wwww.codestore.net. October 2003.
#######################################################################################

if ( $_SERVER['REQUEST_METHOD']=='GET') {
	$categories=mysql_query("SELECT DISTINCT category FROM entries") or die ("SQL Query Failed!");
	
	if ( isset($_GET['id']) && is_int((int)$_GET['id']) && isset($_GET['edit']) ) { 
	//edit mode
		$entry=mysql_query("SELECT * FROM entries WHERE entry_id=".$_GET['id']) or die ("SQL Query Failed!");
		$row = mysql_fetch_array($entry);

		$categories_select = "<select name=\"categories\">\n<option> - Select - </option>\n";
		while ( $cat = mysql_fetch_array($categories) ) { 
			$categories_select .= "<option".(($row['category']==$cat['category'])?" selected":"").">".$cat['category']."</option>\n";
		}
		$categories_select .= "</select>\n";
		
		$form_elements = array(
			"FormTag"=>"<form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']."\" enctype=\"multipart/form-data\" name=\"entry\">",
			"Subject"=>"<input name=\"subject\" value=\"".stripslashes($row["subject"])."\" size=\"30\" />",
			"Category"=>$categories_select,
			"NewCategory"=>"<br />Or enter a new one:<br /><input name=\"newcategory\" value=\"\" size=\"30\" id=\"newcategory\">",
			"Body"=>"<textarea name=\"body\" rows=\"10\" cols=\"55\"\>".stripslashes($row['body'])."</textarea><br />",
			"DiaryDate"=>"<input name=\"diary_date\" value=\"".date("d/m/Y",strtotime($row['diary_date']))."\" size=\"14\" />",
			"CreatedDate"=>date("d/m H:i",strtotime($row['time_created'])),
			"ModifiedDate"=>(isset($row['time_modified']))?date("d/m H:i",strtotime($row['time_modified'])):null,
			"ButtonTags"=>"<input type=\"submit\" value=\"Save\" name=\"Submit\" />"
		);
		
	} elseif ( isset($_GET['id']) && is_int((int)$_GET['id']) ) { 
	//read mode
		$entry=mysql_query("SELECT * FROM entries WHERE entry_id=".$_GET['id']) or die ("SQL Query Failed!");
		$row = mysql_fetch_array($entry);
		
		$form_elements = array(
			"FormTag"=>"<form method=\"GET\" action=\"".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']."\" name=\"entry\">",
			"Subject"=>stripslashes($row["subject"]),
			"Category"=>$row['category'],
			"NewCategory"=>"",
			"Body"=>stripslashes($row['body']),
			"DiaryDate"=>date("d/m/Y",strtotime($row['diary_date'])),
			"CreatedDate"=>date("d/m H:i",strtotime($row['time_created'])),
			"ModifiedDate"=>(isset($row['time_modified']))?date("d/m H:i",strtotime($row['time_modified'])):null,
			"ButtonTags"=>"<input type=\"button\" value=\"Edit\" name=\"Submit\" onclick=\"location.href+='&edit=1';\"/>"
		);
	} else { 
	//new
		$categories_select = "<select name=\"categories\">\n<option> - Select - </option>";
		while ( $cat = mysql_fetch_array($categories) ) { 
			$categories_select .= "<option>".$cat['category']."</option>\n";
		}
		$categories_select .= "</select>\n";

		$form_elements = array(
			"FormTag"=>"<form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."\" enctype=\"multipart/form-data\" name=\"entry\">",
			"Subject"=>"<input name=\"subject\" value=\"\" size=\"30\" />",
			"Category"=>$categories_select,
			"NewCategory"=>"<br />Or enter a new one:<br /><input name=\"newcategory\" value=\"\" size=\"30\" id=\"newcategory\">",			
			"Body"=>"<textarea name=\"body\" rows=\"10\" cols=\"55\"\></textarea><br />",
			"DiaryDate"=>"<input name=\"diary_date\" value=\"\" size=\"14\" />",
			"CreatedDate"=>date("d/m H:i", time()),
			"ButtonTags"=>"<input type=\"submit\" value=\"Save\" name=\"Submit\" />"
		);
	}
?>

<html>
<head>
<title>A simple PHP form</title>
</head>
<body>

<h3>Journal Entry</h3>
<p>Created: 
<?= $form_elements["CreatedDate"]; ?>
<? if ( isset($form_elements["ModifiedDate"]) ) echo " (Modified: ".$form_elements["ModifiedDate"].")"; ?>
</p>

<?= $form_elements["FormTag"]; ?>

<table border="0" cellpadding="3" width="480">
<tr>
<td>Title:</td>
<td><?= $form_elements["Subject"]; ?></td>
</tr>

<tr>
<td>Category:</td>
<td><?= $form_elements["Category"]; ?>
<?= $form_elements["NewCategory"]; ?>
</td>
</tr>


<tr>
<td>Diary Date:</td>
<td><?= $form_elements["DiaryDate"]; ?></td>
</tr>

</table>

<br />
<?= $form_elements["Body"]; ?>
<br /><br />
<?= $form_elements["ButtonTags"]; ?>

</form>
</div>

</body>
</html>

<? //Deal with a FORM that was POSTed.
} elseif ( $_SERVER['REQUEST_METHOD']=='POST') {
	$category=( empty($_POST['newcategory']) ) ? $_POST['categories'] : strip_tags(addslashes($_POST['newcategory']));
	if ( isset($_GET['id']) && is_int((int)$_GET['id']) ){ 
	//Entry already has an ID so we just need to UPDATE the current values
		$query="UPDATE entries SET 
					subject='".addslashes(htmlspecialchars($_POST['subject']))."', 
					category='".$category."',
					body='".addslashes(strip_tags($_POST['body'],'<i><b>'))."',
					diary_date='".date("Y-m-d", strtotime($_POST['diary_date']))."',
					time_modified='".date("Y-m-d H:i:s",time())."'
				WHERE entry_id=".$_GET['id'].";";
		mysql_query($query);
		$returnid = $_GET['id'];
		
	} else { 
	//No ID for the entry so we need to INSERT a new one!
		$query="INSERT INTO entries VALUES( 
					null, 
					'".addslashes(htmlspecialchars($_POST['subject']))."', 
					'".addslashes(strip_tags($_POST['body'],'<b><i>'))."',
					'".$category."',
					'".date("Y-m-d", strtotime($_POST['diary_date']))."',
					'".date("Y-m-d H:i:s",time())."',
					null)";
		mysql_query($query);
		$returnid=mysql_insert_id($connection); //ID of the new entry!
	}
	//Send the user back to the view. Equivalent to a $$Return field!
	Header("Location:".$_SERVER['PHP_SELF']."?id=".$returnid);

} else {
	die("Your request method is not supported by this page!");
}
?>