<?php
include("_confirm.php");

$id = @$_GET['id'];
$dir = @$_GET['dir'];

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

if ($id == "") {
 echo "<font color=red>No forum ID found.</font>";
}
else if ($dir == "") {
 echo "<font color=red>No move direction found.</font>";
}
else if (!$q['id']) {
 echo "<font color=red>That forum does not exist.</font>";
}
else {
 $q2 = mysqli_query($connection,"SELECT * FROM `forums` WHERE inCat='{$q['inCat']}' ORDER BY forumOrder ASC LIMIT 1");
 $firstForum = mysqli_fetch_array($q2);
 $q2 = mysqli_query($connection,"SELECT * FROM `forums` WHERE inCat='{$q['inCat']}' ORDER BY forumOrder DESC LIMIT 1");
 $lastForum = mysqli_fetch_array($q2);
 $canMove = true;
 if ($q['id'] == $firstForum['id'] && $q['id'] == $lastForum['id']) {
  $canMove = false;
  echo "<font color=red>This forum cannot be moved.</font>";
 }
 else if ($q['id'] == $firstForum['id']) {
  if ($dir == "up") {
   $canMove = false;
   echo "<font color=red>This forum cannot be moved up.</font>";
  }
 }
 else if ($q['id'] == $lastForum['id']) {
  if ($dir == "down") {
   $canMove = false;
   echo "<font color=red>This forum cannot be moved down.</font>";
  }
 }
 if ($canMove) {
  if ($dir == "up") {
   $forumOrder = $q['forumOrder'];
   $forumOrderUp = $q['forumOrder'] - 1;
   $q = mysqli_query($connection,"SELECT * FROM `forums` WHERE forumOrder='$forumOrderUp' LIMIT 1");
   $q = mysqli_fetch_array($q);
   $q2 = mysqli_query($connection,"UPDATE `forums` SET forumOrder='$forumOrderUp' WHERE id='{$id}'");
   $q3 = mysqli_query($connection,"UPDATE `forums` SET forumOrder='$forumOrder' WHERE id='{$q['id']}'");
   if ($q2 && $q3) {
    echo "<font color=red>The forum <b>{$q['name']}</b> has been moved up.</font>";
   }
   else {
    echo "<font color=red>Unable to move forum <b>{$q['name']}</b> up. Please try again later.</font>";
   }
  }
  else if ($dir == "down") {
   $forumOrder = $q['forumOrder'];
   $forumOrderDown = $q['forumOrder'] + 1;
   $q = mysqli_query($connection,"SELECT * FROM `forums` WHERE forumOrder='$forumOrderDown' LIMIT 1");
   $q = mysqli_fetch_array($q);
   $q2 = mysqli_query($connection,"UPDATE `forums` SET forumOrder='$forumOrderDown' WHERE id='{$id}'");
   $q3 = mysqli_query($connection,"UPDATE `forums` SET forumOrder='$forumOrder' WHERE id='{$q['id']}'");
   if ($q2 && $q3) {
    echo "<font color=red>The forum <b>{$q['name']}</b> has been moved down.</font>";
   }
   else {
    echo "<font color=red>Unable to move forum <b>{$q['name']}</b> down. Please try again later.</font>";
   }
  }
 }
}

echo "<br /><br />\n<a href=\"?do=frmmg\">[ Back ]</a>\n";
?>