<?php
include("includes/global.php");

global $userInfo;

$id = @$_GET['id'];
$do = @$_GET['do'];
if (!$id) header("Location: index.php");

if (!$userInfo['loggedin']) {
 header("Location: login.php?redir=newthread.php?id=".$id);
exit;
}

$query = mysqli_query($connection,"SELECT * FROM `forums` WHERE id='$id'");
$q = mysqli_fetch_array($query);

if (!$q || $q['locked'] && $userInfo['title'] != "Administrator") header("Location: index.php");

$pageInfo['title'] = "New Thread";
$pageInfo['homelink'] .= " -> <a href=\"viewforum.php?id=".$q['id']."\">".$q['name']."</a>";
$pageInfo['homelink'] .= " -> <a href=\"newthread.php?id=".$id."\">New Thread</a>";

if ($do == "") {
 fetchTemplate("header");
 $action = "newthread.php?id={$id}&do=post";
 fetchTemplate("postform");
 fetchTemplate("footer");
}
else if ($do == "post") {
 $title = @$_POST['title'];
 $post = @$_POST['post'];
 if ($title && $post) {
  $date = time();
  $query = mysqli_query($connection,"INSERT INTO `threads` VALUES ('','$title','{$userInfo['id']}','$date','0','$id','0')");
  if ($query) {
   $title = htmlspecialchars($title);
   $post = htmlspecialchars($post);
   $title = stripslashes($title);
   $post = stripslashes($post);
   $title = format_chars($title);
   $post = format_chars($post);
   $threadID = mysqli_insert_id($connection);
   $query = mysqli_query($connection,"INSERT INTO `posts` VALUES ('','$title','{$userInfo['id']}','$date','$id','$threadID','$post')");
   if ($query) {
    $posts = $userInfo['posts'] + 1;
    mysqli_query($connection,"UPDATE `users` SET posts='$posts' WHERE id='".$userInfo['id']."'");
    $query = mysqli_query($connection,"SELECT * FROM `forums` WHERE id='$id'");
    $q = mysqli_fetch_array($query);
    $threads = $q['threads'] + 1;
    $posts = $q['posts'] + 1;
    mysqli_query($connection,"UPDATE `forums` SET threads='$threads', posts='$posts' WHERE id='$id'");
    header("Location: viewthread.php?id=".$threadID);
   }
   else {
    fetchTemplate("header");
?>
<p align=center><font color=red><b>Error:</b> Unable to create new thread. Please try again later.</font></p>
<?php
    fetchTemplate("footer");
   }
  }
  else {
?>
<p align=center><font color=red><b>Error:</b> Unable to create new thread. Please try again later.<br /></font></p>

<form method="post" action="newthread.php?id=<?php echo $id; ?>">
 <input type="hidden" name="title" value="<?php echo $title; ?>">
 <input type="hidden" name="post" value="<?php echo $post; ?>">
 <p align=center><input type="submit" value="Back"></p>
</form>
<?php
  }
 }
 else {
  fetchTemplate("header");
?>
<p align=center><font color=red>Please fill in all of the fields.<br /></font></p>

<form method="post" action="newthread.php?id=<?php echo $id; ?>">
 <input type="hidden" name="title" value="<?php echo $title; ?>">
 <input type="hidden" name="post" value="<?php echo $post; ?>">
 <p align=center><input type="submit" value="Back"></p>
</form>
<?php
  fetchTemplate("footer");
 }
}
?>