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

$maxPerPage = $pageInfo['maxPerPage'];
$p = @$_GET['p'] ? $_GET['p'] : 1;
$offset = ($p * $maxPerPage) - $maxPerPage;

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

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

$locked = $q['locked'];

if (!$q)
    {
        header("Location: index.php");
        exit;
    }

$pageInfo['title'] = "View Forum: ".$q['name'];

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

fetchTemplate("header");

$cid = $id;

$oldquery = mysqli_query($connection,"SELECT * FROM `threads` WHERE inForum='$cid' AND sticky='0'");
$oldcount = mysqli_num_rows($oldquery);

fetchTemplate("viewforum");

$query = mysqli_query($connection,"SELECT * FROM `threads` WHERE inForum='$cid' AND sticky='1' ORDER BY id DESC");
$count = mysqli_num_rows($query);
if ($count > 0) {
 while ($q = mysqli_fetch_array($query)) {
  $id1 = $q['id'];
  $q2 = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='$id1'");
  $replys = mysqli_num_rows($q2) - 1;
  $lr = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='$id1' ORDER BY id DESC");
  $lr = mysqli_fetch_array($lr);
  fetchTemplate("viewforumrow");
 }
}

$query = mysqli_query($connection,"SELECT * FROM `threads` WHERE inForum='$cid' AND sticky='0' ORDER BY id DESC LIMIT $offset,$maxPerPage");
$count = $oldcount;
while ($q = mysqli_fetch_array($query)) {
 $id2 = $q['id'];
 $q2 = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='$id2'");
 $replys = mysqli_num_rows($q2) - 1;
 $lr = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='$id2' ORDER BY id DESC");
 $lr = mysqli_fetch_array($lr);
 fetchTemplate("viewforumrow");
}
if ($count == 0) {
?>
 <tr>
  <td align="center" colspan="7" class="alt7">
   <b>This forum does not have any non-sticky threads.</b>
  </td>
 </tr>
<?php
}

fetchTemplate("viewforumend");

fetchTemplate("footer");
?>