<?php define( '_BIGNIGHT_EXEC', 1 );?>
<?php session_start();?>

<?php require_once("helper.php"); ?>
<?php require_once("user.php"); ?>


<?php

	if(empty($_GET["id"])) die("No event specified.");
	$id = intval($_GET["id"]);
	if($user===NULL) die("Log in to use comments.");
	
	global $DB;
	$event = $DB->qry("SELECT a.event_id AS attending FROM events e LEFT JOIN (SELECT * FROM attending WHERE username='{$user["username"]}') a ON e.id=a.event_id WHERE id={$id};");
	if ($DB->numrows()===0){
		die("Invalid event id");
	}
	
	$email = false;
	if(isset($_GET["delete"])){		// delete comment
		$delete = intval($_GET["delete"]);
		$username = $DB->qry("SELECT username FROM comments WHERE id={$delete};",3);
		if ($DB->numrows()===0){
			die("Invalid comment id");
		}
		if($username==$user["username"]){
			$DB->qry("DELETE FROM comments WHERE id={$delete};");
		} else {
			die("You do not own this comment.");
		}
	} else {	// new comment
		if(empty($_GET["comment"])) die("Empty comment.");
		$comment = str_replace("'","''",$_GET["comment"]);
		$time = $DB->qry("SELECT time FROM comments WHERE username='{$user["username"]}' ORDER BY time DESC LIMIT 1;",3);
		if(time()-$time<60) die("Please wait 1 minute to post next comment.");
		else if(strlen($comment)>255) die("Comment too large.");
		else {
			$DB->qry("INSERT INTO comments (`username`,`event_id`,`comment`,`time`) VALUES ('{$user["username"]}',{$id},'{$comment}'," . time() . ")");
			$comment_id = $DB->qry("SELECT LAST_INSERT_ID();",3);
			if($DB->numrows()===0) die("Error posting comment.");
			else $email=true;
		}
	}
	
	echo "|";
	display_comments($id);
	
	if($email) email_comment_subs($comment_id);
	
?>