<?
	require_once("includes/config.php");
	
	// make sure the user is logged in
	if(!blog_isAuthenticated())
	{
		blog_redirect("index.php");
	}
	
	// get values from post and escape using mysql_real_escape_string to prevent SQL injection attacks
	$title = isset($_POST["title"]) ? mysql_real_escape_string(trim($_POST["title"])) : "";
	$categories = isset($_POST["categories"]) ? mysql_real_escape_string(trim($_POST["categories"])) : "";
	$content = isset($_POST["content"]) ? mysql_real_escape_string(trim($_POST["content"])) : "";
	
	// if the user provided both title and content, attempt to insert the blog post into the database
	if(!empty($title) and !empty($content))
	{
		// get the user from the session, we'll need their ID to insert into the posts table
		$user = $_SESSION[BLOG_USER];
		
		// start transaction
		$start_trans_result = mysql_query("START TRANSACTION");
		if($start_trans_result === FALSE)
		{
			exit( "Could not start transaction: " . mysql_error() );
		}
	
		// insert post into database
		$post_result = mysql_query("INSERT INTO posts (title, content, user_id) VALUES ('$title', '$content', '$user->id')");
		if($post_result === FALSE or mysql_affected_rows() != 1)
		{
			mysql_query("ROLLBACK");
			exit( "Could not insert post into database: " . mysql_error() );
		}
		
		// get the auto incremented post id generated by the database
		$postId = mysql_insert_id();

		// insert categories into database
		if(!empty($categories))
		{
			$tokens = explode(",", $categories);
			foreach($tokens as $token)
			{
				$category = trim($token);
				
				// check to see if the category already exists
				$category_exists_result = mysql_query("SELECT id FROM categories WHERE category = '$category'");
				if($category_exists_result === FALSE)
				{
					mysql_query("ROLLBACK");
					exit( "Could not check category exists in database: " . mysql_error() );
				}
				
				if(mysql_num_rows($category_exists_result) == 1)
				{
					// category exists, fetch the category id from the existing row
					$row = mysql_fetch_assoc($category_exists_result);
					$categoryId = $row["id"];
				}
				else
				{
					// category does not exists, insert the category in the categories table and fetch the auto incremented category id
					$category_insert_result = mysql_query("INSERT INTO categories (category) VALUES ('$category') ON DUPLICATE KEY UPDATE category=category");
					if($category_insert_result === FALSE or mysql_affected_rows() != 1)
					{
						mysql_query("ROLLBACK");
						exit( "Could not insert category into database: " . mysql_error() );
					}

					// get the auto incremented category id generated by the database
					$categoryId = mysql_insert_id();					
				}
								
				// insert post->category mapping into the posts2categories table
				$p2c_result = mysql_query("INSERT INTO posts2categories (post_id, category_id) VALUES ('$postId', '$categoryId')");
				if($p2c_result === FALSE or mysql_affected_rows() != 1)
				{
					mysql_query("ROLLBACK");
					exit( "Could not insert post2category into database: " . mysql_error() );
				}
			}
		}

		// no db errors, we can commit the transaction
		$commit_result = mysql_query("COMMIT");
		if($commit_result === FALSE)
		{
			mysql_query("ROLLBACK");
			exit( "Could not commit transaction: " . mysql_error() );
		}
		
		// success, redirect the user to the new post with message that it was added
		$feedback = new Feedback(Feedback::PostAdded);
		$feedback->addMessage("Thank you, your post has been added!");
		$_SESSION[BLOG_FEEDBACK] = $feedback;	
		blog_redirect(blog_createpostlink($postId));
	}
	
	// invalid form submission if we reached here AND the $_POST is not empty
	$invalid = !empty($_POST);
?>

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

	<div id="contentnav">
		<h6><a href="index.php">&#60; home</a></h6>
	</div>

	<div id="addpost">
		<h2>Add Post</h2>
		
		<? if($invalid) { ?>
		<div class="error">
			<p>Please enter the title, categories, and content of your post.</p>
		</div>
		<? } ?>
		
		<form id="addPostForm" action="<? echo $_SERVER["PHP_SELF"]; ?>" method="post">
			<p>To add a post, enter the title, categories, and content.</p>
			<p><input type="text" id="title" name="title" size="25" maxlength="255" value="<? echo $title; ?>" index="10" /> <label for="title">Title</label></p>
			<p><input type="text" id="categories" name="categories" size="25" maxlength="255" value="<? echo $categories; ?>" index="11"/> <label for="categories">Categories (optional, ex. blog,php)</label></p>
			<p><textarea name="content" cols="5" rows="20" index="12"><? echo $content; ?></textarea></p>
			<p><input type="submit" name="button" value="Submit Post" index="13"/></p>
		</form>
	</div>

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