<?php

  /*

      levels.php

      Level Admin. Allows the user to administer the list of levels
      for this domain an put them in order. The order given is that of the
      life cycle of an escalated issue (1st line support -> higher).
      [Commented]
  
      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release

      ## PAGE CONTAINS HANDYANDY MYSQL MODS ##
      ## Copyright (C) 2005 Andy Deakin (handyandy.org.uk) ##

      ----

      Copyright (C) 2003  Central Manchester CLC
      Copyright (C) 2003  David Thorne (davethorne@gmail.com)

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation version 2.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  */

  // Start session and populate it with data
  session_start();

  // Page security
  if ($_SESSION['_usertype'] != 'Administrator' && 
      $_SESSION['_usertype'] != 'Domain Administrator' && 
      $_SESSION['_usertype'] != 'Root') {
    require_once 'system/security.php';
    ThrowOut();
  }

  // Page Title
  $ptitle = 'Levels';

  // Includes
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/message.php';
  require 'header.php';

  // Language selection
  set_text_domain("levels");

  // Retrieve Get/Post variables
  $act = $_REQUEST['act'];
  $level = $_POST['level'];
  $levels = $_REQUEST['levels'];

  // Action: Add a level to the system
  if ($act == 'addlevelaction') {
    $act = 'addlevel';
    // Make sure the level has a name
    if ($level == '') {
      $message = gettext("CORRECTION: You must give this level a name.");
    } else {
      $levelcount = db_recordset("SELECT * FROM tbl_Levels WHERE active=1 AND domain=$_SESSION[_domain] AND id>0");
      // Add the level
      db_send("INSERT INTO tbl_Levels (level,domain,sortorder) VALUES ('" . $level . "'," . $_SESSION['_domain'] . ',' . count($levelcount) . ")");

      $levels = '';
      $act = '';
      $message = gettext("NOTE: Level successfully added to system.");
    }
  }

  // Action: Request details to add a level to the system
  if ($act == 'addlevel') {

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('Level Admin')?></h1>
  <h2><?php echo gettext('Please enter the following information to add a level:')?></h2>
  
  <div class="block">
    <form name="mainform" method="post" action="">
      <input type="hidden" name="act" value="addlevelaction" />
      <div class="labelfieldpair">
        <div class="name"><label for="level"><?php echo gettext('Level Name')?></label></div>
        <div class="field"><input type="text" name="level" id="level" size="35" maxlength="50" value="<?php echo $level?>" /></div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Add Level')?>" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='levels.php?levels=<?php echo $levels?>'" />
      </div>
    </form>
  </div>

<?php
  }

  // Action: Edit a level
  if ($act == 'editlevelaction') {
    $act = 'editlevel';
    // Make sure the level has a name
    if ($level == '') {
      $message = gettext("CORRECTION: You must give this level a name.");
    } else {
      // Edit the level
      db_send("UPDATE tbl_Levels SET level='" . $level . "' WHERE ID=$levels");
      $message = gettext("NOTE: Level successfully updated");
      $act = '';
    }
  }

  // Action: Remove a level from the system
  if ($act == 'removelevel') {
    // Find the sort order of this level
    $level = db_recordset("SELECT sortorder,active FROM tbl_Levels WHERE id=$levels");
    // deactivate it and negate the sort order
    db_send("UPDATE tbl_Levels SET active=1-active,sortorder=-1 WHERE id=$levels");
    // change all the higher sort orders in order to fill the gap that has now been made
    if ($level[0][active] == 0) {
      db_send("UPDATE tbl_Levels SET sortorder=sortorder+1 WHERE domain=$_SESSION[_domain] AND active=1");
    }else{ db_send("UPDATE tbl_Levels SET sortorder=sortorder-1
      WHERE domain=$_SESSION[_domain] AND active=1 AND sortorder>" . $level[0][sortorder]);
    }
    $act = "";
    $levels = '';
    $message = gettext("NOTE: Level successfully (de)activated.");
  }

  // Action: Move a level up
  if ($act == 'up') {
    // Find this level's sort order
    $level = db_recordset("SELECT sortorder,active FROM tbl_Levels WHERE id=$levels");

    // Only change the ordering of active levels
    if ($level[0][active] == 1) {
      // Only move a level up if it isn't at the top already
      if ($level[0][sortorder] > 0) {
        // Find the level that is one in line above it
        $newlevel = db_recordset("SELECT id FROM tbl_Levels WHERE domain=$_SESSION[_domain] AND active=1 AND sortorder=" . ($level[0][sortorder]-1));
        // Swap the sort orders for the two levels
        db_send("UPDATE tbl_Levels SET sortorder=" . ($level[0][sortorder]-1) . " WHERE id=$levels");
        db_send("UPDATE tbl_Levels SET sortorder=" . $level[0][sortorder] . " WHERE id=" . $newlevel[0][id]);
      }
    } else {
      $message = gettext("CORRECTION: You cannot change the precedence of an inactive item.");
    }

    $act = "";
  }

  // Action: Move a level down
  if ($act == 'down') {
    // Find the lowest level
    $levelsRS = db_recordset("SELECT * FROM tbl_Levels WHERE domain=$_SESSION[_domain] AND active=1");
    // Find this level's sort order
    $level = db_recordset("SELECT sortorder,active FROM tbl_Levels WHERE id=$levels");

    // Only change the ordering of active levels
    if ($level[0][active] == 1) {
      // Only move a level down if it isn't at the bottom already
      if ($level[0][sortorder] < (count($levelsRS)-1)) {
        // Find the level that is one in line below it
        $newlevel = db_recordset("SELECT id FROM tbl_Levels WHERE domain=$_SESSION[_domain] AND active=1 AND sortorder=" . ($level[0][sortorder]+1));
        // Swap the sort orders for the two levels
        db_send("UPDATE tbl_Levels SET sortorder=" . ($level[0][sortorder]+1) . " WHERE id=$levels");
        db_send("UPDATE tbl_Levels SET sortorder=" . $level[0][sortorder] . " WHERE id=" . $newlevel[0][id]);
      }
    } else {
      $message = gettext("CORRECTION: You cannot change the precedence of an inactive item.");
    }

    $act = "";
  }

  // Action: Request details to edit a level
  if ($act == 'editlevel') {

    // Retrieve Level information
    $levelsRS = db_recordset("SELECT * FROM tbl_Levels WHERE id=" . $levels);

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('Level Admin')?></h1>
  <h2><?php echo gettext('Please enter the following information to edit a level:')?></h2>
  
  <div class="block">
    <form name="mainform" method="post" action="">
      <input type="hidden" name="act" value="editlevelaction" />
      <input type="hidden" name="levels" value="<?php echo $levels?>" />
      <div class="labelfieldpair">
        <div class="name"><label for="level"><?php echo gettext('Level Name')?></label></div>
        <div class="field"><input type="text" name="level" id="level" size="35" maxlength="50" value="<?php echo $levelsRS[0][level]?>"></div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Submit Changes')?>" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='levels.php?levels=<?php echo $levels?>'" />
      </div>
    </form>
  </div>

<?php
  }

  // Default action: Show levels and invite user to choose action...
  if ($act == '') {
    // Retrieve levels
    $sql = "SELECT * FROM tbl_Levels WHERE domain=$_SESSION[_domain]";
    if ($_SESSION['_usertype'] != 'Root') {
      $sql .= " AND active=1";
    }
    $sql .= " ORDER BY active DESC,sortorder";
    $levelsRS = db_recordset($sql);
    $num_levels = count($levelsRS);

    if (!$levels) $levels=$levelsRS[0][id];

    if ($message) { display($message); }
?>

<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

  function mainSubmit (act) {
    var flag = true;
    if ((act == 'removelevel' || act == 'editlevel') && document.mainform.levels.value == 0) {
      alert('<?php echo gettext("There are no levels on which to action your request.")?>');
      flag = false;
    }
    if (act == 'removelevel' && flag && !confirm('<?php echo gettext("Are you sure you wish to change the status of this level?")?>')) flag = false;
    if (flag) {
      document.mainform.act.value=act;
      document.mainform.submit();
    }
  }

//-->
//]]>
</script>

  <h1><?php echo gettext('Level Admin')?></h1>
  <h2><?php echo gettext('Please use the lists below to administer the levels of issues in this system:')?></h2>
        
  <div class="block">
    <p><?php echo gettext('The first level in this list is of lowest priority, and movement through the list would be synonymous with escalation of an issue.')?></p>
    <form name="mainform" id="mainform" method="post" action="">
      <input type="hidden" name="act" value="" />
      <div class="columnleft">
        <div class="labelright"><label for="levels"><?php echo gettext('Levels')?></label></div>
        <div class="columnright">
          <input type="button" value="<?php echo gettext('New')?>..." onclick="mainSubmit('addlevel')" /><br />
          <input type="button" value="<?php echo gettext('Edit')?>" onclick="mainSubmit('editlevel')" /><br />
          <input type="button" value="<?php echo gettext('(De)activate')?>" onclick="mainSubmit('removelevel')" />
        </div>
        <div class="columnleft">
          <select name="levels" id="levels" size="10">
<?php
  if ($num_levels == 0) {
    print ("            <option value=\"0\" selected=\"selected\">[".gettext('No Levels')."]</option>\n");
  }
  foreach ($levelsRS as $record) {
    // Set as default if this was previously chosen
    if ($record[id] == $levels) {$checked = " selected=\"selected\"";} else {$checked = "";};
    if ($record[active] == 0) {$style = " class=\"inactive\"";} else {$style = "";};
    print ("            <option value=\"${record[id]}\"${checked}${style}>${record[level]}</option>\n");
  }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft">&nbsp;</div>
        <div class="columnleft">
          <input type="button" value="<?php echo gettext('Up')?>" onclick="mainSubmit('up')" /><br />
          <input type="button" value="<?php echo gettext('Down')?>" onclick="mainSubmit('down')" /><br />
        </div>
      </div>
    </form>
    <hr class="hide" />
  </div>

<?php
  }

  // Include
  require 'footer.php';
?>
