<?php
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * 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, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/

require_once('include/SearchForm/SearchForm.php');

class EcmCallsSearchForm extends SearchForm {

    function EcmCallsSearchForm($module, &$seedBean, $tpl = null) { 
		parent::SearchForm($module, $seedBean, $tpl);
		
		/*
		global $app_strings;
		$this->tabs[] = array('title'  => $app_strings['LNK_SAVED_VIEWS'],
							  'link'   => $module . '|saved_views',
							  'key'    => $module . '|saved_views');
		*/
    }

	function setup() {
		parent::setup();
		
	  	//date settings
		global $timedate;
		$time_format = $timedate->get_user_time_format();
		$date_format = $timedate->get_cal_date_format();
		$time_separator = ":";
		if(preg_match('/\d+([^\d])\d+([^\d]*)/s', $time_format, $match)) {
		   $time_separator = $match[1];
		}
		$t23 = strpos($time_format, '23') !== false ? '%H' : '%I';
		if(!isset($match[2]) || $match[2] == '') {
		 $this->xtpl->assign("CALENDAR_FORMAT",$date_format . ' ' . $t23 . $time_separator . "%M");
		} else {
		  $pm = $match[2] == "pm" ? "%P" : "%p";
		  $this->xtpl->assign("CALENDAR_FORMAT",$date_format . ' ' . $t23 . $time_separator . "%M" . $pm);
		}

		$this->xtpl->assign("TIME_FORMAT",$time_format);
		
		global $app_list_strings, $mod_strings;
		$parents = array(
			'' => '',
			'Contacts' => $app_list_strings['moduleList']['Contacts'],
			'Accounts' => $app_list_strings['moduleList']['Accounts'],
			'Users' => $mod_strings['LBL_PARENT_FROM'],//$app_list_strings['moduleList']['Users'],
		);
		
			if(isset($_REQUEST['calldate_basic']) && $_REQUEST['calldate_basic'] != '') {
				$_REQUEST['call_date_from_basic'] = '';
				$_REQUEST['call_date_to_basic'] =  '';
			}
			
			$this->xtpl->assign("PARENT_FROM_BASIC",get_select_options_with_id($parents, $_REQUEST['parent_from_basic']));
			$this->xtpl->assign("PARENT_TO_BASIC",get_select_options_with_id($parents, $_REQUEST['parent_to_basic']));
	
			if(isset($_REQUEST['call_date_from_basic']) && strlen($_REQUEST['call_date_from_basic'])>6) $this->xtpl->assign("CALLDATEFROMBASIC",$_REQUEST['call_date_from_basic']);
			if(isset($_REQUEST['call_date_to_basic']) && strlen($_REQUEST['call_date_to_basic'])>6) $this->xtpl->assign("CALLDATETOBASIC",$_REQUEST['call_date_to_basic']);
			
			global $app_list_strings;
			$this->xtpl->assign("CALLDATE_BASIC",get_select_options_with_id($app_list_strings['search_date_type_dom'], $_REQUEST['calldate_basic']));	



			if(isset($_REQUEST['calldate_advanced']) && $_REQUEST['calldate_advanced'] != '') {
				$_REQUEST['call_date_from_advanced'] = '';
				$_REQUEST['call_date_to_advanced'] =  '';
			}
			
			$this->xtpl->assign("PARENT_FROM_ADVANCED",get_select_options_with_id($parents, $_REQUEST['parent_from_advanced']));
			$this->xtpl->assign("PARENT_TO_ADVANCED",get_select_options_with_id($parents, $_REQUEST['parent_to_advanced']));
			
			
			$json = getJSONobj();
			$pio = array (
				'ids' => array (
					'Accounts' => $this->getParentsIds('Accounts',true),
					'Contacts' => $this->getParentsIds('Contacts',true),
					'Users' => $this->getParentsIds('Users',true),				
				),
			);
			$this->xtpl->assign("PARENT_IDS_OBJECTS", str_replace('&quot;', '\"', $json->encode($pio)));
			
			$this->xtpl->assign("PARENT_FROM_ID_ADVANCED",get_select_options_with_id($this->getParentsIds($_REQUEST['parent_from_advanced'],true),$_REQUEST['parent_from_id_advanced']));
			$this->xtpl->assign("PARENT_TO_ID_ADVANCED",get_select_options_with_id($this->getParentsIds($_REQUEST['parent_to_advanced'],true),$_REQUEST['parent_to_id_advanced']));
			
			
	
			if(isset($_REQUEST['call_date_from_advanced']) && strlen($_REQUEST['call_date_from_advanced'])>6) $this->xtpl->assign("CALLDATEFROMADVANCED",$_REQUEST['call_date_from_advanced']);
			if(isset($_REQUEST['call_date_to_advanced']) && strlen($_REQUEST['call_date_to_advanced'])>6) $this->xtpl->assign("CALLDATETOADVANCED",$_REQUEST['call_date_to_advanced']);
			
			global $app_list_strings;
			$this->xtpl->assign("CALLDATE_ADVANCED",get_select_options_with_id($app_list_strings['search_date_type_dom'], $_REQUEST['calldate_advanced']));	

			$this->xtpl->assign("CURRENT_USER_ONLY_ADVANCED",((isset($_REQUEST['current_user_only_advanced']) && $_REQUEST['current_user_only_advanced']=="on")?"checked":""));

			$this->xtpl->assign("IN_OUT_ADVANCED",((isset($_REQUEST['in_out_advanced']) && $_REQUEST['in_out_advanced']=="on")?"checked":""));
	}

	function getParentsIds($module,$empty=false) {
		
		$arr = array();
		//if($empty) $arr[''] = ' ';
		
		$where = '';
		switch ($module) {
			case "Users": $what = " `id`, CONCAT(IFNULL(CONCAT(`first_name`,' '),''), `last_name`) as name "; $where = " `id` <> '1' AND ";
						  $order_by = " `name` ASC";
				break;
			case "Contacts": $what = " `id`, CONCAT(IFNULL(CONCAT(`first_name`,' '),''), `last_name`) as name ";
						  $order_by = " `name` ASC";
				break;
			case "Accounts": $what = " `id`, `name` "; 
						  $order_by = " `name` ASC";
				break;
		}

		$query = "SELECT $what FROM `".strtolower($module)."` WHERE $where `deleted`='0' ORDER BY ".$order_by;
		$result = $GLOBALS['db']->query($query);
		
		if($result) 
			while($row = $GLOBALS['db']->fetchByAssoc($result)) $arr[$row['id']] = $row['name']; 
		
		return $arr;
		
	}

    function generateSearchWhere($add_custom_fields = false, $module='') {
        
		//var_dump($_REQUEST);
		
		global $timedate;
        $values = $this->searchFields;
        
        $where_clauses = array();
        $like_char = '%';
        $table_name = $this->bean->object_name;

        foreach($this->searchFields as $field=>$parms) {
			$customField = false;
            // Jenny - Bug 7462: We need a type check here to avoid database errors
            // when searching for numeric fields. This is a temporary fix until we have 
            // a generic search form validation mechanism.
            $type = (!empty($this->bean->field_name_map[$field]['type']))?$this->bean->field_name_map[$field]['type']:'';
        	if(!empty($this->bean->field_name_map[$field]['source']) && $this->bean->field_name_map[$field]['source'] == 'custom_fields'){
                $customField = true;	
              }
           
            if ($type == 'int') {
                if (!empty($parms['value'])) {
                    $tempVal = explode(',', $parms['value']);
                    $newVal = '';
                    foreach($tempVal as $key => $val) {
                        if (!empty($newVal))    
                            $newVal .= ',';
                        if(!empty($val) && !(is_numeric($val))) 
                            $newVal .= -1;
                        else 
                            $newVal .= $val;
                    }
                    $parms['value'] = $newVal;
                }
            }
            // do not include where clause for custom fields with checkboxes that are unchecked
            elseif($type == 'bool' && empty($parms['value']) && $customField) {
                continue; 
            }
            elseif($type == 'bool' && !empty($parms['value'])){
            	if ($parms['value'] == 'on'){
            		$parms['value'] = 1;
            	}
            }
			
            if(isset($parms['value']) && $parms['value'] != "") {
                $operator = 'like';
                if(!empty($parms['operator'])) {
                    $operator = $parms['operator'];
                }
                
                if(is_array($parms['value'])) {
                    $field_value = '';
                    
                    // If it is a custom field of mutliselect we have to do some special processing
                    if($customField && !empty($this->bean->field_name_map[$field]['isMultiSelect']) && $this->bean->field_name_map[$field]['isMultiSelect']) { 
	                    $operator = 'custom_enum';
	                    $db_field = $this->bean->table_name .  "_cstm." . $field;
	                    foreach($parms['value'] as $key => $val) {
	                        if($val != ' ' and $val != '') {
	                               $qVal = $GLOBALS['db']->quote($val);
	                               if (!empty($field_value)) {
	                                   $field_value .= ' or ';
	                               }
	                               $field_value .= "$db_field like '$qVal' or $db_field like '%$qVal^%' or $db_field like '%^$qVal%' or $db_field like '%^$qVal^%'";
	                        }                            
	                    }               
                    } else { 
                        $operator = 'in';
	                    foreach($parms['value'] as $key => $val) {
	                        if($val != ' ' and $val != '') {
	                            if (!empty($field_value)) {
	                                $field_value .= ',';
	                            }
	                            $field_value .= "'" . $GLOBALS['db']->quote($val) . "'";
	                        }
	                    }
                    }
                }
                else {
                    $field_value = $GLOBALS['db']->quote($parms['value']);
                }
                
                //set db_fields array.
                if(!isset($parms['db_field'])) {
                    $parms['db_field'] = array($field);
                }
                
                if(isset($parms['my_items']) and $parms['my_items'] == true) {
                    global $current_user;
                    $field_value = $GLOBALS['db']->quote($current_user->id);
                    $operator = '=';
                }
                    
                $where = '';
                $itr = 0;
                if($field_value != '') {
                    foreach ($parms['db_field'] as $db_field) {
                    	
                        if (strstr($db_field, '.') === false) {
                        	if(!$customField){
                            	$db_field = $this->bean->table_name .  "." . $db_field;
                        	}else{
                        		$db_field = $this->bean->table_name .  "_cstm." . $db_field;	
                        	}
                           
                        }

                        if($type == 'date') {
                           // Collin - Have mysql as first because it's usually the case
                           // The regular expression check is to circumvent special case YYYY-MM
                           if($GLOBALS['db']->dbType == 'mysql') {
                                 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
                                    $field_value = $timedate->to_db_date($field_value, false);
                                    $operator = '=';  
                                 } else {
                                    $operator = 'db_date';	
                                 }                          	
                           } else if($GLOBALS['db']->dbType == 'oci8') {
                            	 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
                                    $field_value = $timedate->to_db_date($field_value, false);
                                    $field_value = "to_date('" . $field_value . "', 'YYYY-MM-DD hh24:mi:ss')";
                            	 }
                                 $operator = 'db_date';                           	
                           } else if($GLOBALS['db']->dbType == 'mssql') {
                                 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
                                    $field_value = "Convert(DateTime, '".$timedate->to_db_date($field_value, false)."')";
                                 }
                                 $operator = 'db_date';                            	
                           } else {
                           	     $field_value = $timedate->to_db_date($field_value, false);
                           	     $operation = '=';
                           }
                        } 
                        
                       
                        if($GLOBALS['db']->dbType == 'oci8' && isset($parms['query_type']) && $parms['query_type'] == 'case_insensitive') {
                              $db_field = 'upper(' . $db_field . ")";
                              $field_value = strtoupper($field_value);	 
                        } 
                        	
                        $itr++;
                        if(!empty($where)) {
                            $where .= " OR ";
                        }

                        switch(strtolower($operator)) {
                        	case 'subquery':
                        		$where .= "{$db_field} IN ({$parms['subquery']} '{$field_value}%')";
    	                    	break;                            
                            case 'like':
                                $where .=  $db_field . " like '".$field_value.$like_char."'";
                                break;
                            case 'in':
                                $where .=  $db_field . " in (".$field_value.')';
                                break;
                            case '=':
                                $where .=  $db_field . " = '".$field_value ."'";
                                break;  
                            case 'db_date':
                                if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
                                  $where .=  $db_field . " = ". $field_value;
                                } else {
                                  // Create correct date_format conversion String
                                  if($GLOBALS['db']->dbType == 'oci8') {
                                  	$where .= db_convert($db_field,'date_format',array("'YYYY-MM'")) . " = '" . $field_value . "'";	
                                  } else {
                                  	$where .= db_convert($db_field,'date_format',array("'%Y-%m'")) . " = '" . $field_value . "'";	
                                  }
                                }
                                break;
                        }
                    }
                }
                if(!empty($where)) {
                    if($itr > 1) {
                        array_push($where_clauses, '( '.$where.' )');
                    } 
                    else {
                        array_push($where_clauses, $where);
                    }                   
                }
            }
        }
       
        return $where_clauses;
    }

}


?>