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

  $tcrm_fields = array (
    'status',
    'support_person_id',
    'escalated_to_person_id',
    'problem_id',
    'source_id',
  );

  $base_fields = array(
    't.browser',
    'p.last_name',
    'p.first_name',
    'p.company',
    'p.work_phone',
    'p.email',
    'p.title',
    't.account_id',
    'tm.info1',
    'tm.info2',
    't.mass_queue',
    't.use_help',
    'c.comments',
    't.additional_info',
    'tm.subject',
  );

  globalize_request_keys('save_option','logic','query_name','save_query', 
    'atts', 'this_crm_is_owner');

  $base_params = array();
  $att_params = array();

# check for provided query_id
#   if exists pull common format parameters
#   else read in params from GET/POST
# create SQL based on params
# run SQL
# create base result set
# create attribute result set
# merge 2 result sets if necessary
# redirect to proper page

  if (array_key_exists('query_id',$_REQUEST) && $_REQUEST['query_id']) {
    $query_id = $_REQUEST['query_id'];

    require_once 'lib/search_query.php';

    $search_query = new Search_Query ($dbi);

    $search_query->Get_Info ($query_id, $type);

    $sql_params = $search_query->Get('sql_params');

    if (!$sql_params) {
      print "Invalid saved query to retrieve.";
      return;
    }

    $unserial = unserialize( $sql_params );

    if ($unserial[version] != 3) {
      print "You will need to delete and recreate your query, sorry for the inconvenience.";
      return;
    }

    $base_params = $unserial['base_params'];
    $att_params = $unserial['att_params'];

    /* 
       Don't unnecessarily override save_option if it was previously set
       via CGI params. You can specifiy list from the "My Queries" page.
     */
    if (!$save_option) $save_option = $unserial[save_option];

    $logic = $unserial[logic];

  } else {

    if ($logic != 'or') $logic = 'and';

    $att_params = $atts;

    foreach ($tcrm_fields as $multi) {
      $base_params['tcrm_fields'][$multi] =
        array_key_exists($multi,$_REQUEST) ? $_REQUEST[$multi] : '';
    }

    foreach ($base_fields as $column) {
      list ($prefix, $search) = explode ('.', $column);
      $base_params['base_fields'][$column] =
        array_key_exists($search,$_REQUEST) ? $_REQUEST[$search] : '';
    }

    foreach (array ('created', 'updated', 'close') as $name) {
      foreach (array('start','end') as $s) {
        $key = "{$name}_{$s}_date";
        $base_params['dates'][$key] = array_key_exists($key,$_REQUEST) ?
                                        $_REQUEST[$key] : '';
      }
    }

    if (($save_query == 'query') and $query_name and (count($base_params) or
                                                      count($att_params))) {
      require_once '../../../lib/search_query.php';
  
      $search_query = new Search_Query ($dbi);
  
      $sql_params = array(
        version => 3,
        base_params => $base_params,
        att_params => $att_params,
        save_option => $save_option,
        logic => $logic,
      );
  
      $search_query->Add (array (
        query_name => $query_name,
        sql_params => serialize($sql_params),
        person_id => $REMOTE_USER,
      ));
    }
  }

  $params = array ();
  $sql = '';
  $tables_used = array('p'=>'','c'=>'');

  foreach ($tcrm_fields as $multi) {
    $values = $base_params['tcrm_fields'][$multi];

    if (!$values) continue;

    $sql .= " (";
    $minisql = '';

    foreach ($values as $v) {
      if (!strlen($v)) continue;
      $minisql .= "\n  tm.$multi = ? or ";
      $params[] = $v;
    }

    $sql .= substr($minisql, 0, strlen($minisql) - 3)."\n) $logic";
  }

  foreach ($base_params['base_fields'] as $column => $value) {
    if (!strlen($value)) continue;

    list ($prefix, $search) = explode ('.', $column);

    $tables_used[$prefix] = 1;
    $sql .= " lower($column) like ? $logic";
    $params[] = strtolower($value);
  }

  foreach (array ('created', 'updated', 'close') as $name) {

    list ($are_dates, $start, $end) = check_date_range (
      $base_params['dates']["{$name}_start_date"],
      $base_params['dates']["{$name}_end_date"]
    );

    if ($are_dates) {
      $to_date = to_date();

      $sql .= " tm.{$name}_date between $to_date and $to_date $logic";
      $params[] = $start.' 00:00:00';
      $params[] = $end.' 23:59:59';
    }
  }

  if ($sql) {
    $sql = substr ($sql, 0, strlen($sql) - strlen($logic));
  } elseif (!$att_params) {
    print "<font class=\"errors\">Nothing to search on</font>";
    return;
  }

  require_once '../../../lib/search_result.php';

  $which_crm_sql = " tm.crm_id = ? ";
  $which_crm_id = $REMOTE_USER_CRM_ID;

  if (!$this_crm_is_owner or $this_crm_is_owner == 'Y') {
    $which_crm_sql .= " and t.crm_id = tm.crm_id ";
  } elseif ($this_crm_is_owner == 'R') {
    $which_crm_sql .= " and not (t.crm_id = tm.crm_id) ";
  } elseif ($this_crm_is_owner == 'N') {
  }

  $result = new Search_Result ();

  if ($sql) {

    if ($which_crm_sql) {
      $sql .= " and $which_crm_sql ";
      $params[] = $which_crm_id;
    }

    $tables = '';
    if ($tables_used['p']) $tables .= ' inner join person p on t.user_person_id = p.person_id ';
    if ($tables_used['c']) $tables .= ' inner join comments c on tm.ticket_id = c.ticket_id ';

    ##
    ## order by should use tm.created_date, using ticket_id for now to keep
    ## sql simple so it works in many DBs
    ##
    $full_sql = "
     select distinct tm.ticket_id
       from ticket_crm_map tm
              inner join ticket t on tm.ticket_id = t.ticket_id
              $tables
      where $sql
order by tm.ticket_id
    ";

    $query_id = $result->Create_Result_Set ($full_sql, $params);
    if (!$query_id) {
      echo('search.php: <pre>' . htmlentities($result->error) . '</pre>');
      return;
    }

    $ticket_id = $result->First_ID ($query_id);
  }

  $quotes = array ();
  $binds = array ();

  if ($att_params) {
    $i = 0;
    foreach ($att_params as $att_id => $ary) {
      if ($logic != 'or') $i++;

      $same_att_sql = array ();

      foreach ($ary['option_id'] as $id) {

        if (array_key_exists ('ai', $att_params[$att_id])) {
          $search_ai = $att_params[$att_id]['ai'];

          ## if ai defined but no length assume they didn't type anything
          ## and didn't want to search on it
          if (strlen($search_ai)) {
	    $same_att_sql[] = "  (av$i.attribute_id = ? and av$i.member_id = ? and upper(av$i.additional_info) like ?)\n";
            $binds[] = $att_id;
	    $binds[] = $id;
            $binds[] = strtoupper($search_ai);
          }

        } else {
          $binds[] = $att_id;
	  $binds[] = $id;
	  $same_att_sql[] = "  (av$i.attribute_id = ? and av$i.member_id = ?)\n";
        }
      }

      if (count($same_att_sql)) {
        if (!array_key_exists($i,$quotes)) $quotes[$i] = '';
        if ($quotes[$i]) $quotes[$i] .= " $logic ";
        $quotes[$i] .= "(\n".join (' or ', $same_att_sql).")\n";
      }
    }
  }

  if ($quotes) {
    $quotes_sql = ' ( '.join (" $logic ", $quotes).' ) ';
    $more_sql = '';

    if ($which_crm_sql) {
      $quotes_sql = " and tm.crm_id = ?\n and ".$quotes_sql;
      $more_sql = " and t.crm_id = ? ";
      array_unshift( $binds, $which_crm_id, $which_crm_id );
    }

    $att_joins = '';
    $att_where = '';

    if ($logic == 'or') {
      $att_joins .= " inner join  attribute_values av$i on (t.ticket_id = av$i.id)\n";
    } else {
      foreach ($quotes as $i => $s) {
        $att_joins .= " inner join  attribute_values av$i on (t.ticket_id = av$i.id)\n";
      }
    }

##
## for the or case do 1 join and put all clauses or'ed together
##

    $full_sql = "
      select distinct tm.ticket_id
        from ticket_crm_map tm inner join (
               ticket t
$att_joins
             ) on (t.ticket_id = tm.ticket_id)
       where t.crm_id = tm.crm_id
             $more_sql
             $quotes_sql
    order by tm.ticket_id
    ";

    $query_id_two = $result->Create_Result_Set( $full_sql, $binds );
    $ticket_id_two = $result->First_ID ($query_id_two);
  } else {
    $query_id_two = $ticket_id_two = '';
  }

  if (!$ticket_id and !$ticket_id_two) {
    print "<font class=\"errors\">No Records Found</font>";
    return;
  }

  if ($query_id and $ticket_id and $query_id_two and $ticket_id_two) {
    ##
    ## merge into one result set
    ##
    $query_id = $result->Merge_Results ($query_id, $query_id_two, $logic);
    $ticket_id = $result->First_ID ($query_id);

  } elseif ($query_id_two and $ticket_id_two) {
    $query_id = $query_id_two;
    $ticket_id = $ticket_id_two;
  }

  if ($save_option == 'export') {
    $script = 'export';
  } elseif ($save_option == 'list') {
    $script = '../ticket/list';
  } else {
    $script = '../ticket/edit_ticket';
  }

  redirect ("$script?ticket_id=$ticket_id&query_id=$query_id", 1);

  function check_date_range ($start='', $end='') {
    $ret = 0;

    foreach (array ('start', 'end') as $date) {
      if (ereg('^.{4}/.{2}/.{2}$', $$date)) $ret = 1;
    }

    if (!$start) $start = '1900/01/01';
    if (!$end)   $end   = '2100/01/01';

    return array ($ret, $start, $end);
  }
?>
