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

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

// first and last category IDs
$q = mysqli_query($connection,"SELECT * FROM `cats` ORDER BY catOrder ASC LIMIT 1");
$firstCat = mysqli_fetch_array($q);
$q = mysqli_query($connection,"SELECT * FROM `cats` ORDER BY catOrder DESC LIMIT 1");
$lastCat = mysqli_fetch_array($q);

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

if ($id == "") {
 echo "<font color=red>No category ID found.</font>";
}
else if (!$q['id']) {
 echo "<font color=red>That category does not exist.</font>";
}
else {
 if ($q['id'] == $firstCat['id'] && $q['id'] == $lastCat['id']) {
  echo "<font color=red>This category cannot be moved.</font>";
 }
 else {
  $dir = @$_GET['dir'];
  if ($dir == "up") {
   if ($q['id'] == $firstCat['id']) {
    echo "<font color=red>This category cannot be moved <b>up</b>.</font>";
   }
   else {
    $q2 = mysqli_query($connection,"SELECT * FROM `cats` WHERE catOrder < {$q['catOrder']} ORDER BY catOrder DESC LIMIT 1");
    $catAbove = mysqli_fetch_array($q2);
    $q3 = mysqli_query($connection,"UPDATE `cats` SET catOrder='{$catAbove['catOrder']}' WHERE id='{$q['id']}'");
    $q4 = mysqli_query($connection,"UPDATE `cats` SET catOrder='{$q['catOrder']}' WHERE id='{$catAbove['id']}'");
    if ($q3 && $q4) {
     echo "<font color=red>The category <b>{$q['name']}</b> been moved up.</font>";
    }
    else {
     echo "<font color=red>Unable to move category. Please try again later.</font>";
    }
   }
  }
  else if ($dir == "down") {
   if ($q['id'] == $lastCat['id']) {
    echo "<font color=red>This category cannot be moved <b>down</b>.</font>";
   }
   else {
    $q2 = mysqli_query($connection,"SELECT * FROM `cats` WHERE catOrder > {$q['catOrder']} ORDER BY catOrder ASC LIMIT 1");
    $catBelow = mysqli_fetch_array($q2);
    $q3 = mysqli_query($connection,"UPDATE `cats` SET catOrder='{$catBelow['catOrder']}' WHERE id='{$q['id']}'");
    $q4 = mysqli_query($connection,"UPDATE `cats` SET catOrder='{$q['catOrder']}' WHERE id='{$catBelow['id']}'");
    if ($q3 && $q4) {
     echo "<font color=red>The category <b>{$q['name']}</b> been moved down.</font>";
    }
    else {
     echo "<font color=red>Unable to move category. Please try again later.</font>";
    }
   }
  }
 }
}

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