<?/*
Copyright (C) 2003 Media Net Link, Inc. Danville, CA 94526 USA

This file is part of AthenaRMS.

AthenaRMS 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; either version 2 of the License, or
(at your option) any later version.

AthenaRMS 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
*/?>
<?php
  require_once 'server_functions.php';

  globalize_request_keys('download_detail_x', 'download_totals_x',
    'start_year', 'start_month', 'start_day', 'end_year', 'end_month',
    'end_day', 'show_report', 'get_report');

  /*
    Some strange output buffering thing on w3 forced me to do this.  If
    the user requested a download, we need to clear and destroy the output
    buffer before anything else happens.  Seriously, anything else.

    BWD 2003/07/24 - the standard header comes up before this so you would
      definitely need to clean that from the buffer.
  */
  if ($download_detail_x || $download_totals_x) {
    ob_end_clean();
  }

  require_once 'db.php';
  require_once 'ticket.php';
  require_once 'ticket_details_inc.php';

  /*
    Need to handle these early, since we won't actually be outputting
    any HTML at all.

    This stuff we need early, too.
  */
  $start = "$start_year/$start_month/$start_day 00:00:00";
  $end = "$end_year/$end_month/$end_day 23:59:59";
  $us_start = "$start_month/$start_day/$start_year 12:00am";
  $us_end = "$end_month/$end_day/$end_year 11:59pm";

  $sql_start = "$start_year-$start_month-$start_day 00:00:00";
  $sql_end = "$end_year-$end_month-$end_day 23:59:59";

  $start = $sql_start;
  $end = $sql_end;

  if ($download_detail_x) {
    show_ticket_detail_html($start,$end);
    exit;
  } elseif ($download_totals_x) {
    show_closed_by_response_html($start,$end);
    exit;
  }
?>

<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>

<div class="athenatitleshadow">Reports<div class="athenatitle">Reports</div></div>

</td>
<td align="right" class="textsm">

</td></tr></table>
<?php
  if (!$_SESSION['reports']) $_SESSION['reports'] = array ();
  if (!$_SESSION['reports']['show_report']) 
    $_SESSION['reports']['show_report'] = array ();

  include 'lib/report_types.php';

  $date_fields = array (
    'start_year',
    'start_month',
    'start_day',
    'end_year',
    'end_month',
    'end_day',
    'show_report',
  );

  foreach ($date_fields as $df) {
    if ($$df) $_SESSION['reports'][$df] = $_REQUEST[$df];
    $$df = $_SESSION['reports'][$df];
  }

  if (!$start_year or !$start_month or !$start_day or
      !$end_year or !$end_month or !$end_day or (!count($show_report) && $get_report)) {

    redirect ('./', true, false);
  }

  $ticket = new Ticket ($dbi);

  $_SESSION['reports']['start_date'] = $start;
  $_SESSION['reports']['end_date'] = $end;

  print "<font class='textsm'>$us_start to $us_end</font><br /><br />\n";

###############

/*
  At some point I will rearrange these blocks to match the order of the
  checkboxes on the index page.
*/

###############

  if (report_needed(2)) {
    show_ticket_group ('Status', 2);
  }

###############

  if (report_needed(1)) {

    $h = $ticket->Counts_by ($start, $end, date_format('tm.created_date','%Y/%m/%d'));
    if (!$h) {
      print "weekly.php1: <pre>" . $ticket->error . "</pre>\n";
      return;
    }

    list ($html, $total_opened_tickets) = format_group_records ($h,'BY_OPEN_DATE');
    $title = get_title(1);

    print show_title("$title: $total_opened_tickets");
    if ($html) {
      print "<br /><table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n$html";
      print "</table><br />\n\n";
    } else {
      show_no_data();
    }

  }

###############

  if (report_needed(3)) {

    $h = $ticket->Counts_by_Closed ($start, $end, 
      date_format('tm.close_date', '%Y/%m/%d'));

    if (!$h) {
      print "weekly.php2: <pre>" . $ticket->error . "</pre>\n";
      return;
    }

    list ($html, $closed_count) = format_group_records ($h,'BY_CLOSE_DATE');

    print show_title( get_title(3).": $closed_count" );
    /* $closed_count = $ticket->Closed_Count ($start, $end); */
    print "<br /><table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n$html";
    print "</table><br />\n\n";

  }

###############

  if (report_needed(8)) {

    $h = $ticket->Counts_by_Person ($start, $end, 'Opened');
    if (!$h) {
      print "weekly.php3: <pre>" . $ticket->error . "</pre>\n";
      return;
    }

    list ($html, $total_tickets) = format_group_records ($h,'BY_OPENER',"$start_year/$start_month/$start_day","$end_year/$end_month/$end_day");

    print show_title( get_title(8).": $total_tickets" );
    print "<br /><table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n";

    print $html;

    print "</table><br />\n\n";
  }

###############

  if (report_needed(4)) {

    $h = $ticket->Counts_by_Person ($start, $end, 'Closed');
    if (!$h) {
      print "weekly.php4: <pre>" . $ticket->error . "</pre>\n";
      return;
    }

    list ($html, $total_tickets) = format_group_records ($h,'BY_CLOSER',"$start_year/$start_month/$start_day","$end_year/$end_month/$end_day");

    print show_title( get_title(4).": $total_tickets" );
    print "<br /><table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n";

    print $html;

    print "</table><br />\n\n";
  }

###############

  if (report_needed(9)) {
    print show_title( get_title(9) );
    show_problem_group ('created_date');
  }

###############

  if (report_needed(5)) {
    print show_title( get_title(5) );
    show_problem_group ('close_date');
  }

###############

  if (report_needed(10)) {
    print show_title( get_title(10) );
    show_ticket_detail($start, $end);
  }

###############

  if (report_needed(11)) {
    print show_title( get_title(11) );
    show_closed_by_response($start, $end);
  }
?>

<?php

  return;

###############

  print "<h3>Problems for Performance Issue Tickets</h3>\n";
  print "in progress...<br>\n";

###############

##
## fix these, they consume mega memory
##

  #show_closed_within (0, 'Same Day');
  #show_closed_within (1, 'Next Day');
  #show_closed_within (2);

###############

  print "<h3>All Tickets During this Period by Person</h3>\n";
  print "<br /><table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n";

  $h = $ticket->Counts_by_Person ($start, $end);
    if (!$h) {
      print "weekly.php5: <pre>" . $ticket->error . "</pre>\n";
      return;
    }

  list ($html, $total_tickets) = format_group_records ($h);
  print $html;

  print "</table><br />\n\n";
  print "<!-- $total_tickets -->\n";

###############

  print "<h3>Tickets During this Period by Escalated Person</h3>\n";
  print "in progress<br />\n";

###############


  function gen_X ($count) {
    $buf = '';
    ## No longer cutting in half
    for ($i=0; $i<$count; $i++) {
      $buf .= 'X';
    }
    return $buf;
  }

  function gen_pct ($part, $total) {
    return sprintf ('%01.1f', $part / $total * 100);
  }

  function show_problem_group ($column='close_date') {

    global $dbi;
    global $start;
    global $end;

    global $start_year;
    global $start_month;
    global $start_day;
    global $end_year;
    global $end_month;
    global $end_day;

    global $REMOTE_USER_CRM_ID;

    $to_date = to_date();
    $h = $dbi->prepare ("
      SELECT COUNT(*), 
	     p.problem_type, 
	     p.problem_id
        FROM ticket_crm_map tm INNER JOIN 
	     ticket t ON (tm.ticket_id = t.ticket_id),
             problem_type p
       WHERE tm.$column BETWEEN $to_date AND $to_date
	 AND t.crm_id = tm.crm_id
         AND tm.crm_id = ?
         AND tm.crm_id = p.crm_id
         AND tm.problem_id = p.problem_id
    GROUP BY p.problem_type, p.problem_id
    ORDER BY 1 DESC
    ");

    if (DB::isError($h)) {
      print "weekly.php6: <pre>" . $h->getMessage() . "\n"
	. $h->getUserInfo() . "</pre>\n";
      return;
    }

    $res = $dbi->execute ($h, array($start, $end, $REMOTE_USER_CRM_ID));

    if (DB::isError($res)) {
      print "weekly.php7: <pre>" . $res->getMessage() . "\n"
	. $res->getUserInfo() . "</pre>\n";
      return;
    }

    if ($column == 'created_date') {
      $by_type_opened_or_closed = 'BY_TYPE_OPENED';
    } else {
      $by_type_opened_or_closed = 'BY_TYPE_CLOSED';
    }

    list ($html, $total_tickets) = format_group_records ($res,$by_type_opened_or_closed,"$start_year/$start_month/$start_day","$end_year/$end_month/$end_day");

    if ($html) {
      print "<table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n";
      print $html;
      print "</table><br />\n\n";
    } else {
      show_no_data();
    }

  }

  function show_ticket_group ($group, $id) {
    global $ticket;
    global $start;
    global $end;

    print show_title( get_title($id) );

    $h = $ticket->Counts_by ($start, $end, $group);

    if (!$h) {
      print "show_ticket_group: ".$ticket->error;
      exit;
    }

    list ($html, $total_tickets) = format_group_records ($h);
    if ($html) {
      print "<br /><table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n";
      print $html;
      print "</table><br />\n\n";
    } else {
      show_no_data();
    }

  }

  function show_no_data() {
    print<<<EOF
<br/><font class="errors">No data available.</font><br/><br/>
EOF;
  }

  function format_group_records ($h, $type='',$start='',$end='') {
    $html = '';
    $total = 0;
    $tmp = array();
    $max = -1;
    $MAX_CHARACTERS = 60; ## or something

    while ($row = $h->fetchRow ()) {
      if (count($row) == 3) list($c, $d, $optional_id) = $row;
      else list($c, $d) = $row;

      $total += $c;

      /*
	If $type was specified (one of BY_OPEN_DATE, BY_CLOSE_DATE,
	BY_CLOSER, BY_TYPE_*), decorate $d as needed.
      */
      switch ($type) {
	case 'BY_OPEN_DATE':
	  $munged_date = strftime('%m/%d/%Y',strtotime($d));
	  $d = "<a href=\"../search/search.php?created_start_date=$d&created_end_date=$d&save_option=list\">$munged_date</a>";
	  break;
	case 'BY_CLOSE_DATE':
	  $munged_date = strftime('%m/%d/%Y',strtotime($d));
	  $d = "<a href=\"../search/search.php?close_start_date=$d&close_end_date=$d&save_option=list\">$munged_date</a>";
	  break;
	case 'BY_OPENER':
	  /*
	    Special case:  if we're going BY_OPENER, then the query is also
	    getting the person_id into $optional_id.
	  */
	  $d = "<a href=\"../search/search.php?created_start_date=$start&amp;created_end_date=$end&amp;support_person_id[]=$optional_id&amp;save_option=list\">$d</a>";
	  break;
	case 'BY_CLOSER':
	  /*
	    Special case:  if we're going BY_CLOSER, then the query is also
	    getting the person_id into $optional_id.
	  */
	  $d = "<a href=\"../search/search.php?close_start_date=$start&close_end_date=$end&support_person_id[]=$optional_id&status[]=Closed&save_option=list\">$d</a>";
	  break;
	case 'BY_TYPE_OPENED':
	  /*
	    Other special case: for BY_TYPE, $optional_id has the problem ID.
	  */
	  $d = "<a href=\"../search/search.php?created_start_date=$start&created_end_date=$end&problem_id[]=$optional_id&save_option=list\">$d</a>";
	  break;
	case 'BY_TYPE_CLOSED':
	  $d = "<a href=\"../search/search.php?close_start_date=$start&close_end_date=$end&problem_id[]=$optional_id&save_option=list\">$d</a>";
	  break;
      }

      array_push($tmp, array($c,$d));
      if ($c > $max) $max = $c;
    }

    foreach ($tmp as $a) {
      list ($c,$d) = $a;
      $count = floor($MAX_CHARACTERS * $c / $max);

      $html .= "<tr><td colspan='3'><img src='../../img/cldot.gif' width='1' height='2' alt=''></td></tr>
      <tr>
  <td bgcolor='white' nowrap='nowrap'>&nbsp;&nbsp;<font class='supersubttyl2'>$d</font>&nbsp;</td>
  <td bgcolor='white'><font class='textsm'>&nbsp;($c)</font>&nbsp;&nbsp;</td>
  <td><font class='reportchart'>".gen_X($count)."</font>&nbsp;&nbsp;</td>
</tr>
<tr><td colspan='3'><img src='../../img/cldot.gif' width='1' height='2' alt=''></td></tr>
";
    }

    return array ($html, $total);
  }

  function show_closed_within ($days, $name='') {
    global $ticket;
    global $start;
    global $end;
    global $total_opened_tickets;

    if (!$name) $name = " $days days";

    $h = $ticket->Closed_Within ($start, $end, $days);

    list ($html, $count) = format_group_records ($h);

    $pct = gen_pct ($count, $total_opened_tickets);

    print "<h3>Tickets Opened this Period and Closed in $name: $count ($pct%)</h3>\n";
    print "<table width='100%' bgcolor='#e6f0ce' class='reporttable' border='0' cellspacing='0' cellpadding='0' style='border: black 1px solid'>\n";

    print $html;

    print "</table><br />\n\n";
  }

  function get_title ($id) {
    global $REPORT_TYPES;
    return $REPORT_TYPES[$id];
  }

  function report_needed ($id) {
    global $get_report;

    if ($get_report && array_key_exists('reports', $_SESSION)
      && array_key_exists('show_report', $_SESSION['reports'])
      && array_key_exists($id, $_SESSION['reports']['show_report']))
	return $_SESSION['reports']['show_report'][$id];
    else return;
  }

  function show_title ($text) {
    return "<font class='textsm'><b>$text</b></font>\n";
  }

  function get_person_ids($name) {

  }

  function prepend_support_person($p) {
    return "support_person_id[]=$p";
  }

?>
