<?/*
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 'base_object.php';

class Search_Result extends Base_Object {
  function Search_Result () {
    global $dbi;
    $this->db = &$dbi;

    $this->Set_CRM ();
  }

  function Set_CRM ($crm_id='') {
    if (!$crm_id) $crm_id = $this->Current_CRM ();
    if (!$crm_id) {
	$this->error = 'Search_Result::Set_CRM(): Current_CRM returned 0!';
	return;
    }

    $this->crm_id = $crm_id;

    return 1;
  }

  function Get_CRM () {
    if ($this->crm_id) return $this->crm_id;

    if (!$this->Set_CRM ()) {
	$this->error = 'Search_Result::Get_CRM(): ' . $this->error;
	return;
    }

    return $this->crm_id;
  }

  function Merge_Results ($qid, $qid2, $logic='') {
    if ($logic == 'and') {
      $sql = '
        select distinct sr.ticket_id
          from search_results sr
                 inner join search_results sr2
                   on (sr.ticket_id = sr2.ticket_id)
         where sr.sr_query_id = ?
           and sr2.sr_query_id = ?
      ';
    } else {
      $sql = '
        select distinct ticket_id
          from search_results
         where sr_query_id in (?, ?)
      ';
    }

    return $this->Create_Result_Set ($sql, array ($qid, $qid2));
  }

  function Create_Result_Set ($sql, $params) {
    $query_id = $this->Create_PK ($this->Person_Logged_In(), $this->Get_CRM());
    if (!$query_id) {
	$this->error = 'Search_Result::Create_Result_Set(): '
	    . $this->error;
	return;
    }

    $results = $this->Get_Resulting_Ticket_IDs( $sql, $params );
    if (is_null($results)) {
      $this->error = 'Search_Result::Create_Result_Set(): ' . $this->error;
      return;
    }

    $ok = $this->Create_Search_Result_Records( $query_id, $results );

    if (!$ok) {
      $this->error = 'Search_Result::Create_Result_Set(): ' . $this->error;
      return;
    } else {
      return $query_id;
    }
  }

  function Get_Resulting_Ticket_IDs( $sql,$params ) {
    #print "<pre>";
    #print_r(array('sql' => $sql, 'params' => $params));
    #print "</pre>";
    #exit;

    $res = $this->db->getAll( $sql, $params );
    if (!DB::isError($res)) return $res;

    $this->error = 'Search_Result::Get_Resulting_Ticket_IDs(): '
      . $res->getMessage() . "\n" . $res->getUserInfo();
    return;
  }

  function Create_Search_Result_Records( $query_id, $tickets ) {
    $h = $this->db->prepare ('
      insert into search_results (
        sr_query_id, ticket_id, order_id
      ) values (
        ?, ?, ?
      )
    ');

    foreach ($tickets as $r) {
      $oid = $this->db->nextId('order_id');
      $res = $this->db->execute($h, array($query_id, $r[0], $oid));
      if (DB::isError($res)) {
	$this->error = 'Search_Result::Create_Search_Result_Records(): '
	  . $res->getMessage() . "\n" . $res->getUserInfo();
	return;
      }
    }

    return true;
  }

  function Create_PK ($pid, $crm_id) {
    $qid = $this->db->nextId ('sr_query_id');

    $h = $this->db->prepare ('
      insert into search_result_queries (sr_query_id, crm_id, person_id) values (?, ?, ?)
    ');

    $ok = $this->db->execute( $h, array($qid,$crm_id,$pid) );

    if (DB::isError($ok)) {
      return 0;
    } else {
      return $qid;
    }
  }

  function First_ID ($query_id) {
    $h = $this->db->prepare ('
      select ticket_id
        from search_results
       where sr_query_id = ?
    order by order_id asc
    ');
    $res = $this->db->execute ( $h, array($query_id) );
    if (DB::isError($res)) {
       $this->error = $res->getMessage();
       print "first: ".$res->getMessage();
       return;
    }
    $r = $res->fetchRow ();

    return $r[0];
  }

  function Total_Results ($query_id) {
    $h = $this->db->prepare ('
      select count(*)
        from search_results
       where sr_query_id = ?
    ');
    $res = $this->db->execute( $h, array($query_id) );
    if (DB::isError($res)) {
       $this->error = $res->getMessage();
       print "total: ".$res->getMessage();
       return;
    }
    $r = $res->fetchRow ();

    return $r[0];
  }

  function Order_ID ($tid, $query_id) {
    $h = $this->db->prepare ('
      select order_id
        from search_results
       where sr_query_id = ?
         and ticket_id = ?
    ');
    $res = $this->db->execute( $h, array($query_id,$tid) );
    if (DB::isError($res)) {
       $this->error = "Order_ID: ".$res->getMessage();
       return;
    }
    $r = $res->fetchRow ();

    return $r[0];
  }

  function Get_ID ($query_id, $curr_id='', $next='1') {
    if ($next < 0) {
      $sort = 'desc';
      $sign = '<';
    } else {
      $sort = 'asc';
      $sign = '>';
    }

    if (!$curr_id) {
      $sql = "
        select ticket_id
          from search_results
         where sr_query_id = ?
      order by order_id $sort
      ";
      $binds = array($query_id);

    } else {
      $curr_order_id = $this->Order_ID ($curr_id, $query_id);
  
      $sql = "
        select ticket_id
          from search_results
         where sr_query_id = ?
           and order_id $sign ?
      order by order_id $sort
      ";

      $binds = array($query_id, $curr_order_id);
    }

    $h = $this->db->prepare( $sql );
    $res = $this->db->execute( $h, $binds );

    if (DB::isError($res)) {
       $this->error = $res->getMessage();
       return;
    }

    $r = false;

    if ($sort == 'desc') {
      for ($i= (real) $next; $i<0; $i++) {
        $r = $res->fetchRow();
      }
    } else {
      for ($i= (real) $next; $i>0; $i--) {
        $r = $res->fetchRow();
      }
    }

    if ($r && $r[0]) {
      return $r[0];
    } else {
      return $this->First_ID ($query_id);
    }
  }

  function Current_Ticket ($tid, $qid) {
    if ($tid == $this->First_ID ($qid)) return 1;

    $h = $this->db->prepare ('
      select count(*)
        from search_results
       where sr_query_id = ?
         and ticket_id <= ?
    ');
    $res = $this->db->execute( $h, array($qid,$tid) );
    if (DB::isError($res)) {
       $this->error = $res->getMessage();
       return;
    }

    $r = $res->fetchRow ();

    return $r[0];
  }

  function Delete_by_Ticket_ID ($tid, $crm_id='') {
    if (!$crm_id) $crm_id = $this->Get_CRM ();
    if (!$crm_id or !$tid) return 0;

    $h = $this->db->prepare ('
      delete from search_results
            where ticket_id = ?
    ');
    $ok = $this->db->execute ($h, array($tid));

    if (DB::isError($ok)) {
       $this->error = 'Search_Result::Delete_by_Ticket_ID(): ' 
	. $ok->getMessage() . "\n" . $ok->getUserInfo();
      return;
    }

     return true;
  }

  function List_Query_Tickets ($qid, $crm_id='') {
    if (!$crm_id) $crm_id = $this->Get_CRM ();

    $df = date_format('tcm.created_date', '%b %d %Y');
    $sql = "
      select tcm.ticket_id,
             tcm.status,
             p.first_name,
             p.last_name,
             p.email,
             p.company,
             tcm.created_date as created_tstamp,
             tcm.problem_id,
             tcm.source_id,
             t.account_id,
             tcm.info1,
             tcm.info2,
             tcm.support_person_id,
             tcm.escalated_to_person_id,
             t.mass_queue,
             s.source,
             pt.problem_type,
             tcm.subject,
             t.user_person_id,
             ps.last_name as support_last_name,
             ps.first_name as support_first_name,
             pe.last_name as escalated_last_name,
             pe.first_name as escalated_first_name,
             $df as created_date,
             p.work_phone,
             p.home_phone,
             p.pager_num,
             p.cell_phone,
             p.title
        from search_results sr
               inner join ticket_crm_map tcm on (sr.ticket_id = tcm.ticket_id)
                 inner join ticket t on (tcm.ticket_id = t.ticket_id)
                   inner join person p on (t.user_person_id = p.person_id)
                 inner join person ps on (tcm.support_person_id = ps.person_id)
                 inner join person pe on (tcm.escalated_to_person_id = pe.person_id)
                 inner join problem_type pt on (tcm.problem_id = pt.problem_id)
                 inner join source s on (tcm.source_id = s.source_id)
       where tcm.crm_id = ?
         and sr.sr_query_id = ?
    order by t.created_date
    ";

    return $this->db->getAll($sql, array($crm_id, $qid), DB_FETCHMODE_ASSOC); 
  } 
} 
?>
