<?php

  /*

      reports.php

      Display a detailed summary of each issue restricted by certain criteria.

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-02 arne_sf: Replaced all instances of column name 'user' for table tbl_UserSites with 'userid'
        
      ## 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'] == '' || $_SESSION['_usertype'] == 'Root') {
    require_once 'system/security.php';
    ThrowOut();
  }

  // Page Title
  $ptitle = 'Reports';

  // Includes
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/message.php';
  require_once 'system/sorting.php';
  require_once 'system/user_preferences.php';
  require_once 'system/global_preferences.php';
  require_once 'system/functions.php';
  require 'header.php';
  require 'system/calendar.inc';

  // Language selection
  set_text_domain("reports");

  // Retrieve Get/Post variables
  $act = $_REQUEST['act'];
  $orderby = $_GET['orderby'];
  $orderdir = $_GET['orderdir'];
  $site = $_REQUEST['site'];
  $reportedby = $_REQUEST['reportedby'];
  $priority = $_REQUEST['priority'];
  $level = $_REQUEST['level'];
  $status = $_REQUEST['status'];
  $category = $_REQUEST['category'];
  $detail = $_REQUEST['detail'];
  $datefrom = $_REQUEST['datefrom'];
  $dateto = $_REQUEST['dateto'];
  $assignedto = $_REQUEST['assignedto'];
  $createdby = $_REQUEST['createdby'];

  if ($conf_db['dsn']['phptype'] == 'pgsql') {
    $is_pgsql = true;
  }

  $reset = $_REQUEST['reset'];

  if ($reset == 'yes') {
    // Reset remembered sql restrictions
    $_SESSION['_searchsql'] = '';
  }

  // Action: Retrieve issues that match the search and dsiplay them
  if ($act == 'action') {

    // Set up sorting and grouping values for the unresolved issue list
    if ($orderby == '') {
      $grouporderby = 'id';
      $orderby = 'sortorder DESC,id DESC';
      $orderdir = '';
    } else {
      $grouporderby = $orderby;
    }

    // Parse the dates given - if any
    $validdate = true;
    if ($datefrom != '') {
      $pieces = explode("/", $datefrom);
      if (count($pieces) == 1) {
        // Parse a date without slashes DDMMYYYY
        if (!is_numeric($pieces[0])) {
          $validdate = false;
        } elseif (strlen($pieces[0]) != 8) {
          $validdate = false;
        } else {
          $day = substr($pieces[0], 0,2);
          $month = substr($pieces[0], 2, 2);
          $year = substr($pieces[0], 4, 4);
          if (checkdate($month, $day, $year)) {
            $datefrom = mktime(0,0,0, $month, $day, $year);
          } else {
            $validdate = false;
          }
        }
      } elseif (count($pieces) == 3) {
        // Parse a date with slashes (DD/MM/YYYY)
        $day = intval($pieces[0]);
        $month = intval($pieces[1]);
        $year = intval($pieces[2]);
        if (!checkdate($month, $day, $year)) {
          // Invalid date
          $validdate = false;
        } else {
          $datefrom = mktime(0,0,0,$month, $day, $year);
        }
      } else {
        // Invalid date
        $validdate = false;
      }
    }
    if ($dateto != '') {
      $pieces = explode("/", $dateto);
      if (count($pieces) == 1) {
        // Parse a date without slashes DDMMYYYY
        if (!is_numeric($pieces[0])) {
          $validdate = false;
        } elseif (strlen($pieces[0]) != 8) {
          $validdate = false;
        } else {
          $day = substr($pieces[0], 0,2);
          $month = substr($pieces[0], 2, 2);
          $year = substr($pieces[0], 4, 4);
          if (checkdate($month, $day, $year)) {
            $dateto = mktime(23,59,59, $month, $day, $year);
          } else {
            $validdate = false;
          }
        }
      } elseif (count($pieces) == 3) {
        // Parse a date with slashes (DD/MM/YYYY)
        $day = intval($pieces[0]);
        $month = intval($pieces[1]);
        $year = intval($pieces[2]);
        if (!checkdate($month, $day, $year)) {
          // Invalid date
          $validdate = false;
        } else {
          $dateto = mktime(23,59,59,$month, $day, $year);
        }
      } else {
        // Invalid date
        $validdate = false;
      }
    }
    if (($datefrom != '' && $dateto == '') ||
        ($datefrom == '' && $dateto != '')) {
      $act = '';
      $message = gettext("CORRECTION: When restricting results by date, please enter
      both a 'from' date and a 'to' date.");
    } elseif ($datefrom >= $dateto && $datefrom != '') {
      $act = '';
      $message = gettext("CORRECTION: The 'to' date needs to be later than the 'from'
      date");
    } elseif (!$validdate) {
      $act = '';
      $message = gettext('CORRECTION: Invalid date entered - Dates must be entered in
      the form DD/MM/YYYY (with or without slashes) or selected from the popup
      calendar.');
    } else {
      $act = 'dosearch';
    }
  }
  if ($act == 'dosearch') {
    // If the session does not remember a previous search, then create the sql from scratch
    if ($_SESSION['_searchsql'] == '') {
      // create sql statement using restictions
      $sql = '';
      if ($is_pgsql) {
//       if ($_SESSION['_usertype'] == 'Client' || $_SESSION['_usertype'] == 'Site Contact') {
//         $sql .= 'tbl_UserSites,';
//       }
//       $sql .= 'vw_Issues';
       $sql .= 'tbl_UserSites,vw_Issues';
      }
      if ($id != '') {
        if ($is_pgsql) {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND vw_Issues.site=tbl_UserSites.site AND vw_Issues.id=$id AND ";
        } else {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND tbl_Issues.site=tbl_UserSites.site AND tbl_Issues.id=$id AND ";
        }
      
      } else {
        if (count($category) > 0) {
          if ($is_pgsql) {
            $sql .= ',tbl_ProblemDetails';
          }
        }
        if ($is_pgsql) {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND vw_Issues.site=tbl_UserSites.site AND ";
        } else {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND tbl_Issues.site=tbl_UserSites.site AND ";
        }
        if (count($site) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.site IN (';
          } else {
            $sql .= 'tbl_Issues.site IN (';
          }
          $flag = 0;
          foreach ($site as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($reportedby) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.reportedby IN (';
          } else {
            $sql .= 'tbl_Issues.reportedby IN (';
          }
          $flag = 0;
          foreach ($reportedby as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($createdby) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.createdby IN (';
          } else {
            $sql .= 'tbl_Issues.createdby IN (';
          }
          $flag = 0;
          foreach ($createdby as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if ($datefrom != '' && $dateto != '') {
          if ($is_pgsql) {
            $sql .= "vw_Issues.createdon > $datefrom " .
              " AND vw_Issues.createdon < $dateto AND ";
          } else {
            $sql .= "tbl_Issues.createdon > $datefrom " .
              " AND tbl_Issues.createdon < $dateto AND ";
          }
        }
        if (count($assignedto) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.assignedto IN (';
          } else {
            $sql .= 'tbl_Issues.assignedto IN (';
          }
          $flag = 0;
          foreach ($assignedto as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($level) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.level IN (';
          } else {
            $sql .= 'tbl_Issues.level IN (';
          }
          $flag = 0;
          foreach ($level as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($priority) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.priority IN (';
          } else {
            $sql .= 'tbl_Issues.priority IN (';
          }
          $flag = 0;
          foreach ($priority as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($status) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.status IN (';
          } else {
            $sql .= 'tbl_Issues.status IN (';
          }
          $flag = 0;
          foreach ($status as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($category) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.detail=tbl_ProblemDetails.id AND tbl_ProblemDetails.category IN (';
          } else {
            $sql .= 'tbl_Issues.detail=tbl_ProblemDetails.id AND tbl_ProblemDetails.category IN (';
          }
          $flag = 0;
          foreach ($category as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($detail) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.detail IN (';
          } else {
            $sql .= 'tbl_Issues.detail IN (';
          }
          $flag = 0;
          foreach ($detail as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
      }

      if ($is_pgsql) {
        $sql .= "vw_Issues.domain=$_SESSION[_domain]";
      } else {
        $sql .= "tbl_Issues.domain=$_SESSION[_domain]";
      }

      // Set session to remember these restrictions
      $_SESSION['_searchsql'] = $sql;
    } else {
      // Retrieve the stored restrictions in sql form
      $sql = $_SESSION['_searchsql'];
    }
    
    if ($is_pgsql) {
      $issuesRS = db_recordset("SELECT count(vw_Issues.ID) AS num FROM $sql");
      // How many issues would be in this category
      $num_issues = $issuesRS[0][num];
      $issuesRS = db_recordset("SELECT sum(tbl_times.time) AS totaltime FROM
      tbl_times, $sql AND tbl_times.issue = vw_issues.id");
      $totaltime = $issuesRS[0]['totaltime'];
      $sql = "SELECT vw_Issues.* FROM $sql ORDER BY $orderby $orderdir";
      $issuesRS = db_recordset($sql);
    } else {
      $sql_from = "tbl_Issues, tbl_UserSites, tbl_ProblemDetails";
      $issuesRS = db_recordset("SELECT DISTINCT tbl_Times.* FROM
      tbl_Times, $sql_from $sql AND tbl_Times.issue = tbl_Issues.id");
      $totaltime='0';
      for($i=0;$i<count($issuesRS);$i++) { 
        $totaltime +=$issuesRS[$i]['time'];    
      }
      $totaltime = maketime($totaltime);
      $sql = "SELECT DISTINCT $aselects FROM $afrom $sql ORDER BY $orderby $orderdir";
      $issuesRS = db_recordset($sql);
      $num_issues = count($issuesRS);
    }
    // Find the highest status (the terminal status) and treat it as closed
    $closedstatus = get_closed_status($_SESSION['_domain']);
?>

  <h1><?php echo gettext("Report")?></h1>
  
  <div class="block">

    <div class="buttonpanel">
<?php
        // Make the back button work correctly for searches initiated from
        // an issue page (i.e. more issues like this links)
    $referer = $_SERVER['HTTP_REFERER'];
    if ($referer == '') $referer = 'reports.php';
?>
      <input name="again" type="button" id="again" value="<?php echo gettext("Back to previous page")?>"
      onclick="document.location='<?php echo $referer?>'" />
    </div>
    <table width="95%" border="0" align="center" cellpadding="1" cellspacing="0" summary="<?php echo gettext("This table summarises the unresolved issues for this user's sitestes.")?>">
      <thead>
        <tr>
          <th align="left" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('id',$orderby,$orderdir)?>">#</a><?php echo makesymbol('id',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('createdon',$orderby,$orderdir)?>"><?php echo gettext("Reported")?></a><?php echo makesymbol('createdon',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('reportedbyname',$orderby,$orderdir)?>"><?php echo gettext("Reported By")?></a><?php echo makesymbol('reportedbyname',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('createdbyname',$orderby,$orderdir)?>"><?php echo gettext("Created By")?></a><?php echo makesymbol('createdbyname',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('assignedtoname',$orderby,$orderdir)?>"><?php echo gettext("Assigned To")?></a><?php echo makesymbol('assignedtoname',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('sitename',$orderby,$orderdir)?>"><?php echo gettext("Site")?></a><?php echo makesymbol('sitename',$orderby,$orderdir)?></th>
          <th align="center" class="issueheader"><?php echo gettext("Time spent")?></th>
          <th align="center" class="issueheader"><a href="reports.php?act=action&amp;<?php echo makeordering('sortorder',$orderby,$orderdir)?>"><?php echo gettext("Priority")?></a><?php echo makesymbol('sortorder',$orderby,$orderdir)?></th>
        </tr>
      </thead>
<?php
    if ($num_issues > 0) {
?>
      <tfoot>
        <tr>
          <td align="right" colspan="8"><?php printf(gettext("Total time spent: %s, %s issues(s) total."),$totaltime,$num_issues);?></td>
        </tr>
      </tfoot>
<?php
    }
?>
      <tbody>
<?php
    if ($num_issues == 0) {
      // If there are no issues, then say as much...
      print "        <tr>\n";
      print "          <td colspan=\"8\" align=\"center\" class=\"issuecell\">".gettext("No Unresolved Issues.")."</td>\n";
      print "        </tr>\n";
    }

    // Alternately shade the rows on the sorted attribute by keeping track
    // of the previously shown value. If this value != last value then the
    // colour can be changed

    // flag shows whether to shade or not - starts being 'NO SHADING'
    $flag = 1;
    // Nullify the last value
    $lastvalue = "\0";
    foreach ($issuesRS as $record) {

      // Get the total time spent on each issue
      $timeRS = db_recordset("SELECT SUM(time) AS ts FROM tbl_Times WHERE
      issue={$record['id']}");
      $timespent = maketime($timeRS[0]['ts']);
      if ($timespent == '' || $timespent == '0::' || $timespent == '::') {
    ## $timespent = $timeRS[0]['ts'];
      ## if ($timespent == '') {
        $timespent = '00:00:00';
      }

      if ($lastvalue != $record[$grouporderby]) {
        // If different, toggle shading
        $flag = 1 - $flag;
        $lastvalue = $record[$grouporderby];
      }
      if ($flag == 0) {
        $class = 'reportcell';
        $altclass = 'issuecell';
      } else {
        $class = 'reportcelldark';
        $altclass = 'issuecelldark';
      }

      // For the priority column, choose the colouring
      if ($closedstatus == $record['status'] || $record['recalled'] == 1) {
        $priority='prioritydefunct';
      } else {
        switch ($record['class']) {
          case 0: $priority='prioritylow';
            break;
          case 1: $priority='prioritymedium';
            break;
          case 2: $priority='priorityhigh';
            break;
        }
      }

      // Show attributes
      print "        <tr valign=\"top\">\n";
      print "          <td class=\"$class\"><a href=\"issue.php?id=${record[id]}\">${record[id]}</a></td>\n";
      print "          <td class=\"$class\">";
      if (strftime('%d/%m/%y',$record[createdon]) == strftime('%d/%m/%y')) {
        print strftime('%H:%M',$record[createdon]);
      } else {
        print strftime('%d/%m/%y',$record[createdon]);
      }
      print "</td>\n";
      print "          <td class=\"$class\">{$record['reportedbyname']}</td>\n";
      print "          <td class=\"$class\">{$record['createdbyname']}</td>\n";
      print "          <td class=\"$class\">{$record['assignedtoname']}</td>\n";
      print "          <td class=\"$class\">{$record['sitename']}</td>\n";
      print "          <td class=\"$class\">$timespent</td>\n";
      print "          <td align=\"center\" rowspan=\"2\" class=\"$priority\">";
      if ($record['recalled'] == 1) {
        print 'Recalled';
      } else {
        print $record[priorityname];
      }
      print "</td>\n";
      print "        </tr>\n";
      print "        <tr valign=\"top\">\n";
      print "        <td class=\"$altclass\"
      colspan=\"3\">Summary: {$record['summary']}</td>";
      print "        <td class=\"$altclass\"
      colspan=\"4\">Description: {$record['description']}</td>";
      print "        </tr>";

    }
?>
      </tbody>
    </table>

  </div>

<?php
  }

  // Default action: To ask for search terms and restrictions
  if ($act == '') {

    // Retrieve the values for restrictions from the actual set of issues
    $sitesRS = db_recordset("SELECT DISTINCT tbl_Sites.* FROM tbl_UserSites,tbl_Sites,tbl_Issues WHERE tbl_UserSites.userid=$_SESSION[_id] AND tbl_UserSites.site=tbl_Sites.id AND tbl_Sites.domain=$_SESSION[_domain] AND tbl_Issues.site=tbl_Sites.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Sites.site");
    $categoriesRS = db_recordset("SELECT DISTINCT tbl_ProblemCategories.* FROM tbl_ProblemCategories,tbl_ProblemDetails,tbl_Issues WHERE tbl_ProblemCategories.id=tbl_ProblemDetails.category AND tbl_ProblemDetails.id=tbl_Issues.detail AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_ProblemCategories.description");
    $num_categories = count($categoriesRS);
    if ($num_categories > 0)
      $detailsRS = db_recordset("SELECT DISTINCT tbl_ProblemDetails.* FROM tbl_ProblemDetails,tbl_Issues WHERE tbl_ProblemDetails.id=tbl_Issues.detail AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_ProblemDetails.description");
    $prioritiesRS = db_recordset("SELECT DISTINCT tbl_Priorities.* FROM tbl_Priorities,tbl_Issues WHERE tbl_Issues.priority=tbl_Priorities.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Priorities.sortorder");
    $levelsRS = db_recordset("SELECT DISTINCT tbl_Levels.* FROM tbl_Levels,tbl_Issues WHERE tbl_Issues.level=tbl_Levels.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Levels.sortorder");
    $statusesRS = db_recordset("SELECT DISTINCT tbl_Statuses.* FROM tbl_Statuses,tbl_Issues WHERE tbl_Issues.status=tbl_Statuses.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Statuses.sortorder");
    $usersRS = db_recordset("SELECT DISTINCT tbl_Users.* FROM tbl_Users,tbl_Issues WHERE tbl_Issues.reportedby=tbl_Users.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Users.name");
    $assignedtoRS = db_recordset("SELECT DISTINCT tbl_Users.* FROM
    tbl_Users,tbl_Issues WHERE tbl_Issues.assignedto=tbl_Users.id AND
    tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Users.name");
    $createdbyRS = db_recordset("SELECT DISTINCT tbl_Users.* FROM
    tbl_Users,tbl_Issues WHERE tbl_Issues.createdby=tbl_Users.id AND
    tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Users.name");
    // Reset remembered sql restrictions
    $_SESSION['_searchsql'] = '';

?>

<script language="javascript" type="text/javascript" src="system/forms.js"></script>
  <?php if ($message) { display(gettext($message));} ?>
  <h1><?php echo gettext("Reports")?></h1>
  <h2><?php echo gettext("Please select the criteria for the issues to report on")?>:</h2>
  
  <div class="block">
    <form id="mainform" method="get" onsubmit="return mainSubmit()" action="">
      <input type="hidden" name="act" value="action" />
      <div class="columnleft">
        <div class="labelleft"><label for="site"><?php echo gettext("Site")?>:</label></div>
        <div class="columnleft">
          <select name="site[]" id="site" size="4" multiple="multiple">
<?php
    foreach ($sitesRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[site]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="reportedby"><?php echo gettext("Reported By")?>:</label></div>
        <div class="columnleft">
          <select name="reportedby[]" id="reportedby" size="4" multiple="multiple">
<?php
    foreach ($usersRS as $record) {
      print ("            <option value=\"{$record['id']}\">{$record['name']}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="createdby"><?php echo gettext("Created By")?>:</label></div>
        <div class="columnleft">
          <select name="createdby[]" id="createdby" size="4" multiple="multiple">
<?php
    foreach ($createdbyRS as $record) {
      print ("            <option value=\"{$record['id']}\">{$record['name']}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="assignedto"><?php echo gettext("Assigned To")?>:</label></div>
        <div class="columnleft">
          <select name="assignedto[]" id="assignedto" size="4" multiple="multiple">
<?php
    foreach ($assignedtoRS as $record) {
      print ("            <option value=\"{$record['id']}\">{$record['name']}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="priority"><?php echo gettext("Priority")?>:</label></div>
        <div class="columnleft">
          <select name="priority[]" id="priority" size="4" multiple="multiple">
<?php
    foreach ($prioritiesRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[priority]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="level"><?php echo gettext("Level")?>:</label></div>
        <div class="columnleft">
          <select name="level[]" id="level" size="4" multiple="multiple">
<?php
    foreach ($levelsRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[level]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="status"><?php echo gettext("Status")?>:</label></div>
        <div class="columnleft">
          <select name="status[]" id="status" size="4" multiple="multiple">
<?php
    foreach ($statusesRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[status]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
<?php
    if ($num_categories > 0) {
?>
      <div class="columnleft">
        <div class="labelleft"><label for="category"><?php echo gettext("Problem Category")?>:</label></div>
        <div class="columnleft">
          <select name="category[]" id="category" size="4" multiple="multiple">
<?php
      foreach ($categoriesRS as $record) {
        print ("            <option value=\"${record[id]}\">${record[description]}</option>\n");
      }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="detail"><?php echo gettext("Problem Detail")?>:</label></div>
        <div class="columnleft">
          <select name="detail[]" id="detail" size="8" multiple="multiple">
<?php
      reset($categoriesRS);
      // Create a grouped <select> list, grouping details on categories
      foreach ($categoriesRS as $record) {
        print "            <optgroup label=\"${record[description]}\">\n";
        $current = filter_records($detailsRS,'category',$record[id]);
        foreach ($current as $recorddetail) {
          print "              <option value=\"${recorddetail[id]}\">${recorddetail[description]}</option>\n";
        }
        print "            </optgroup>\n";
      }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labeleft"><?php echo gettext("Creation date")?>:</div>
        <div class="columnleft">
            <label for="datefrom"><?php echo gettext("From")?>:</label>
            <div class="field"><input type="text" size="10" name="datefrom" 
            id="datefrom" />
            <a href="javascript:showCalendar('caldatefrom','datefrom')"
            >[ <?php echo gettext("calendar")?> ]</a></div>
            <div id="caldatefrom" class="calendar"></div>
            <label for="dateto"><?php echo gettext("To")?>:</label>
            <div class="field"><input type="text" size="10" name="dateto" 
            id="dateto" />
            <a href="javascript:showCalendar('caldateto','dateto')"
            >[ <?php echo gettext("calendar")?> ]</a></div>
            <div id="caldateto" class="calendar"></div>
        </div>
      </div>
<?php
    }
?>
      <hr class="hide" />
      <div class="buttonpanel">
        <input type="submit" value="<?php echo gettext("Find!")?>" />
        <input type="reset" value="<?php echo gettext("Reset")?>" />
      </div>
    </form>
  </div>

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

  document.forms.mainform.id.focus();

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

<?php
  }

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