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

$pageInfo['title'] = "Search";

$query = @$_GET['query'];

if ($query) {
 $part = @$_GET['part'] ? @$_GET['part'] : "title";
 $order = @$_GET['order'] ? @$_GET['order'] : "date";
 $by = @$_GET['by'] ? @$_GET['by'] : "asc";
 $pageInfo['homelink'] .= " -> <a href=\"search.php?query={$query}\">Search</a>";
 $by = strtoupper($by);

 $pattern = "";
 $splitQuery = explode(" ", $query);
 $c = count($splitQuery);
 for ($i=0; $i<$c; $i++) {
  if ($i < $c-1) $b = " OR ";
  else $b = "";
  $g = $splitQuery[$i];
  $pattern .= "`{$part}` LIKE '%{$g}%'{$b}";
 }

 fetchTemplate("header");
 $q = mysqli_query($connection,"SELECT * FROM `posts` WHERE {$pattern} ORDER BY {$order} {$by}");
 $c = mysqli_num_rows($q);
 echo "<font color=red>Your search returned {$c} results.<br /></font><br>\n";
?>
<table cellspacing="0" cellpadding="0" class="forums" align="center">
 <tr>
  <th width="40%" class="alt5">Post Title</th>
  <th width="60%" class="alt5">Author</th>
 </tr>
<?php
 while ($row = mysqli_fetch_array($q)) {
  $count = 0;
  $mycount = 1;
  $q2 = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='{$row['inThread']}'");
  while ($row2 = mysqli_fetch_array($q2)) {
   $count++;
   if ($row2['id'] == $row['id']) $mycount = $count;
  }
  $maxPerPage = $pageInfo['maxPerPage'];
  $postPage = ceil($mycount / $maxPerPage);

  $poster = mysqli_query($connection,"SELECT * FROM `users` WHERE id='{$row['posterId']}'");
  $poster = mysqli_fetch_array($poster);

  fetchTemplate("searchResult");
 }
 if ($c == 0) {
?>
 <tr>
  <td align="center" colspan="2" class="alt7"><font color=red><b>No search results to be displayed.</b></font></td>
 </tr>
<?php
 }
?>
</table><br />
<?php
}
else {
 $pageInfo['homelink'] .= " -> <a href=\"search.php\">Search</a>";
 fetchTemplate("header");

 fetchTemplate("searchForm");
}

fetchTemplate("footer");
?>