<?/*
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

## BROKEN FOR MYSQL

$headings = array (
  'Problem',
  'Ticket Id',
  'Opened Date',
  'Updated Date',
  'Closed Date',
  'Days Open',
  'First Response',
);

  $total_headings = array (
    'Date',
    'New-Open',
    'Closed-Same',
    'Closed-Next',
    'Closed-Other',
  );

function fetch_ticket_data($start, $end) {
  global $dbi;
  global $REMOTE_USER_CRM_ID;
  global $db_config;

  $dfcreated = date_format('tcm.created_date');
  $dfcreated2 = date_format('tcm.created_date', '%Y/%m/%d');
  $dfupdated = date_format('tcm.updated_date');
  $dfclose = date_format('tcm.close_date');

  $to_date = to_date();

  switch ($db_config['driver']) {
    case 'pgsql':
      $days = 'EXTRACT(epoch FROM AGE(tcm.close_date, tcm.created_date))/86400';
      $days_open = "ROUND(($days)::NUMERIC, 2)";
      $something = "TRUNC($days)";
      break;
    case 'mysql':
      $days = '(UNIX_TIMESTAMP(tcm.close_date) - '
	    .  'UNIX_TIMESTAMP(tcm.created_date)) / 86400';
      $days_open = "ROUND($days, 2)";
      $something = "FLOOR($days)";
      break;
    case 'oci8':
      $days = 'tcm.close_date-tcm.created_date';
      $days_open = "round($days,2)";
      $something = "round($days)";
      $start = str_replace('/', '-', $start);
      $end = str_replace('/', '-', $end);
      break;
    default:
      die('dont know how to lookup info based on database type (ticket_details_inc.php)');
  }

  $sql = <<<EOF
SELECT pt.problem_type, 
       tcm.ticket_id, 
       $dfcreated AS create_ts,
       $dfupdated AS update_ts, 
       $dfclose AS close_ts,
       $days_open AS days_open,
       min(c.created_date) AS first_response,
       $something AS something,
       $dfcreated2 AS create_day,
       tcm.created_date
FROM ticket_crm_map tcm
     LEFT OUTER JOIN comments c ON (tcm.ticket_id = c.ticket_id)
     LEFT OUTER JOIN ticket t ON 
	(c.ticket_id = t.ticket_id AND NOT (c.person_id = t.user_person_id)),
     problem_type pt
WHERE tcm.crm_id = ?
  AND tcm.created_date BETWEEN $to_date AND $to_date
  AND tcm.crm_id = pt.crm_id
  AND tcm.problem_id = pt.problem_id
GROUP BY pt.problem_type,
	 tcm.ticket_id,
	 $dfcreated,
	 $dfupdated,
	 $dfclose,
	 $days_open,
	 $something,
	 $dfcreated2,
	 tcm.created_date
ORDER BY UPPER(pt.problem_type), tcm.created_date
EOF;

  $h = $dbi->prepare($sql);

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

  if (DB::isError($res))
    die("weekly.php: fetch_ticket_data(): <pre>\n".$res->getMessage()."\n"
      .$res->getUserInfo()."($REMOTE_USER_CRM_ID: $start => $end)\n</pre>\n");
  
  $ret = array();
  while ($r = $res->fetchRow()) {   
    array_push($ret, $r);
  }

  return $ret;
}

function show_ticket_detail($start, $end) {
  global $headings;

  $out = <<<EOF
  <table cellpadding="1" border="0" cellspacing="0"><tr><td bgcolor="b7d573">
  <table cellpadding="2" border="0" cellspacing="1">
  <tr bgcolor="#b7d573">

EOF;

  foreach ($headings as $head) {
    $out .= "  <th  class='subtitle' nowrap=\"nowrap\" align=\"center\">&nbsp;$head&nbsp;</th>\n";
  }

  $out .= "</tr>\n";

  $rows = fetch_ticket_data($start, $end);

  $has_data = false;
  foreach ($rows as $r) {
    $created_date = array_pop($r); # was only used for ordering
    $has_data = true;
    $open_date = array_pop($r);
    $time = array_pop($r);

    $out .= "<tr>\n";
    foreach ($r as $i) {
      /*
	Need to find the ticket ID.  Odds are it's the only one that's
	composed solely of numbers.
      */
      if (ereg('^[0-9]+$', $i)) {
	$i = "<a href=\"../ticket/edit_ticket?ticket_id=$i\">$i</a>";
      }
      $out .= "  <td bgcolor='#ffffff' class='textsm' nowrap=\"nowrap\">&nbsp;$i&nbsp;</td>\n";
    }
    $out .= "</tr>\n";

  }

  $out .=<<<EOF
  </table></td></tr></table>
EOF;

  if ($has_data) {
    print $out;
  } else {
    print<<<EOF
<br/><font class="errors">No data available.</font><br/><br/>
EOF;
  }
}

/*
  As show_ticket_detail(), but returns it comma-separated.  Also this sends
  a content-type header for you, so don't expect to send HTML to the user
  and expect it to be rendered.
*/
function show_ticket_detail_html($start, $end) {
  global $headings;

  /* 
    Empty the output buffer and disable output buffering.  I call 
    ob_end_clean() because otherwise a rogue "-- end sub header -->" 
    shows up for no good reason.
  */
  while (@ob_end_clean());
  header('Content-Type: text/application-csv');
  header('Content-Disposition: attachment; filename=ticket_detail.csv');

  print join(",", $headings);
  print "\n";

  $rows = fetch_ticket_data($start, $end);

  foreach ($rows as $r) {
    $open_date = array_pop($r);
    $time = array_pop($r);

    /* 
      Quotify the row elements for CSV format.  Primarily we're going to
      change any double quotes ('"') into doubled double quotes ('""'), and
      if there's a comma (',') in it, surround it with quotes.
    */
    $r = array_map("csvify",$r);

    print join(",", $r);
    print "\n";
  }
}

function show_closed_by_response($start, $end) {
  $totals = array();
  $rows = fetch_ticket_data($start, $end);

  global $total_headings;

  foreach ($rows as $r) {
    $open_date = array_pop($r);
    $time = array_pop($r);

    if ($time > 1) $time = 'other';

    if (!array_key_exists($open_date, $totals)) $totals[$open_date] = array();

    if (!array_key_exists('open', $totals[$open_date]))
      $totals[$open_date]['open'] = 0;

    if (!array_key_exists($time, $totals[$open_date]))
      $totals[$open_date][$time] = 0;

    $totals[$open_date]['open']++;
    $totals[$open_date][$time]++;
  }

  $out = <<<EOF
  <table cellpadding="1" border="0" cellspacing="0"><tr><td bgcolor="b7d573">
  <table cellpadding="2" border="0" cellspacing="1">
  <tr bgcolor="#b7d573">

EOF;

  foreach ($total_headings as $head) {
    $out .= "  <th class='subtitle' nowrap=\"nowrap\" align=\"center\">&nbsp;$head&nbsp;</th>\n";
  }

  $out .= "</tr>\n";

  ksort($totals);
  reset($totals);
  $has_data = false;
  foreach ($totals as $day => $day_ary) {
    $has_data = true;
    foreach (array(0, 1) as $n)
      if (!array_key_exists($n, $day_ary)) $day_ary[$n] = 0;
    $data = array($day, $day_ary['open'], $day_ary[0], $day_ary[1],
		  $day_ary['other']);

    $out .= "<tr>\n";
    foreach ($data as $i) {
      $out .= "  <td bgcolor='#ffffff' align=\"center\" class='textsm'>&nbsp;$i&nbsp;</td>\n";
    }
    $out .= "</tr>\n";

  }

  $out .= "</table></td></tr></table>\n";

  if ($has_data) {
    print $out;
  } else {
    print<<<EOF
<br/><font class="errors">No data available.</font><br/><br/>
EOF;
  }
}

function show_closed_by_response_html($start, $end) {
  $totals = array();
  $rows = fetch_ticket_data($start, $end);

  global $total_headings;

  foreach ($rows as $r) {
    $open_date = array_pop($r);
    $time = array_pop($r);

    if ($time > 1) $time = 'other';

    if (!array_key_exists($open_date, $totals)) $totals[$open_date] = array();

    if (!array_key_exists('open', $totals[$open_date]))
      $totals[$open_date]['open'] = 0;
    $totals[$open_date]['open']++;

    if (!array_key_exists($time, $totals[$open_date]))
      $totals[$open_date][$time] = 0;
    $totals[$open_date][$time]++;
  }

  /* 
    Empty the output buffer and disable output buffering.
  */
  if (ob_get_length()) ob_end_clean();
  header('Content-Type: text/application-csv');
  header('Content-Disposition: attachment; filename=resolution_metrics.csv');

  print join( ",", $total_headings );
  print "\n";

  ksort($totals);
  reset($totals);
  foreach ($totals as $day => $day_ary) {
    foreach (array('open', 0, 1, 'other') as $key)
      if (!array_key_exists($key, $day_ary)) $day_ary[$key] = 0;

    $data = array($day, $day_ary['open'], $day_ary[0], $day_ary[1], 
		  $day_ary['other']);

    print join( ",", array_map('csvify', $data) );
    print "\n";
  }
}

function csvify($str) {
  $ret = ereg_replace('"','""',$str);
  if (ereg(',',$ret)) {
    $ret = "\"$ret\"";
  }

  return $ret;
}
?>
