<?php
session_start();
if(isset($_SESSION['autheticate']))
{
	$identification = $_SESSION['identification'];
	$admin = $_SESSION['admin'];
}
//echo $identification. " Is authecate user <br>" ;
if($admin == 1)
{
	//echo " User is administrator <br>";
}
//echo "Personal Blog of Sunil Panthi <br>";
require_once("mysql_login.php");
/////////////////////////////////////////////////////////////////////
// this is for multiple page
$rowPerPage = 2;
$pageNum = 1; 
// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
}
$offset = ($pageNum - 1) * $rowPerPage;
$read_post = "SELECT * FROM `post` ORDER BY `date_created` DESC LIMIT $offset, $rowPerPage";
//$query_num = "SELECT COUNT(*) AS NUMEROUS FROM `post`";
//$query_num_result = mysql_query($query_num) or die ("Error on ". mysql_error());
//echo "<b> ".  $query_num_result . " </b> " . "Number of columbs on post <br>";
//$row = mysql_fetch_array($query_num_result);
//$numrows = $row['numrows'];
//echo $numrows. "Is a Number<br>". $row[0];
// how many rows we have in database
$query   = "SELECT COUNT(*) AS numrows FROM post";
$result  = mysql_query($query) or die('Error, query failed');
$row     = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
//echo $numrows . " : Number of rows <br>";
//Number of pages
$PageMax = ceil($numrows/$rowPerPage);
//echo "Max Page <b> " . $PageMax . "</b><br>";
//Print the link for accessing page
$self = $_SERVER['PHP_SELF']; // this is for navigation between pages
$nav = '';

	for($page = 1; $page <= $PageMax; $page++)
		{
			if($pageNum == $page)
			{
			$nav = $nav. " $page";
			} else
			{
			$nav = $nav."<a href = \"$self?page=$page\">$page ||</a>";
			}
		}
			if($pageNum > 1)
			{
				$page = $pageNum - 1;
				$prev = "<a href = \"$self?page=$page\">[prev]</a>";
				$first = "<a href = \"$self?page=1\"><< </a>";
			
			} else
			{
				$prev = "";
				$first = "";
			}
			if($pageNum < $PageMax)
			{
				$page = $pageNum + 1;
				$next = "<a href = \"$self?page=$page\">[next]</a>";
				$last = "<a href = \"$self?page=$PageMax\"> >> </a>";
			} else 
			{
				$next = "";
				$last = "";
			}
/////////////////////////////////////////////////////////////////////
//$read_post = "SELECT * FROM `post` ORDER BY `date_created` DESC";
$read_post_query = mysql_query($read_post);
if(!$read_post_query)
{
	echo "Error on reading database " . "<b> " . mysql_error(). " </b>" ;
}
while($result_row = mysql_fetch_array($read_post_query))
{
//echo $result_row['postid'] . "<br>";
echo "<br><img src = images/horizental.jpg width = 795 height = 10>";
echo "<br><b>". $result_row['title']. "</b>". "<br> <br>";
echo "<b> Blog Category : " . $result_row['category']. "</b><br><br>";
echo $result_row['post']. "<br>";
	if($result_row['attachment'] != NULL)
	{
	$attached_file = $result_row['attachment'];
	//echo "File name $attached_file <br>";
	echo "<a href=file_upload/$attached_file> Attached File</a><br>";
	//echo "<br><a href = file_upload/$attached_file> Attachment</a>";
	}
echo " <img src = images/time.jpg width = 16 height = 16>  ". $result_row['date_created']. "  ||  ";
//echo " User Id " . $result_row['identification']. "<br>";
				$read_user_query = "SELECT * FROM user where identification = $result_row[identification]";
				$read_user_result = mysql_query($read_user_query);
				while($result_user = mysql_fetch_array($read_user_result))
				{
					echo "  <img src = images/user.jpg width = 16 height = 18>    " . $result_user['username'] . "   ||  ";
				//if same user logs in have user to edit, delete, post new comment
					if($identification == $result_row['identification'])
					{
							echo " || <a href = $authen_change?which=$result_row[postid]&what=edit&page=$pageNum#myanchor_edit_post>  Edit ||</a> ";
							echo " <a href = $authen_change?which=$result_row[postid]&what=delete&page=$pageNum> Delete ||</a> ";
							echo " <a href = frame_post.php>New Post ||</a>";
					}
					// user use is administrator give him/her access to delete the conent if not appropriate
					// $admin == 0, for retular user and $admin == 1 for administrator
					if($admin == 1)
					{
						   echo " <a href = $authen_change?which=$result_row[postid]&what=delete&page=$pageNum>Admin Delete || </a> ";
					}
					if(isset($identification))
					{
						echo " <a href = $authen_change?which=$result_row[postid]&what=add_comment&page=$pageNum&#myanchor_add_comment><img src = images/comment.jpg width = 20 height = 12> Add Comment</a>";
					}
				}
				// If comment is submiteed for this Post display it. 
				//echo "<br><img src = images/horizental.jpg width = 795 height = 10>";
				$num_row = $result_row['postid'];
				$read_comment = "SELECT * FROM comment where postid = $result_row[postid] ORDER BY `date_created` DESC";
				$read_comment_result = mysql_query($read_comment);
				while($result_comment_row = mysql_fetch_array($read_comment_result))
				{
					echo "<br><b>>>>>>>>>>...................Comments.....................<<<<<<<<<<<<</b>";
					//echo " <br> <div aligh = center><b> .............................................</b></div>";
					//echo " <br>  <div align = center>.........................................</div>";
					//echo "<br> Comment ID:  ". $result_comment_row['commentid']; 
					echo "<b><br>" . $result_comment_row['subject'] . "</b> <br>"; 
					echo "<br> Comment : " . $result_comment_row['body'] . "<br> " ;
					//echo "<br> Owner : ". $result_comment_row['identification']; 
					//echo "<br> Post Id: " . $result_comment_row['postid'];
					//Find the authenticated user who can edit comment
					$authen_user_comment = "SELECT * FROM user where identification = $result_comment_row[identification]"; 
					echo "<br> <img src = images/time.jpg> " . $result_comment_row['date_created'] . " || " ;
					$authen_user_comment_result = mysql_query($authen_user_comment);
					//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
					//echo "User name : ".$authen_user_comment['username'];
					while($result_user_comment = mysql_fetch_array($authen_user_comment_result))
					{
						echo " <img src = images/user.jpg width = 16 height = 18>  ". $result_user_comment['username'] . " || " ;
						//echo "<br> Do Stuff"; 
						if($identification == $result_comment_row['identification'])
						{
							//echo "<br> Here you go authenticated user " ; 
							echo "<a href = $authen_change?which=$result_comment_row[commentid]&what=edit_comm&page=$pageNum#anchor_edit_comment>Edit </a> || ";
							echo "<a href = $authen_change?which=$result_comment_row[commentid]&what=delete_comm&page=$pageNum> Delete</a> || ";
						}
						// if user is administrator allow him to delete the comment 
						if($admin == 1)
						{
							echo " <a href = $authen_change?which=$result_comment_row[commentid]&what=delete_comm&page=$pageNum>Admin Delete</a> || ";
						}
					}
				}
				echo "<br><img src = images/horizental.jpg width = 795 height = 10>";

	//echo "<hr>";
}
///////////////////////////////////////////////////////////////////////
// Delete comment if user is authenticated or administrator
if($_GET['what'] == delete_comm)
{
	include("javapopups.htm");
	echo "<br> Delete the comment " ; 
	echo "Row number " ;
	echo $row_num = $_GET['which'];
	echo $row_num .  "<br>is row number ";
	$delete_comment = "DELETE FROM comment where commentid = $row_num";
	$delete_comment_query = mysql_query($delete_comment);
	if(!delete_comment_query)
	{	
		echo "Error on deleting ".mysql_error();
	} else
	{
		echo "Comment deleted! "; 
		echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$pageNum\">";
	}
}
//////////////////////////////////////////////////////////////////////
// Edit the comment if user is authenticated 
if(($_GET['what']==edit_comm)&&(!isset($_POST['edit_comment'])))
{
$comment_row_num = $_GET['which']; 
echo $comment_row_num . "<b> Is Row number that need to be deleted </b> " ;
$comment_row = "SELECT * FROM `comment` where commentid = $comment_row_num";
$comment_row_result = mysql_query($comment_row);
	if(!$comment_row_result)
	{
		echo "Error on quering comment " . mysql_error() . "<br> " ;
	}
	else
	{
		while($row_comment = mysql_fetch_array($comment_row_result))
		{
			//echo $row_comment['subject'] . " Is Subject " ;
			echo "<a name=anchor_edit_comment></a>";
			echo "<form action=\"$PHP_SELF\" method=\"POST\">";
			echo "Subject:<input type = text name = editsubject value = $row_comment[subject]><br> <br>";
			echo "Comment:<br><textarea name = editcommentbody cols = 30 rows = 10>$row_comment[body]</textarea><br><br>";
			echo "<input type = submit name = edit_comment value = Edit >";
			echo "</form>";
			
		}
	}
}
// Get value from edit form and dump in mysql
if(isset($_POST['edit_comment']))
{ 
	echo "<br> Is it in Subroutine<br>";
	echo $subject =  mysql_real_escape_string($_POST[editsubject]);
	echo $body = mysql_real_escape_string($_POST[editcommentbody]);
	echo $commentid = $_GET[which];
	echo "<br>" . $subject . "<br> " . $body. "<br> " . $commentid ; 
	$dump_edit_comment = "UPDATE comment SET subject = '$subject', body = '$body' where commentid = '$commentid'";
	$edit_comment_query = mysql_query($dump_edit_comment);
		if(!$edit_comment_query)
		{
			echo "Error on updating comment " . mysql_error();
		}
		else
		{
			echo " updated successfully! " ;
			echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$pageNum\">";
		}
}
/////////////////////////////////////////////////////////////
// Add new comment if user is authenticated 
if(($_GET['what']==add_comment))
{
		// This function can be called once to create a table 
	if(isset($_POST['submit_comment']))
	{
		function create_table_comment()
		{
			$create_table_comment = 'CREATE TABLE `comment`(`commentid` int(6) auto_increment NOT NULL, 
														`subject` varchar(200) NOT NULL, 
														`body` longtext NOT NULL, 
														`identification` int NOT NULL, 
														`postid` int NOT NULL,
														`date_created` timestamp NOT NULL, 
														 PRIMARY KEY(`commentid`))';
			$create_table_result = mysql_query($create_table_comment);
				if(!$create_table_result)
				{
					echo "Error on creating table ". mysql_query();
				}
				else
				{
					echo "Table created successfully";
				}												
		}
		function dump_comment_mysql()
		{
			$page_num = $_GET['page']; // Get the current page number
			$identification = $_SESSION['identification']; // Authenticated user
			$post_id = $_GET['which']; // Row number of the post 
			$subject = stripslashes($_POST['subject']);
			$subject = mysql_real_escape_string($subject);
			$body = stripslashes($_POST['commentbody']);
			$body = mysql_real_escape_string($body);
			//$identification = 2;
			//$post_id = 3;
			//$dump_comment_mysql = "INSERT INTO `comment` VALUES('$commentid', '$subject', '$body', '$identification', '$postid', '$date_created')";
			$dump_comment_mysql = "INSERT INTO `comment` VALUES('$commentid', '$subject', '$body', '$identification', '$post_id', now())";
			$dump_comment_result = mysql_query($dump_comment_mysql);
				if(!$dump_comment_result)
				{
				echo "Error on quering comment" . mysql_error();
				}
				 else
				{
				echo "Comment submitted successfully";
				echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$page_num\">";
				}
				
		}
		// Function call to dump new comment on 
		//create_table_comment();
		dump_comment_mysql();
	} else
	{
		echo " Subroutine for adding comment "; 
		echo "<a name=myanchor_add_comment></a>"; // Link Anchor
		echo "<form action=\"$PHP_SELF\" method=\"POST\">";
		echo "Subject: <input type = text name = subject> <br><br>";
		echo "Comment:<br> <textarea name = commentbody cols = 30 rows = 10></textarea><br><br>";
		echo "<input type = submit name = submit_comment value = Submit Comment>";
		//echo "<input name=submit type=submit value=Create Account>";
		echo "</form>";
		// User Id 
		echo "<br> User Id is: " . $identification;
		echo "<br> Post Id is : " . $_GET['which']; 
	}
		
}
//////////////////////////////////////////
// If Authenticated allow new Posting
if(isset($_SESSION['autheticate']))
{
	echo "<br><a href = frame_post.php>New Post</a>";
}
else
{
	//echo " Not Authenticated to make a change, Login required ";
}
echo "<br>$first$nav$last" ;// . $first. $prev. $nav. $next. $last;
$authen_change = $_SERVER['PHP_SELF']; // if user is authenticated allowed to change
///////////////////////////////////////////////////////////////////////////
// Edit post
if(($_GET['what']==edit)&&(!isset($_POST['submit'])))
{
$edit_row_num = $_GET['which'];
echo " <br> Edit the row $edit_row_num ";
$edit_row_post = "SELECT * FROM `post` where postid = $edit_row_num";
$edit_row_post_result = mysql_query($edit_row_post);
		if(!$edit_row_post_result)
		{
			echo " Error on MySql " . mysql_error();
		}
		else
			{
				while($post_row = mysql_fetch_array($edit_row_post_result))
				{
					echo " <br> " . $post_row['title'] . "  is the title of the blog " ;
					//echo "<br> " . $post_row['post'];
					echo "<a name=myanchor_edit_post></a>"; // Anchored Edit Post
					echo "<form action=\"$PHP_SELF\" method=\"POST\">";
					echo "<input type = text name = title value = $post_row[title]> <br>";
					echo "<input type = text name = category value = $post_row[category]><br>";
					echo "<textarea name = body cols = 40 rows = 10> $post_row[post] </textarea><br>"; 
					echo "<input name=submit type=submit value=Edit>";
					echo "</form>";
				}
			}		

}
////////////////////////////////////////////////////////////////////////////////////
// Post Edit on post
if(isset($_POST['submit']))
{
 $page_num = $_GET['page'];
 echo "<br><h1> Do this if user want to eidt</h1> " ;
 echo " <br>Title: " . $_POST['title'];
 echo " <br>Category: " . $_POST['category'];
 echo "<br> Body:" . $_POST['body'];
 echo "<br> Identification:". $identification;
 echo "<br>Row Number: " . $_GET['which'];
 $row_num = ($_GET['which']);
 $title = mysql_real_escape_string($_POST['title']);
 $category = mysql_real_escape_string($_POST['category']);
 $body = mysql_real_escape_string($_POST['body']);
 $identification;
 
 // Dump everything into MySQL after change has been made
 	$edit_post = "UPDATE `post` SET title = '$title', category = '$category', 
								post = '$body', identification = '$identification', date_created = now() where postid = '$row_num'";
									
	$edit_post_result = mysql_query($edit_post);
	if(!$edit_post_result)
	{
		echo "<br> Error on while editing the post " . mysql_error();
	} else
	{
		echo "<br> Your post has been successfully edited " ;
		echo "<meta http-equiv = \"refresh\" content = \"1; URL=index.php?page=$pageNum\">";
	}
	
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// This is for delete POST
if($_GET['what']==delete)
{
$page_num = $_GET['page'];
$delete_row_num = $_GET['which'];
echo " <br> Delete subroutine <br>";
echo "Page Num : $page_num "; 
echo "<br> Row Num : $delete_row_num " ; 
$delete_post = "DELETE FROM `post` WHERE postid = '$delete_row_num'";
$delete_post_result = mysql_query($delete_post);
	if(!$delete_post_result)
	{
		echo " Post can not be deleted " . mysql_error();
	}
	else
	{
		echo " Post deleted "; 
		echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$pageNum\">";
	}
}
?>