<?php
/**********************************************************
* Source Copyright 2014 Author                            *
* Unauthorized reproduction is not allowed                *
* Author: JPK Software Solutions Pvt. Ltd.                *
* Email: sales@visionhelpdesk.com                         *
* Owner: www.visionhelpdesk.com                           *
**********************************************************/

if(!defined('_VIS_')) die('Error: Call from undefined function');
class ticket { 
    var $error;

   function ticket_display($operation, $and_conditions, $or_conditions, $filter='', $page=0, $sort_by='') {
	   $database=new class_database(); 
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        if($and_conditions!='' && count($and_conditions)!=0) {
            $filter="(";
            foreach($and_conditions as $key => $value) {
                if(!strstr($key, '.')) $filter.=VIS_TABLE_PREFIX.'ticket.';
                $filter.=$key.$value." and ";
            }
            $filter=substr($filter, 0, -4);
            $filter.=") and ";
        }
        if($or_conditions!="" && count($or_conditions)!=0) {
            $filter.="(";
            foreach($or_conditions as $key => $value) {
                if(!strstr($key, '.')) $filter.=VIS_TABLE_PREFIX.'ticket.';
                $filter.=$key.$value." or ";
            }
            $filter=substr($filter, 0, -3);
            $filter.=") and ";
        }
        if(isset($operation['vis_client_id']) && $operation['vis_client_id']!= '')
        {
			$filter.= ' and '.VIS_TABLE_PREFIX.'ticket.client_id='.$operation['vis_client_id'];
		}else if (isset($operation['vis_group_id']) && $operation['vis_group_id'] != '') {
			$operation['view_title'] = $operation['vis_group_name'];
            include_once(VIS_PATH_CLASS . VIS_CLASS_PREFIX . 'client.php');
            $object = new class_client($database);
            $filter = VIS_TABLE_PREFIX . 'client.parent_id=0 and ' . VIS_TABLE_PREFIX . 'client.group_id=' . $operation['vis_group_id'];
            list($client_info, $client_details) = $object->get_client($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);			
            if ($client_details != -1) {
                for ($j = 0; $j < count($client_details); $j++) {
                    if ($client_id == '')
                            $client_id = $client_details[$j]['client_id'];
                    else
                            $client_id = $client_id . ',' . $client_details[$j]['client_id'];
                }
				if($operation['vis_operation']=='filter_ticket_group' || $operation['ticket_operation']=='filter_ticket_group') 
					$filter ='  (' . VIS_TABLE_PREFIX . 'ticket.client_id IN (' . $client_id . ' ) ) and is_deleted=0 and draft_id=0 and status_id!=3 ';
				else 
	                $filter.=' and (' . VIS_TABLE_PREFIX . 'ticket.client_id IN (' . $client_id . ' ) ) and is_deleted=0 and draft_id=0';
            }
        }else { 	$filter.=(isset($operation['filter_id']) && $operation['filter_id'] == 21) ? ' and draft_id != 0 ' : ((isset($operation['vis_draft']) && $operation['vis_draft'] == 1) ? ' and draft_id='.VIS_STAFF_ID : ' and draft_id=0');
			
        }
        if(isset($operation['vis_filter_array']) && $operation['vis_filter_array']!='')
        {
			$filter=VIS_TABLE_PREFIX.'ticket.ticket_id in ('.$operation['vis_filter_array'].')';
		}
        $ticket_object=new class_ticket($database);         
        $staff=new class_staff($database);
        $temp=$staff->get_ticket_view(VIS_STAFF_ID ,VIS_LOCATION_AREA);
        list($view_info, $view_details)=$temp;
        $limit=($page*$view_info['page_count']).','.$view_info['page_count'];
        if($sort_by=='') { // && $view_info['sort_by1']!='' && $view_info['sort_by2']!='' && $view_info['sort_by3']!='') {
            if($view_info['sort_by1']!='') $sort_by.=$view_info['sort_by1'].' '.$view_info['sort_order1'].',';
            if($view_info['sort_by2']!='') $sort_by.=$view_info['sort_by2'].' '.$view_info['sort_order2'].',';
            if($view_info['sort_by3']!='') $sort_by.=$view_info['sort_by3'].' '.$view_info['sort_order3'].',';
            $sort_by=substr($sort_by,0,-1);
        }
        $conditions=array();
      
        $export_csv='';        
        if($operation['vis_operation']=='filter_ticket' || $operation['vis_operation']=='filter_ticket_group' || $operation['vis_operation']=='filter_queue_ticket' || $operation['vis_operation']=='tag_search' || $operation['vis_operation']=='search_label_tickets' || ($operation['vis_operation']=='apply_filter' && ($operation['ticket_operation']=='filter_ticket' || $operation['ticket_operation']=='filter_queue_ticket' || $operation['ticket_operation']=='filter_ticket_group' ))){
            for($i=0;$i<count($view_details);$i++) {
                $conditions[$i]=$view_details[$i]['tab_name'];
            }
        } 
        $temp1=$ticket_object->get_ticket($filter, $limit, $page, $sort_by, VIS_STAFF_ID, VIS_LOCATION_AREA,$export_csv,$conditions,$operation['filter_id']);
        list($ticket_info, $ticket_details)=$temp1;

		$label_details='';	
			$link_dis=0;
		$label_dis=0;
		foreach($view_details as $v){
				if($v['tab_name']=='link'){$link_dis=1;}
				if($v['tab_name']=='label'){$label_dis=1;}
			}
			if($link_dis==1 || $label_dis==1){
			for($i=0;$i<count($ticket_details);$i++){
			if($link_dis==1){
				$link_data=array('vis_ticket_id'=>$ticket_details[$i]['ticket_id'], 'case'=>1);	
							$link = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
							$ticket_details[$i]['link_present']=($link == -1)?0:1;
			}
			if($label_dis==1){
				$label_details[$i] = $ticket_object->get_ticket_labels($ticket_details[$i]['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
			//$ticket_lock[$i] = $ticket_object->get_ticket_lock($ticket_details[$i]['ticket_id'], 'staff_id!='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
}
        /*foreach($view_details as $v){
            if($ticket_details!=-1){			
                for($i=0;$i<count($ticket_details);$i++){
					switch($v['tab_name']){
						case 'link': 	
							$link_data=array('vis_ticket_id'=>$ticket_details[$i]['ticket_id'], 'case'=>1);	
							$link = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
							$ticket_details[$i]['link_present']=($link == -1)?0:1;
							break;
						case 'label':	
							$label_details[$i] = $ticket_object->get_ticket_labels($ticket_details[$i]['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
							break;
						default: // this case will execute at last
							$ticket_lock[$i] = $ticket_object->get_ticket_lock($ticket_details[$i]['ticket_id'], 'staff_id!='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
                }
            }
        }*/
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
            $database=new class_database();
            $setting_obj=new class_setting($database);
			for($i=0;$i<count($ticket_details);$i++){
						$filter='parent_id='.$ticket_details[$i]['ticket_id'].' and attach_type=0';
						$attach_ci_details = $setting_obj->get_attach_relation_list($filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
						$ticket_details[$i]['ci_present']=($attach_ci_details == -1)?0:count($attach_ci_details);
				}
       $view_info['page_count']=($ticket_info['total']==0)?0:ceil($ticket_info['total']/$view_info['page_count']);
       $ticket_info['ticket_count']=(!$ticket_details || $ticket_details==-1)?0:count($ticket_details);
       $ticket_info['page']=$page;//*$view_info['page_count'];
       $view_info['view_count']=count($view_details); 
       $view_info['view_title']=$operation['view_title'];
         if( isset($operation['tag_count']) && $operation['tag_count'] == 0) {
			   $operation['view_title']=$operation['tag_name'];
			   $ticket_info['total']=$operation['tag_count'];
			    $ticket_details = -1  ;
		 }
        if(isset($operation['vis_status_id']) && is_numeric($operation['vis_status_id']) && isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) {
            $view_info['vis_operation']='filter_queue_ticket';
            $operation['filter_id']=$operation['vis_status_id'].'-'.$operation['vis_department_id'];
        }
        else if (isset($operation['vis_group_id']) && $operation['vis_group_id'] != '') $view_info['vis_operation']='filter_ticket_group';
        else $view_info['vis_operation']='filter_ticket'; 
		if(VIS_LOCATION_AREA==0) {
				echo get_xml($ticket_details, 'ticket_details');
				return true;
         }
         else {
			//$counts=$ticket_object->get_quick_counts('', VIS_STAFF_ID, VIS_LOCATION_AREA);
			if((isset($operation['vis_filter_enable']) && $operation['vis_filter_enable']==1) || (isset($operation['vis_page']) && is_numeric($operation['vis_page']))){
				ob_start();
				include(VIS_PATH_TEMPLATE.'ticket_list.php');
				$tkt_list = ob_get_clean();
				ob_end_flush();
				$select='';
				//$select = "<select name=\"pageing\" class=\"form-control input-sm selectpicker pull-right paging v-middle\" onchange=\"vis_apply_filter(this.value, '".$operation['vis_filter_id']."');\">";
				$paging_list='';
			//	for($i=0;$i<$view_info['page_count'];$i++)
				//	$select.='<option value="'.$i.'" '.(($ticket_info['page']==$i)?'selected="selected"':'').'>'.($i+1).'</option>';
				//$select.="</select><div class=\"text-muted pull-right label_page\">".$vis_language['TXTPAGE'].":</div>";		
				echo json_encode( array('total_cnt'=>$ticket_info['total'], 'paging'=>$select, 'list'=> $tkt_list, 'filter_id'=>$operation['vis_filter_id'],'total_pages'=>$view_info['page_count'],'total_tickets'=>(($ticket_details!=-1)?count($ticket_details):0) ));
			}
			else{
				//--filter list data
				if(isset($operation['vis_action'])) $options=parse_form_array($operation['vis_action']);
				else $options=$operation;
				include(VIS_PATH_TEMPLATE.'ticket.php');
			}
		}
        $database->database_disconnect();
        return true;
    }

    function view_ticket($operation) {
		
    	global $vis_language;
		
	   $data= isset($operation['vis_action']) && $operation['vis_action']!='' ? parse_form_array($operation['vis_action']) : $operation;
		if($data['search_subject']!='') $and_operations['subject like "%'] = $data['search_subject'].'%"';
		if($data['search_department']!='')$and_operations['department_id="'] = $data['search_department'].'"';
		if($data['search_flag']!='')$and_operations['flag_id="'] = $data['search_flag'].'"';
		if($data['search_item']!='')$and_operations['item_id="'] = $data['search_item'].'"';
		if($data['search_level']!='')$and_operations['level_id="'] = $data['search_level'].'"';
		if($data['search_location']!='')$and_operations['location_id="'] = $data['search_location'].'"';
		//if($data['search_owner']!='')$and_operations['owner="'] = $data['search_owner'].'"';
		if($data['search_priority']!='')$and_operations['priority_id="'] = $data['search_priority'].'"';
		if($data['search_status']!='')$and_operations['status_id="'] = $data['search_status'].'"';
		if($data['search_subcategory']!='')$and_operations['subcategory_id="'] = $data['search_subcategory'].'"';
		if($data['search_type']!='')$and_operations['type_id="'] = $data['search_type'].'"';
		if($data['search_category']!='')$and_operations['category_id="'] = $data['search_category'].'"';
		
		 if($and_operations!='' && count($and_operations)!=0) {
            $filter="(";
            foreach($and_operations as $key => $value) {
                if(!strstr($key, '.')) $filter.=VIS_TABLE_PREFIX.'ticket.';
                $filter.=$key.$value." and ";
            }
            $filter=substr($filter, 0, -4);
            $filter.=") and ";
        }
        if($or_operations!="" && count($or_operations)!=0) {
            $filter.="(";
            foreach($or_operations as $key => $value) {
                if(!strstr($key, '.')) $filter.=VIS_TABLE_PREFIX.'ticket.';
                $filter.=$key.$value." or ";
            }
            $filter=substr($filter, 0, -3);
            $filter.=") and ";
        }
		
		                        if($data['search_staff']!='' && $data['search_staff']==0){
							    $filter .= VIS_TABLE_PREFIX.'ticket.ticket_id NOT IN(select ticket_id from '.VIS_TABLE_PREFIX.'ticket_assign where owner_id!='.$data['search_staff'].') and ';
								} 
								else if($data['search_staff']!=''){
                                $filter .= VIS_TABLE_PREFIX.'ticket.ticket_id IN(select ticket_id from '.VIS_TABLE_PREFIX.'ticket_assign where owner_id='.$data['search_staff'].') and ';
								} 
       //print_r($filter);
	   if(IS_LOGIN) {
			if(isset($_REQUEST['hash'])) $operation['message']='<div class="vis_message">#'.$_REQUEST['hash'].' - '.$vis_language['MSGSUCCOTKT'].'</div>';
			else if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
			if(VIS_LOCATION_AREA == 1 && $operation['vis_operation']!='ticket_reply')
			{	
				$action=explode("/", $operation['vis_action']);
				if(count($action) > 3 && $action[2] !='view-ticket')
				{
					$operation['message']='<div class="vis_message">#'.$action[3].' - '.$vis_language['MSGSUCCOTKT'].'</div>';
				}
				if($action[2] == 'view-ticket') $operation['vis_status'] = $action[3];
			}
			}
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $database=new class_database();
            
            $ticket_object=new class_ticket($database);
			$setting_obj=new class_setting($database);
            $client_object=new class_client($database);
												
		$module_setting=$setting_obj->get_module_setting('domain_id='.VIS_DOMAIN.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
	   
        $domains = $ticket_object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
		
		$domain_id = (VIS_LOCATION_AREA == 1 && VIS_SATELLITE_HELPDESK == 3 && isset($operation['dom_id'])) ? $operation['dom_id'] : VIS_DOMAIN;
		
		 $dep_filter=(VIS_LOCATION_AREA==1)?(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1 and access_type=0 and '.VIS_TABLE_PREFIX.'department.domain_id='.$domain_id):(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1');
		 
		  if(VIS_LOCATION_AREA==1) {
			  
              if((defined('VIS_CLIENT_ID') && VIS_CLIENT_ID>0) ||  $operation['vis_client_id']>0){
				
                $userid=(VIS_CLIENT_ID>0)?VIS_CLIENT_ID:$operation['vis_client_id'];
				
                list($client_info, $client)=$client_object->get_client('client_id='.$userid, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
				 $client=$client[0];
               //$userid=VIS_CLIENT_ID;
                if(VIS_LOCATION_AREA==1){
					if($client['department_access']!=0 && $client['parent_id']==0)
						$dep_filter.=' and '.VIS_TABLE_PREFIX.'department.department_id in ('.$client['department_access'].') ';
					elseif($client['parent_id']!=0){
						list($parentclient_info, $parentclient)=$client_object->get_client('client_id='.$client['parent_id'], '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
						if($parentclient[0]['department_access']!=0)
						$dep_filter.=' and '.VIS_TABLE_PREFIX.'department.department_id in ('.$parentclient[0]['department_access'].') ';
					}
				}
            }
            else {
			$userid=0;}
		$departments=$ticket_object->get_department($dep_filter, VIS_STAFF_ID, VIS_LOCATION_AREA, '');
	    }  
        else {
	    $departments=$this->get_properties('get_departments', '');
		}
		if(isset($operation['departmentid'])) { $departmentid = $operation['departmentid']; $department_get= $operation['departmentid'];}
        else $departmentid = $departments[0]['department_id'];
        $domain = (isset($operation['domain_id']) && $operation['domain_id']!='')?$operation['domain_id']:VIS_DOMAIN;
		$module_setting=$setting_obj->get_module_setting('domain_id='.$domain.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		
		if(VIS_LOCATION_AREA==1) {            
            if(!isset($module_setting['vis_show_tickettype']) || (isset($module_setting['vis_show_tickettype']) && $module_setting['vis_show_tickettype']==2))
            {
				$ticket_types=$ticket_object->get_type_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))');
			}
		 }
		else{ 
		    $ticket_types=$this->get_properties('get_types', ''); 
		}
		
		
		if(VIS_LOCATION_AREA==1) {
            if(!isset($module_setting['vis_show_priority']) || (isset($module_setting['vis_show_priority']) && $module_setting['vis_show_priority']==2))
            {
				$priorities=$ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))');
			}
		}
		else{
			$priorities=$this->get_properties('get_priorities', '');
		}
		
		if(VIS_LOCATION_AREA==1) {
			if(!isset($module_setting['vis_show_level']) || (isset($module_setting['vis_show_level']) && $module_setting['vis_show_level']==2)){
			$module_setting['vis_level']='';
			list($ticket_level_count, $level_details)=$setting_obj->get_ticket_level_list( 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))','',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
			}
	    }
		else{
		     $level_details=$this->get_properties('get_level', '');
		}
		
		if(VIS_LOCATION_AREA==1) {
			if(!isset($module_setting['vis_show_category']) || (isset($module_setting['vis_show_category']) && $module_setting['vis_show_category']==2)){
				$module_setting['vis_category']='';
				list($ticket_cat_count,$category_details)=$setting_obj->get_ticket_category_list('is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))','',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
			}
		}
		else{
			 $category_details=$this->get_properties('get_category', '');	
		}
		
		
		$statuslist=$this->get_properties('get_status', '');
        $flags=$this->get_properties('get_flags', '');
        $owner=$this->get_properties('get_staff', '');
		$subcategory_details=$this->get_properties('get_subcategory', '');
		$item_details=$this->get_properties('get_item', '');
		$location_details=$this->get_properties('get_location', '');
		

            list($client_info, $clientdetails)=$client_object->get_client('client_id='.VIS_CLIENT_ID, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            $clientdetails=$clientdetails[0];
                 if($clientdetails['is_manager']==1 && $operation['vis_status']==4)
					{
						$filter_setting=VIS_TABLE_PREFIX.'settings.title="vis_satellite_helpdesk"';
						$optionB_details=$setting_obj->get_settings($filter_setting, VIS_STAFF_ID, VIS_LOCATION_AREA);
						if($optionB_details[0]['content']!=2)$not_for_optionB = VIS_TABLE_PREFIX.'ticket.domain_id='.VIS_DOMAIN.' and '; else $not_for_optionB=' ';
						$status=$operation['vis_status']==4;
						$filter.='(('.$not_for_optionB.VIS_TABLE_PREFIX.'client.group_id='.$clientdetails['group_id'].' and '.VIS_TABLE_PREFIX.'ticket.client_id='.VIS_TABLE_PREFIX.'client.client_id ) or '; 
						$is_manager=$clientdetails['is_manager'];
					}
            if(VIS_VIEW_TICKET==0 && VIS_VIEW_SELFTICKET==0 && VIS_REPLY_TICKET==0) {
                include(VIS_PATH_TEMPLATE.'header.php');
                echo '<script> $("#vis_submit_err_div").show(); $("#vis_submit_err_div").html("'.$vis_language['MSGACCSSDND'].'");</script>';
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }elseif((VIS_VIEW_TICKET==1 || VIS_REPLY_TICKET==1) && VIS_VIEW_SELFTICKET==0) {
                $parent=(VIS_CLIENT_PARENT==0 || VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client='';
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) if($client_details[$i]['client_id']!=VIS_CLIENT_ID) $client.=$client_details[$i]['client_id'].',';
                if($client!='') $filter.=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';
                else $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.$parent;
            }
            elseif((VIS_VIEW_TICKET==1 || VIS_REPLY_TICKET==1) && VIS_VIEW_SELFTICKET==1) {
                $parent=(VIS_CLIENT_PARENT==0 || VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client='';
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) $client.=$client_details[$i]['client_id'].',';
                if($client!=''){
					if($operation['vis_status']==4) { $filter.=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.'))';}
					else $filter.=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';}
                else {if($operation['vis_status']==4) { $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID.')';}
					else $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID;}


            }
            else $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID;
            $close_filter=$filter.' and status_id=3 and is_deleted=0 and draft_id=0 ';
            $parent=(VIS_CLIENT_PARENT==-1 || VIS_CLIENT_PARENT==0)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
            list($parentclient_info, $parentclient)=$client_object->get_client('client_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            $parentclient=$parentclient[0];
            
			if(isset($operation['vis_status']) && is_numeric($operation['vis_status']) && $operation['vis_status']!=0 ) { 
				if($operation['vis_status']!=4)
				{$filter.=' and status_id='.$operation['vis_status']; 
				$status=$operation['vis_status']; 
				}
			}
            else  {
                if($operation['vis_filter_enable']!=1){				
				$filter.=' and status_id!=3';}
				$status='';
			}
			
            $filter.=' and is_deleted=0 and draft_id=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam=0 ';
            $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
            $limit=($page*10).',10'; 
            if(isset($operation['sorted_byView']) && $operation['sorted_byView']!='') {
				$sort = ($operation['sorted_byView']==0)?' modify_date desc ':' receive_date desc ';
				$order=$operation['sorted_byView'];
			}else $sort='';
              if($clientdetails['is_manager']==0){
            $closed_temp=$ticket_object->get_ticket($close_filter, $limit, $page, $sort, VIS_CLIENT_ID, VIS_LOCATION_AREA);
           
            list($closed_ticket_info, $closed_ticket_details)=$closed_temp; 
            $closed_total = $closed_ticket_info['total'];
            $temp=$ticket_object->get_ticket($filter, $limit, $page, $sort, VIS_CLIENT_ID, VIS_LOCATION_AREA);
            list($ticket_info, $ticket_details)=$temp;
           }else{
			 
            $temp_org=$ticket_object->get_ticket($filter, $limit, $page, $sort, VIS_CLIENT_ID, VIS_LOCATION_AREA,'','','','',$is_manager);
            list($ticket_info, $ticket_details)=$temp_org;
            }
            $page_count=($ticket_info['total']==0)?0:ceil($ticket_info['total']/10);
            $ticket_info['page']=$page;			
        }
        else {
            $ticket_details=-1;
            if(VIS_LOCATION_AREA==1 && IS_LOGIN==0){
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                include(VIS_PATH_TEMPLATE.'login.php');
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }            
            $operation['message']='<div class="vis_error_message">'.$vis_language['MSGACCSSDND'].'</div>';
        }
		$module_setting=$setting_obj->get_module_setting('domain_id='.VIS_DOMAIN.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(isset($module_setting['vis_show_priority']) && ($module_setting['vis_show_priority']==0 ||$module_setting['vis_show_priority']==1))
			    $ticket_priority = -1;
		 if(isset($module_setting['vis_show_tickettype']) && ($module_setting['vis_show_tickettype']==0 || $module_setting['vis_show_tickettype']==1))
				$ticket_type = -1;
		 $breadcrumb['Home'] = 'index.php'; 
		 if(isset($operation['sorted_by']) && $operation['sorted_by']!='') {
			 $breadcrumb[$vis_language['TXTVIEWTICKETS']] = '?/ticket/view-ticket'; 
			 $sort=($operation['sorted_by']==0)?$vis_language['TXTUNSOLVED']:(($operation['sorted_by']==4)?$vis_language['TXTORGANIZATION']:$vis_language['TXTSOLVED']);
			 $breadcrumb[$sort] = ''; 
		 }
		 else $breadcrumb[$vis_language['TXTVIEWTICKETS']] = ''; 
         $vis_title = $vis_language['TXTVIEWTICKETS'];
		 $vis_count =  $ticket_info['total']; 
		 $header_title=$vis_language['TXTVIEWTICKETS'];
		
         if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])){
			if($operation['vis_change']==1){
				include(VIS_PATH_TEMPLATE.'ticket_list.php');
			}
			else {
			if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
			else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
			include(VIS_PATH_TEMPLATE.'view_ticket.php');
			if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
			}
		} else {

			if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
			else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
			include(VIS_PATH_TEMPLATE.'view_ticket.php');
			if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
		}
        return true;
    }

    function get_tickets($operation) {
		global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		$filter = (isset($operation['vis_filter_id']) && $operation['vis_filter_id'] == 7) ? 'draft_id=' . VIS_STAFF_ID : ((isset($operation['vis_draft']) && $operation['vis_draft'] == 1) ? 'draft_id=' . VIS_STAFF_ID : '');
        if(isset($operation['vis_filter_id']) && is_numeric($operation['vis_filter_id']) && $operation['vis_filter_id'] != 7) {
            $filter_detail=$object->get_filter($operation['vis_filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            if($filter_detail['filter']!='') $filter.=' ('.$filter_detail['filter'].')';
        }
        else $filter = (($filter != '') ? $filter .= ' and ' : '') .VIS_TABLE_PREFIX.'ticket.is_spam=0 and is_deleted=0';
        if(isset($operation['vis_filter']) && $operation['vis_filter']!='') {
			$filter.=' and '.$operation['vis_filter'];
			if(strpos($operation['vis_filter'], 'client_id') > 0) $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_TABLE_PREFIX.'ticket.client_id';
		}
        $limit=(isset($operation['vis_limit']) && $operation['vis_limit']!='')?$operation['vis_limit']:'';
        $temp=$object->get_ticket($filter, $limit, 0, 'modify_date desc', VIS_STAFF_ID, VIS_LOCATION_AREA);
        list($ticket_info, $ticket_details)=$temp;
        if(!isset($operation['vis_skip_info']) || $operation['vis_skip_info']==1) {
            for($i=0;$i<count($ticket_details);$i++) {
                $data=$object->get_last_post($ticket_details[$i]['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                $ticket_details[$i]['content']=$data['content'];
            }
        }
        $database->database_disconnect();
        $ticket_info['ticket_count']=(!$ticket_details || $ticket_details==-1)?0:count($ticket_details);
        $data=(isset($operation['vis_details_req']) && $operation['vis_details_req']==1)?($ticket_details==-1)?'':array('details'=>$ticket_info, 'data'=>$ticket_details):($ticket_details==-1?'':$ticket_details);
        if($data!= '') echo get_xml($data, 'tickets');
        else echo 'No data found'; //$vis_language['MSGDATANOTFND'];
        return true;
    }

    function filter_ticket($operation) {
//echo "<pre> filter ticket operaton    ....";print_r($operation);echo"<br/>";echo"<pre/>";	
		global $vis_language;
        $fromlink=0;
		if(isset($operation['vis_filter_id']) && is_numeric($operation['vis_filter_id'])) $filter_id=$operation['vis_filter_id']; 
        else if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
            $action=explode("/", $operation['vis_action']);
			if(isset($action[4]) && trim($action[4])==7) $operation['custom_show_report']=7;
            if(isset($action[4]) && is_numeric($action[4])) {
                $operation['vis_filter_id'] = $filter_id=$action[4];
                if($filter_id == 7) $operation['vis_draft']=1 ;
				if(isset($operation['vis_search'])) $operation['vis_search']=1;
			}
            if(isset($action[5]) && $action[5]==1) $operation['vis_report']=1;
            $fromlink=1;
        }
        else $filter_id=1;
        if(isset($operation['vis_action']) && !empty($operation['vis_action'])){
            $data=parse_form_array($operation['vis_action']);		
            if(isset($data['vis_report'])) $operation['vis_report']=$data['vis_report'];
        }
		# Access denied schedule list
		if(VIS_LOCATION_AREA == 2 && VIS_SCHEDULE_TICKET_MANAGE_ACCESS == 0 && VIS_SCHEDULE_TICKET_VIEW_ACCESS == 0 && $filter_id==21){
		    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGACCSSDND'].'"); </script>';
			return false;
		}
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);   
        if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])) {
            $page=$operation['vis_page'];
//echo "<pre> filter ticket page    ....";print_r($page);echo"<br/>";echo"<pre/>";				
            if(isset($_COOKIE['vis_filter_id_page'])) $vis_filter_id_page=unserialize($_COOKIE['vis_filter_id_page']);
            $vis_filter_id_page[$filter_id]=$page;
            setcookie('vis_filter_id_page', serialize($vis_filter_id_page));
        }
        else {
            $page=0;
            if(isset($_COOKIE['vis_filter_id_page']) && $fromlink==0) {
                $vis_filter_id_page=unserialize($_COOKIE['vis_filter_id_page']);
                if(isset($vis_filter_id_page[$filter_id]) && is_numeric($vis_filter_id_page[$filter_id])) $page=$vis_filter_id_page[$filter_id];
            }
        }
        $sort_by=(isset($operation['vis_sort_by']))?$operation['vis_sort_by']:'';
        $filter=$ticket_object->get_filter($filter_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
//echo "<pre> filter ticket filter    ....";print_r($filter);echo"<br/>";echo"<pre/>";		
        if($filter != ""){
		if(!isset($operation['vis_is_report'])){$operation['vis_is_report']=$filter['is_report'];}
		if($operation['vis_is_report']==1){$operation['vis_search']=3;}
		  if(!isset($operation['view_title']))
            $operation['view_title']=$filter['filter_name'];
		    if($action[4]==1)$operation['view_title']=$vis_language['TXTTICKETS'];
            $operation['filter_id']=$filter['filter_id'];
        } else {
		    $operation['vis_filter_id'] = 1;
			$operation['view_title']=$vis_language['TXTTICKETS'];
            return $this->filter_ticket($operation);
        }
        $database->database_disconnect();
         if($filter['filter_name']=="Search Result")
        return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
        else if($filter['filter_name']!="Search Result" && $filter['filter_name']!="Tickets" )
       return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
       else 
        return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
       
    }
	
	
	// function added by sumit date 30/04/16
	/*function cportal_filter_ticket($operation)
	{  
    	global $vis_language;
		$page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
		if(isset($operation['vis_filter_enable']) && $operation['vis_filter_enable']==1)
		{
		$data= isset($operation['vis_action']) && $operation['vis_action']!='' ? parse_form_array($operation['vis_action']) : $operation;
		if($data['search_subject']!='') $and_operations['subject like "%'] = $data['search_subject'].'%"';
		if($data['search_dept']!='')$and_operations['department_id="'] = $data['search_dept'].'"';
		if($data['search_flag']!='')$and_operations['flag_id="'] = $data['search_flag'].'"';
		if($data['search_item']!='')$and_operations['item_id="'] = $data['search_item'].'"';
		if($data['search_level']!='')$and_operations['level_id="'] = $data['search_level'].'"';
		if($data['search_location']!='')$and_operations['location_id="'] = $data['search_location'].'"';
		//if($data['search_owner']!='')$and_operations['owner="'] = $data['search_owner'].'"';
		if($data['search_priority']!='')$and_operations['priority_id="'] = $data['search_priority'].'"';
		if($data['search_status']!='')$and_operations['status_id="'] = $data['search_status'].'"';
		if($data['search_subcategory']!='')$and_operations['subcategory_id="'] = $data['search_subcategory'].'"';
		if($data['search_type']!='')$and_operations['type_id="'] = $data['search_type'].'"';
		if($data['search_category']!='')$and_operations['category_id="'] = $data['search_category'].'"';
		}
		 if($and_operations!='' && count($and_operations)!=0) {
            $filter="(";
            foreach($and_operations as $key => $value) {
                if(!strstr($key, '.')) $filter.=VIS_TABLE_PREFIX.'ticket.';
                $filter.=$key.$value." and ";
            }
            $filter=substr($filter, 0, -4);
            $filter.=") and ";
        }
        if($or_operations!="" && count($or_operations)!=0) {
            $filter.="(";
            foreach($or_operations as $key => $value) {
                if(!strstr($key, '.')) $filter.=VIS_TABLE_PREFIX.'ticket.';
                $filter.=$key.$value." or ";
            }
            $filter=substr($filter, 0, -3);
            $filter.=") and ";
        }
		
		                        if($data['search_owner']!='' && $data['search_owner']==0){
							    $filter .= VIS_TABLE_PREFIX.'ticket.ticket_id NOT IN(select ticket_id from '.VIS_TABLE_PREFIX.'ticket_assign where owner_id!='.$data['search_owner'].') and ';
								} 
								else if($data['search_owner']!=''){
                                $filter .= VIS_TABLE_PREFIX.'ticket.ticket_id IN(select ticket_id from '.VIS_TABLE_PREFIX.'ticket_assign where owner_id='.$data['search_owner'].') and ';
								} 
		 
		 global $vis_language;
         if(IS_LOGIN) {
			if(isset($_REQUEST['hash'])) $operation['message']='<div class="vis_message">#'.$_REQUEST['hash'].' - '.$vis_language['MSGSUCCOTKT'].'</div>';
			else if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
			if(VIS_LOCATION_AREA == 1 && $operation['vis_operation']!='ticket_reply')
			{	
				$action=explode("/", $operation['vis_action']);
				if(count($action) > 3 && $action[2] !='view-ticket')
				{
					$operation['message']='<div class="vis_message">#'.$action[3].' - '.$vis_language['MSGSUCCOTKT'].'</div>';
				}
				if($action[2] == 'view-ticket') $operation['vis_status'] = $action[3];
			}
			}
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $database=new class_database();
            $ticket_object=new class_ticket($database);
			$setting_obj=new class_setting($database);
            $client_object=new class_client($database);

            list($client_info, $clientdetails)=$client_object->get_client('client_id='.VIS_CLIENT_ID, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            $clientdetails=$clientdetails[0];
                 if($clientdetails['is_manager']==1 && $operation['vis_status']==4)
					{
						$status=$operation['vis_status']==4;
						$filter.='(('.VIS_TABLE_PREFIX.'ticket.domain_id='.VIS_DOMAIN.' and '.VIS_TABLE_PREFIX.'client.group_id='.$clientdetails['group_id'].' and '.VIS_TABLE_PREFIX.'ticket.client_id='.VIS_TABLE_PREFIX.'client.client_id ) or '; 
						$is_manager=$clientdetails['is_manager'];
					}
            if(VIS_VIEW_TICKET==0 && VIS_VIEW_SELFTICKET==0 && VIS_REPLY_TICKET==0) {
                include(VIS_PATH_TEMPLATE.'header.php');
                echo '<script> $("#vis_submit_err_div").show(); $("#vis_submit_err_div").html("'.$vis_language['MSGACCSSDND'].'");</script>';
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }elseif((VIS_VIEW_TICKET==1 || VIS_REPLY_TICKET==1) && VIS_VIEW_SELFTICKET==0) {
                $parent=(VIS_CLIENT_PARENT==0 || VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client='';
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) if($client_details[$i]['client_id']!=VIS_CLIENT_ID) $client.=$client_details[$i]['client_id'].',';
                if($client!='') $filter.=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';
                else $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.$parent;
            }
            elseif((VIS_VIEW_TICKET==1 || VIS_REPLY_TICKET==1) && VIS_VIEW_SELFTICKET==1) {
                $parent=(VIS_CLIENT_PARENT==0 || VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client='';
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) $client.=$client_details[$i]['client_id'].',';
                if($client!=''){
					if($operation['vis_status']==4) { $filter.=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.'))';}
					else $filter.=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';}
                else {if($operation['vis_status']==4) { $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID.')';}
					else $filter.=VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID;}


            }
            //else $filter=VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID;
            //$close_filter=$filter.' and status_id=3 and is_deleted=0 and draft_id=0 ';
            $parent=(VIS_CLIENT_PARENT==-1 || VIS_CLIENT_PARENT==0)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
            list($parentclient_info, $parentclient)=$client_object->get_client('client_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            $parentclient=$parentclient[0];
            if(isset($operation['vis_status']) && is_numeric($operation['vis_status']) && $operation['vis_status']!=0 ) { 
				if($operation['vis_status']!=4)
				{$filter.=' and status_id='.$operation['vis_status']; 
				$status=$operation['vis_status']; 
				}
			}
            else  { 
				//$filter.=' and status_id!=3';
				$status='';
			}
           // $filter.=' and is_deleted=0 and draft_id=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam=0 ';
            $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
            $limit=($page*10).',10'; 
              if($clientdetails['is_manager']==0){
            $closed_temp=$ticket_object->get_ticket($filter, $limit, $page, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
           
            list($closed_ticket_info, $closed_ticket_details)=$closed_temp; 
            $closed_total = $closed_ticket_info['total'];
            $temp=$ticket_object->get_ticket($filter, $limit, $page, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            list($ticket_info, $ticket_details)=$temp;
           }else{
			 
            $temp_org=$ticket_object->get_ticket($filter, $limit, $page, '', VIS_CLIENT_ID, VIS_LOCATION_AREA,'','','','',$is_manager);
            list($ticket_info, $ticket_details)=$temp_org;
            }
            $page_count=($ticket_info['total']==0)?0:ceil($ticket_info['total']/10);
            $ticket_info['page']=$page;			
        }
        else {
            $ticket_details=-1;
            if(VIS_LOCATION_AREA==1 && IS_LOGIN==0){
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                include(VIS_PATH_TEMPLATE.'login.php');
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }            
            $operation['message']='<div class="vis_error_message">'.$vis_language['MSGACCSSDND'].'</div>';
        }
		$module_setting=$setting_obj->get_module_setting('domain_id='.VIS_DOMAIN.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(isset($module_setting['vis_show_priority']) && ($module_setting['vis_show_priority']==0 ||$module_setting['vis_show_priority']==1))
			    $ticket_priority = -1;
		 if(isset($module_setting['vis_show_tickettype']) && ($module_setting['vis_show_tickettype']==0 || $module_setting['vis_show_tickettype']==1))
				$ticket_type = -1;
		 $breadcrumb['Home'] = 'index.php'; 
		 if(isset($operation['sorted_by']) && $operation['sorted_by']!='') {
			 $breadcrumb[$vis_language['TXTVIEWTICKETS']] = '?/ticket/view-ticket'; 
			 $sort=($operation['sorted_by']==0)?$vis_language['TXTUNSOLVED']:(($operation['sorted_by']==4)?$vis_language['TXTORGANIZATION']:$vis_language['TXTSOLVED']);
			 $breadcrumb[$sort] = ''; 
		 }
		 else $breadcrumb[$vis_language['TXTVIEWTICKETS']] = ''; 
         $vis_title = $vis_language['TXTVIEWTICKETS'];
		 $vis_count =  $ticket_info['total']; 
		 $header_title=$vis_language['TXTVIEWTICKETS'];
		
         if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])){
			if($operation['vis_change']==1){
				
				include(VIS_PATH_TEMPLATE.'ticket_list.php');
			}
			else {
			//include(VIS_PATH_TEMPLATE.'clifiltered_ticket_list.php');
			include(VIS_PATH_TEMPLATE.'clifiltered_ticket_list.php');		
			}
		} else {
               //include(VIS_PATH_TEMPLATE.'clifiltered_ticket_list.php');
			 include(VIS_PATH_TEMPLATE.'clifiltered_ticket_list.php');
		  }
        return true;
	  //return $this->cportal_ticket_display($operation,$and_operations, '', '', $page, $sort_by);
	
	} */
	
	function filter_ticket_group($operation) {
        $fromlink=0;
		if(isset($operation['vis_filter_id']) && is_numeric($operation['vis_filter_id'])) $filter_id=$operation['vis_filter_id']; 
        else if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
            $action=explode("/", $operation['vis_action']);
            if(isset($action[4]) && is_numeric($action[4])) {
				$operation['vis_group_name'] = $action[3];
				$operation['vis_group_id'] = $action[4];
                if($filter_id == 7) $operation['vis_draft']=1 ;
			}
            $fromlink=1;
        }
        else $filter_id=1;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);   
        if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])) {
            $page=$operation['vis_page'];
            if(isset($_COOKIE['vis_filter_id_page'])) $vis_filter_id_page=unserialize($_COOKIE['vis_filter_id_page']);
            $vis_filter_id_page[$filter_id]=$page;
            setcookie('vis_filter_id_page', serialize($vis_filter_id_page));
        }
        else {
            $page=0;
            if(isset($_COOKIE['vis_filter_id_page']) && $fromlink==0 && isset($operation['vis_page'])) {
                $vis_filter_id_page=unserialize($_COOKIE['vis_filter_id_page']);
                if(isset($vis_filter_id_page[$filter_id]) && is_numeric($vis_filter_id_page[$filter_id])) $page=$vis_filter_id_page[$filter_id];
            }
        }
        $sort_by=(isset($operation['vis_sort_by']))?$operation['vis_sort_by']:'';
        $filter=$ticket_object->get_filter($filter_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($filter != ""){
			if(!isset($operation['view_title']))
            $operation['view_title']=$filter['filter_name'];
            $operation['filter_id']=$filter['filter_id'];
        } else {
            $operation['vis_filter_id'] = 1;
            return $this->filter_ticket_group($operation);
        }
        $database->database_disconnect();
         if($filter['filter_name']=="Search Result")
        return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
        else if($filter['filter_name']!="Search Result" && $filter['filter_name']!="Tickets" )
       return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
       else 
        return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
       
    }
    function search_label_tickets($operation) {
        if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
            $action=explode("/", $operation['vis_action']);
            if(count($action)>4 && isset($action[4]) && is_numeric($action[4]))
                $label_id = $action[4];
        }
        else if(isset($operation['vis_label_id']) && is_numeric($operation['vis_label_id'])) $label_id=$operation['vis_label_id'];
        else return false;
        $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
        $sort_by=(isset($operation['vis_sort_by']))?$operation['vis_sort_by']:'';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $filter=$ticket_object->get_label_filter($label_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $operation['view_title']=$filter['label_name'];
        $operation['filter_id']=$filter['filter_id'];
        $database->database_disconnect();
		##left panel lable filter
		$lp_rq_identifier = explode('&-',$action[3]);
		$filter['filter'] = (isset($lp_rq_identifier[1]) && $lp_rq_identifier[1]==$label_id)?$filter['filter'].' and '.VIS_TABLE_PREFIX.'ticket.status_id <>3':$filter['filter'];
		### left panel lable filter ends
        return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
    }
	
	
    function filter_queue_ticket($operation) {
        global $vis_language;
        $filter_id=0;
        $fromlink=0;
        if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
            $action=explode("/", $operation['vis_action']);
            if(isset($action[4]) && is_numeric($action[4]) && isset($action[5]) && is_numeric($action[5])){
                $operation['vis_department_id'] = $action[4];
                $operation['vis_status_id'] = $action[5];
            }
            $fromlink=1;
        }
        if(isset($operation['vis_filter_id']) && strstr($operation['vis_filter_id'], '-')) {
            $info=explode('-', $operation['vis_filter_id']);
            $operation['vis_status_id']=$info[0];
            $operation['vis_department_id']=$info[1];
            $filter_id=$operation['vis_filter_id'];
        }
        else $filter_id=$operation['vis_status_id'].'-'.$operation['vis_department_id'];
        if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) $department_id=$operation['vis_department_id'];
        else return false;
        if(isset($operation['vis_status_id']) && is_numeric($operation['vis_status_id'])) $status_id=$operation['vis_status_id'];
        else return false;
        $page=0;
        if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])) {
            $page=$operation['vis_page'];
            if(isset($_COOKIE['vis_filter_id_page'])) $vis_filter_id_page=unserialize($_COOKIE['vis_filter_id_page']);
            if($filter_id!=0) $vis_filter_id_page[$filter_id]=$page;
            setcookie('vis_filter_id_page', serialize($vis_filter_id_page));
        }
        else {
            if(isset($_COOKIE['vis_filter_id_page']) && $fromlink==0 && isset($operation['vis_page'])) {
                $vis_filter_id_page=unserialize($_COOKIE['vis_filter_id_page']);
                if(isset($vis_filter_id_page[$filter_id]) && is_numeric($vis_filter_id_page[$filter_id]) && $filter_id!=0) $page=$vis_filter_id_page[$filter_id];
            }
        } 
        $sort_by=(isset($operation['vis_sort_by']))?$operation['vis_sort_by']:'';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');  
        $ticket_object=new class_ticket($database);
		$departments=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$department_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$status=$ticket_object->get_status_list(VIS_TABLE_PREFIX.'ticket_status.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_status.status_id='.$status_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $operation['view_title']=$status[0]['status_name'];
        $operation['view_title1']=$departments[0]['domain_name'].' : '.$departments[0]['department_name'];
        return $this->ticket_display($operation, '', '', VIS_TABLE_PREFIX.'department.department_id='.$department_id.' and status_id='.$status_id.' and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam=0', $page, $sort_by);
    }
    function view_filters($operation) {
        $database=new class_database();
        $operation['vis_current_operation']='view_filters'; 
        $operation['vis_current_module']='ticket'; 
		 if(isset($operation['vis_action'])){
            $action=explode('/', $operation['vis_action']);
             
			if(isset($action[4]) && trim($action[4])==7) $operation['custom_show_report']=7;
        }
        $staff=new class_staff($database);
		$operation['custom_show_report']=(isset($operation['custom_show_report']))?7:'';
        list($view_info, $view_details)=$staff->get_ticket_view(VIS_STAFF_ID, VIS_LOCATION_AREA);	
        $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
        $limit=($page*$view_info['page_count']).','.$view_info['page_count'];
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		if($operation['custom_show_report']==7){
			$filter='vscope=1 and is_report=1 and owner='.VIS_STAFF_ID;
		}else{
			$filter='vscope=1 and is_report=0 and owner='.VIS_STAFF_ID;
		}			
        $filters=$object->get_filters_details($filter.' or (filter_id=25 or filter_id=26 or filter_id=27 or filter_id=28 or filter_id=29)', VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
        $filters_count=($filters!=-1)?count($filters):0;
        $filters_detail_total=$object->get_filters_details($filter.' or (filter_id=25 or filter_id=26 or filter_id=27 or filter_id=28 or filter_id=29)', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $filters_total=($filters_detail_total!=-1)?count($filters_detail_total):0;
        $filters_info['count']=$filters_total;
		$view_info['page_count']=($filters_info['count']==0)?0:ceil($filters_info['count']/$view_info['page_count']);
		$filters_info['page']=$page;	
		
		if($operation['custom_show_report']==7){
			if($filters!=-1){ for($i=0;$i<count($filters);$i++) {
			$criteria_detail=$object->get_search_criteria('(FC.base_criteria=16 or FC.base_criteria=12) and FC.filter_id='.$filters[$i]['filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,1);
			$durationdate=explode('=',$criteria_detail[0]['content']);
			$filters[$i]['fromdate']=$durationdate[0];
			$filters[$i]['todate']=$durationdate[1];
			}
			}
		}
		
        $database->database_disconnect();
								if($operation['vis_filter']==1){
								include(VIS_PATH_TEMPLATE.'filter_list.php');
								}else{
        include(VIS_PATH_TEMPLATE.'filter.php');
								}
        return true;
    }

    function ticket_details($operation) { 
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);
        list($info, $modules)=$sett_obj->get_module('is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        foreach($modules as $var) $module[$var['module']]=1;
        $staffSettings=$sett_obj->get_settings('title="vis_head_menu_staffNm" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
          //
			  include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
			 $client_object=new class_client($database);
				list($client_info, $clientdetails)=$client_object->get_client('client_id='.VIS_CLIENT_ID, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
				$clientdetails=$clientdetails[0];
			//	
				
        if(VIS_LOCATION_AREA==0 || VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3) {
            if(isset($operation['ticket_id']) && is_numeric($operation['ticket_id']) && !isset($operation['vis_ticket_id'])) $operation['vis_ticket_id']=$operation['ticket_id'];
            if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                $action=array('', 'ticket', 'ticket_details', '', $operation['vis_ticket_id']);
            }
            else {
                $spliter=(strstr($operation['vis_action'], '/'))?'/':',';
                $action=explode($spliter, $operation['vis_action']);
            }
            if(isset($action[4]) && $action[4]!='' && is_numeric($action[4])) {
                $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$action[4];
            }
            else {
                $this->error=$vis_language['MSGTKTIDMISS'];
                return false;
            }
        }
        elseif(VIS_LOCATION_AREA==1) {
            $readonly=1;
            if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) $operation['ticket_id']=$operation['vis_ticket_id'];
            else if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
				$action=explode("/", $operation['vis_action']);
				$operation['ticket_id'] = $action[4];
                if(isset($action[5]) && $action[5]==2) $readonly=0;
			}
            if($operation['ticket_id']=='' && VIS_LOCATION_AREA == 1){
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                echo '<div class="vis_error_message"><br/>'.$vis_language['TXTNOMATCHFOUND'].'<br/><br/></div>';
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }
            $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['ticket_id'];
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            if((VIS_VIEW_TICKET==1 || VIS_REPLY_TICKET==1) && VIS_VIEW_SELFTICKET==0) {
                $parent=(VIS_CLIENT_PARENT==0 || VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client='';
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) if($client_details[$i]['client_id']!=VIS_CLIENT_ID) $client.=$client_details[$i]['client_id'].',';
                if($client!='') $filter=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';
                else $filter=VIS_TABLE_PREFIX.'ticket.client_id='.$parent;
            }
            elseif((VIS_VIEW_TICKET==1 || VIS_REPLY_TICKET==1) && VIS_VIEW_SELFTICKET==1) {
                $client='';
                $parent=(VIS_CLIENT_PARENT==-1 || VIS_CLIENT_PARENT==0)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) $client.=$client_details[$i]['client_id'].',';
                if($client!='') {if($clientdetails['is_manager']!=1 )$filter.=' and '.VIS_TABLE_PREFIX.'client.client_id in ('.$client.$parent.')';}
                else{if($clientdetails['is_manager']!=1 ) $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;}
            }
            else {if($clientdetails['is_manager']!=1 )$filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;}
            $filter.=' and draft_id=0';
            
            $ticketCloseSetting=$sett_obj->get_settings('title="vis_head_menu_close_ticket" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
            if($ticketCloseSetting != -1 && $ticketCloseSetting[0]['content'] == 0) $ticketCloseSettings = -1; 
												$ticketfeedbSetting=$sett_obj->get_settings('title="vis_head_menu_feedback_client" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
            if($ticketfeedbSetting != -1 && $ticketfeedbSetting[0]['content'] == 0) $ticketfeedbSettings = -1; 
        }
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
	    if($ticket_details==-1) {
            if(VIS_LOCATION_AREA == 1 && $parent==0){
				$breadcrumb['Home'] = 'index.php';  
				$breadcrumb[$vis_language['TXTLOGIN']] = ''; 
				$vis_title = $header_title=$vis_language['TXTLOGIN'];
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                include(VIS_PATH_TEMPLATE.'login.php');
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }
            if(VIS_LOCATION_AREA == 1){
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                echo '<div class="vis_error_message"><br/>'.$vis_language['TXTNOMATCHFOUND'].'<br/><br/></div>';
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }  
            ?><section class="wrapper fullFrame b-light">
                    <div class="fullMiddle"><? echo $vis_language['MSGACCSSDND']; ?></div>
			</section>  <?    
            return false;
        }
		$ticket_details=$ticket_details[0];
        if($ticket_details['client_id']==0){
			define('VIS_INTERNAL_TICKET', 1);
			$ticket_first_post=$ticket_object->get_last_post($ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA, 1);
		} else define('VIS_INTERNAL_TICKET', 0);
        if($ticket_details['parent_id'] != 0)
        {
              $parent_details = $ticket_object->get_parent_details($ticket_details['parent_id']) ;   
        }
        $page=(isset($operation['vis_page']) && $operation['vis_page']!='')?$operation['vis_page']:1;
        $post_setting=$ticket_object->get_ticket_post_setting($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$post_setting['postcount'] = !isset($post_setting['postcount']) ? 10 : $post_setting['postcount'];
        if(VIS_LOCATION_AREA==1) {
		$total_post_count=$ticket_object->get_total_post_count($ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $post_details=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA, $page, $post_setting['postcount']); 
		 $module_setting1=$sett_obj->get_module_setting('domain_id='.$ticket_details['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$post_paging_count=($total_post_count==0 || $post_setting['postcount']==0)?0:ceil($total_post_count/$post_setting['postcount']);
		}
        $show_inline_img=$ticket_object->get_inline_image_flag($ticket_details['ticket_id'], $post_setting['domainid'], VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $post_count=count($post_details);
        
         $ticket_feedback =  'ticket-feedback';        
        $filter=' (location in (1,2,11)) and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access)) and is_enabled=1 ';
        $custom_group=$sett_obj->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		 //$filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[0]['customgroup_id'].' and '.VIS_TABLE_PREFIX.'customfield.is_enabled=1 ';
		//list($custom_field_info, $custom_fields_details)=$sett_obj->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA); // $custom_fields_details & $custom_group used to decide whether to show custom field tab
		 for($c=0;$c<count($custom_group);$c++){
		        $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$c]['customgroup_id'].' and '.VIS_TABLE_PREFIX.'customfield.is_enabled=1 ';
		        list($custom_field_info, $custom_fields_details)=$sett_obj->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA); // $custom_fields_details & $custom_group used to decide whether to show custom field tab
		        	if($custom_fields_details != -1){ break; }
          }
		
		
		
		$custIds = $ticket_object->get_custom_fields_id($ticket_details['ticket_id']); //feedback details
		if(VIS_LOCATION_AREA==0){
			//Custom field array for API
		  for($c=0;$c<count($custom_group);$c++){
		  $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$c]['customgroup_id'].' and '.VIS_TABLE_PREFIX.'customfield.is_enabled=1 ';
		  list($custom_field_info, $custom_fields_details)=$sett_obj->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA); // $custom_fields_details & $custom_group used 
			if($custom_fields_details != -1){
                	for($j=0; $j<count($custom_fields_details); $j++)
                    {  
				        $val='';
                        if($custom_fields_details[$j]['field_type']<4 || $custom_fields_details[$j]['field_type']==8)
                        {
                            $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);
                            if($custom_data != -1) 
								$custom_fields_details[$j]['custom_field_data'] = $custom_data;
							/*	$val = $custom_data['content'];
                           // else $val = $custom_fields_details[$j]['default_value'];
                            $req = ($custom_fields_details[$j]['is_required']==1)?' *':'';
                            if($custom_fields_details[$j]['field_type']==1){
                                             $custom_field_var.=$val;
                            }
                            if($custom_fields_details[$j]['field_type']==2)
                            {
											$custom_field_var.=$val; 
                                                                     
                            }
                            if( $custom_fields_details[$j]['field_type']==3){
                                              $custom_field_var.=$val; 
                            }
                            if( $custom_fields_details[$j]['field_type']==8){
                                              $custom_field_var.=format_datetime(strtotime($val)); 
                            }*/
                        }
                        else
                        {
                            $filter='field_group='.$custom_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$sett_obj->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                                if($sub_customfields_details != -1)
                                {
                                     $flag = array();   
                                        if($custom_fields_details[$j]['field_type']==4)
                                        {
                                              /*for($cnt=0;$cnt<count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }*/
									        for($k=0;$k< count($sub_customfields_details);$k++)
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']); 
												
												if($custom_data!=-1)$custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
											   /* if($custom_data['content'] === $sub_customfields_details[$k]['default_value'])
                                                {  
                                                    $sel = $custom_field_var.=$sub_customfields_details[$k]['default_value'].' ';
												}*/
                                                $cc_count++;
                                            }
                                        }
                                        if($custom_fields_details[$j]['field_type']==5)
                                        {
                                            for($k=0;$k<count($sub_customfields_details);$k++)
                                            {
                                              $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);  
                                                if($custom_data!= -1) 
                                                {
                                                    $flag[$k] = 1;
                                                    $custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
                                                }
                                              
                                               $cc_count++;
                                            }
                                        }
                                        if($custom_fields_details[$j]['field_type']==6)
                                        {    
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);
												//if($custom_data!=-1)$custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
                                             	if($custom_data['content']== $sub_customfields_details[$k]['default_value']) 
                                                {
													$custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
                                                }
                                            }
                                            $cc_count++;
                                        }
                                        if($custom_fields_details[$j]['field_type']==7)
                                        { 
                                            if($sub_customfields_details[$k]['is_selected'] == 1 )$selDefault = 'selected="selected"';    
                                            /*for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }*/
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);   
											    if($custom_data['content']== $sub_customfields_details[$k]['default_value']) 
                                                {
													if($custom_data!=-1)$custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
												}
                                                //if(count($flag) <= 0 && $sub_customfields_details[$k]['is_selected'] == 1) $custom_field_var.=addslashes($sub_customfields_details[$k]['default_value']).' ';
                                            }
                                            $cc_count++;
                                        }
                                    
                                }
                            }
				       }
					   $custom_group[$c]['custom_group'] = $custom_fields_details;
				}
		    }   
		}
		
		#Redmine
		$check_redmine_status	=	$sett_obj->get_redmine('check_status'); 

		$query	=	"SELECT count(*) FROM `".VIS_TABLE_PREFIX."module_integrate` WHERE  `integration_type` = 37 AND  `ticket_id` =".$ticket_details['ticket_id'];	
		$result=$database->query_exec($query);
        $redmine_link_result = $database->fetch_result_array($result);		
				
	    if(VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3) {
            if(!isset($ticket_details) || $ticket_details==-1) {
                echo $vis_language['MSGINFOMISS'];
                return false;
            }
            $filter=VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$ticket_details['ticket_id'];
            $owner_details=$ticket_object->get_ticket_owner($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
            $label_list=$ticket_object->get_labels_list('(department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access)) and is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $label_details = $ticket_object->get_ticket_labels($ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $tag_details = $ticket_object->get_ticket_tag($ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			#
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
            	$staff_object=new class_staff($database);
				$autoticketlockflag=0;
				$staffsetting=$staff_object->get_staff_group('group_id='.VIS_STAFF_GROUP, VIS_STAFF_ID, VIS_LOCATION_AREA);
				
				if($staffsetting!=-1){ 
				$access=explode(',', $staffsetting[0]['access']); 
				if(isset($access[100])){$autoticketlockflag=$access[100];}else{$autoticketlockflag=0;}
				}
				else{$autoticketlockflag=0;}

				
            $ticket_lock=$ticket_object->get_ticket_lock($ticket_details['ticket_id'], '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $lock_msg = "";
            $self_ticket_lock = 0;
            if($ticket_lock != -1){
                for($i=0; $i<count($ticket_lock); $i++){ 
                    if($ticket_lock[$i]['staff_id'] != VIS_STAFF_ID) 
                        $lock_msg .= $ticket_lock[$i]['first_name'].' '.$ticket_lock[$i]['last_name']; 
                    else $self_ticket_lock = 1;
                }
                $lock_msg = ($lock_msg != "") ? ($lock_msg) .' '. $vis_language['TXTTKTLOCK'] : "";
            }
            $integration_list=$sett_obj->get_integration_details('(integration_type=1 or integration_type=28 or integration_type=35 or integration_type=31 or integration_type=33 or integration_type=29 or integration_type=34 or integration_type=36 or  integration_type=37 or integration_type=41 or integration_type=43 or integration_type=46 or integration_type=48 or integration_type=56) and '.VIS_TABLE_PREFIX.'integration.is_enabled=1 and '.VIS_TABLE_PREFIX.'integration.domain_id='.$ticket_details['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		    for($i=0;$i<count($post_details);$i++){
				$comment_details[$i]=(VIS_COMMENT_ACCESS==0)?-1:$ticket_object->get_post_comment($post_details[$i]['post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);	
				$validation_error[$i]=$ticket_object->get_post_error(' parent_id ='.$post_details[$i]['post_id'].' and remark_method = 1' , VIS_STAFF_ID, VIS_LOCATION_AREA);	
            }
            $billing=$ticket_object->get_billing_setting($ticket_details['department_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $invoices=$ticket_object->get_billing_counts($ticket_details['ticket_id'], $ticket_details['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			$total_invoice_cnt=$unpaid_invoice_cnt=0;
            if($ticket_details['client_id']>0){
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
				$billing=new class_billing($database);
				$total_invoice_cnt=$billing->get_unpaid_invoice_count('('.VIS_TABLE_PREFIX.'invoice.client_id='.$ticket_details['client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$ticket_details['client_id'].') and ticket_id='.$ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($total_invoice_cnt['cnt']>0)
					$unpaid_invoice_cnt=$billing->get_unpaid_invoice_count('('.VIS_TABLE_PREFIX.'invoice.client_id='.$ticket_details['client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$ticket_details['client_id'].') and invoice_status=0 and ticket_id='.$ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
			
            $module_setting=$sett_obj->get_module_setting('(title="vis_show_note" or title="vis_show_custom_field") and domain_id='.$ticket_details['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA); 
						
			$note_details=(VIS_NOTE_ACCESS==0)?-1:$ticket_object->get_note($ticket_details['ticket_id'], $ticket_details['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			
			if(isset($operation['vis_readonly']) && $operation['vis_readonly']==1) $readonly=1;
			else $readonly=0;
			
			$location2=array(0=>0, 1=>3);
			$custom_field_varfeedback=(!$module_setting['vis_show_custom_field'])?-1:$this->edit_custom_fields($location2, $ticket_details['ticket_id'], $ticket_details['department_id'], $database,1); 
			$location3=array(0=>'1', 1=>'2', 2=>'11');
			$custom_field_var=(!$module_setting['vis_show_custom_field'])?-1:$this->edit_custom_fields($location3, $ticket_details['ticket_id'], $ticket_details['department_id'], $database,$readonly); 
			if($custom_field_var == 'Data not available'){$nodata = 1 ;$custom_field_var='';}
			if($custom_field_var == ''){$custom_field_var=$vis_language['MSGRECORDMISS'];}
			
			if($custom_field_varfeedback == 'Data not available'){$nodata = 1 ;$custom_field_varfeedback='';}
			if($custom_field_varfeedback == ''){$custom_field_varfeedback=$vis_language['MSGRECORDMISS'];}
			
			$time_track_details = $ticket_object->get_time_track_details('ticket_id='.$ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,1); 
			$time_track_count = ($time_track_details['count']>0) ? $time_track_details['count'] : 0;
			$link_data=array('vis_ticket_id'=>$ticket_details['ticket_id'], 'case'=>1);		
			$link_arr = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA,1);
			if(VIS_ITIL==1 && isset($module['itil']) && $module['itil']==1)$itil_enabled=1;
			if($itil_enabled==1){
				 $filter1='ticket_id='.$ticket_details['ticket_id'];
				 $service_ticket_details=$ticket_object->get_service_ticket_list($filter1,'', VIS_STAFF_ID, VIS_LOCATION_AREA);
				
				 $filter3='parent_id='.$ticket_details['ticket_id'].' and attach_type=0';
				 $attach_ci_details = $sett_obj->get_attach_relation_list($filter3,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
				
				 $filter6='parent_id='.$ticket_details['ticket_id'].' and attach_type=1';
				 $attach_problem_details = $sett_obj->get_attach_relation_list($filter6,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
				
				 $filter8='parent_id='.$ticket_details['ticket_id'].' and attach_type=6';
				 $attach_changes_details = $sett_obj->get_attach_relation_list($filter8,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
		
			}
			$filter9='parent_id='.$ticket_details['ticket_id'].' and attach_type=12';
			$attach_task_details = $sett_obj->get_attach_relation_list($filter9,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
			
				//THIS ONE FOR APPROVAL TICKET --> TO GET THE TOTAL APPROVALS
			$filter = " approvals_type=0 AND ".VIS_TABLE_PREFIX."ticket_approvals.is_enabled=1 AND parent_id=".$ticket_details['ticket_id'];
			list($total_approvals, $approvals_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			
			$filter = " approvals_type=0 AND ".VIS_TABLE_PREFIX."ticket_approvals.is_enabled=1 AND ".VIS_TABLE_PREFIX."ticket_approvals.staff_id=".VIS_STAFF_ID." AND parent_id=".$ticket_details['ticket_id'];
						list($single_approvals, $single_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
								
 						$filter = " approvals_type=0 AND remark!='' AND parent_id=".$ticket_details['ticket_id'];
						
						list($total_remark, $remark_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID,VIS_LOCATION_AREA);

						$filter= ' is_enabled=1 AND parent_id='.$ticket_details['ticket_id'];
						$approvals_status=$ticket_object->get_approvals_status($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			//THIS ONE FOR APPROVAL TICKET --> TO GET THE TOTAL APPROVALS ENDS
								
			$departments = $ticket_object->get_all_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$ticket_details['domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA, VIS_TABLE_PREFIX.'domain.domain_id');
			
			$module_setting1=$sett_obj->get_module_setting('domain_id='.$ticket_details['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
			
				if(VIS_LOCATION_AREA==2) {
				if(isset($module_setting1['vis_add_read_ticket_tolog']) && $module_setting1['vis_add_read_ticket_tolog']==1){
					$auditfilter='ticket_id='.$ticket_details['ticket_id'].' and operation_id=52 and operator_id='.VIS_STAFF_ID.' and operator='.VIS_LOCATION_AREA;
					$audit_log=$ticket_object->get_checkaudit_log($auditfilter, VIS_STAFF_ID, VIS_LOCATION_AREA);
					if($audit_log==-1){
						$ticket_object->add_audit_log($ticket_details, 52, '', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
				}
				
				
				
			}
			
        }
        if(VIS_LOCATION_AREA==2) {
            if(isset($operation['vis_action']) && $operation['vis_action']=='load_more_post') include(VIS_PATH_TEMPLATE.'ticket_post_list.php');
			else include(VIS_PATH_TEMPLATE.'ticket_view.php');
        }
        elseif(VIS_LOCATION_AREA==0) {
			$ticket_details['recipients'] = str_replace(",", ", ", $ticket_details['recipients']);
			$ticket_details['owner'] = ($ticket_details['owner'] == "") ? $vis_language['TXTUNASSIGNED'] : $ticket_details['owner'];
            $ticket_details['custom_fields']=$custom_group;
			header('Content-Type: application/json');
			$postdetails=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA, $page, $post_setting['postcount']); 
	
	        #Remove space in the ticket post -- for the mobile app
			for($i=0;$i<count($postdetails);$i++){
			$postdetails[$i]["content"] = strip_tags($postdetails[$i]["content"]);
			$postdetails[$i]["content"] = str_replace('&nbsp;', ' ', $postdetails[$i]["content"]);
			$breaks = array("<br />","<br>","<br/>");
			$postdetails[$i]["content"] = str_ireplace($breaks, "\r\n", $postdetails[$i]["content"]);
			}
			#end
            $ticket_details['post_details']=$postdetails;
            echo get_xml($ticket_details, 'ticket');
            return true;
        }
        elseif(VIS_LOCATION_AREA==3) {
            include(VIS_PATH_TEMPLATE.'ticket_details.php');
        }
        else {
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$setting_obj=new class_setting($database);
			$module_setting=$setting_obj->get_module_setting('domain_id='.$ticket_details['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$attachment=$setting_obj->get_settings(' module_id=2 and title="vis_attachment" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$attachment=is_numeric($attachment[0]['content'])?$attachment[0]['content']:1;
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
			list($client_info, $client_details)=$client_object->get_client('client_id='.VIS_CLIENT_ID, 1, 0, '', $userid, VIS_LOCATION_AREA);
            $client_details=$client_details[0];
            $location=array(0=>3, 1=>3);
            $custom_field_var =$this->edit_custom_fields($location, $ticket_details['ticket_id'], $ticket_details['department_id'], $database,1);
			
			$fileddata=$ticket_object->get_groupbycustomfield_data(VIS_TABLE_PREFIX.'customfield_data.customfield_id IN (select customfield_id from '.VIS_TABLE_PREFIX.'customfield'.' where  is_enabled=1 and customgroup_id IN(select customgroup_id from '.VIS_TABLE_PREFIX.'customgroup where (location='.$location[0].' or location='.$location[1].' ) and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))))',$ticket_details['ticket_id']);
						
            $location=array(0=>1, 1=>1, 2=>11);
            $user_custom_field_var=$this->edit_custom_fields($location, $ticket_details['ticket_id'], $ticket_details['department_id'], $database,$readonly);
            $type_list=$ticket_object->get_type_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))');
            $status_list=$ticket_object->get_status_list('is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))', $userid, VIS_LOCATION_AREA);
            $priority_list=$ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))');
		    if(isset($module_setting['vis_show_priority']) && ($module_setting['vis_show_priority']==0 ||$module_setting['vis_show_priority']==1))
			    $ticket_priority = -1;
		    if(isset($module_setting['vis_show_tickettype']) && ($module_setting['vis_show_tickettype']==0 || $module_setting['vis_show_tickettype']==1))
				$ticket_type = -1;
            $header_title=$ticket_details['ticket_hash'];
			$breadcrumb['Home'] = 'index.php'; 
			$breadcrumb[$vis_language['TXTVIEWTICKETS']] = '?/ticket/view-ticket'; 
			$breadcrumb[$ticket_details['ticket_hash']] = '';
			$vis_title = $vis_language['TXTVIEWTICKETS'];
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
			if(VIS_ITIL==1){
				 $filter1='ticket_id='.$ticket_details['ticket_id'];
				 $service_ticket_details=$ticket_object->get_service_ticket_list($filter1, VIS_STAFF_ID, VIS_LOCATION_AREA);
				 $filter2=VIS_TABLE_PREFIX."itil_service_item.item_id=".$service_ticket_details[0]['service_item_id'];
				 $service_details=$setting_obj->get_service_item_list($filter2,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
				 list($dpinf, $domain)=$setting_obj->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$service_details[0]['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				 //$filter3 = VIS_TABLE_PREFIX.'customfield.customgroup_id='.$service_details[0]['item_id'].' and '.VIS_TABLE_PREFIX.'customfield.ci_type=2 and '.VIS_TABLE_PREFIX.'customfield_data.content!="" and '.VIS_TABLE_PREFIX.'customfield_data.parent_id='.$service_ticket_details[0]['service_id'];
				 $filter3 = VIS_TABLE_PREFIX.'customfield.customgroup_id='.$service_details[0]['item_id'].' and '.VIS_TABLE_PREFIX.'customfield.ci_type=2 and '.VIS_TABLE_PREFIX.'customfield_data.parent_id='.$service_ticket_details[0]['service_id'];
				 $service_custom_details=$setting_obj->get_service_custom_data($filter3, VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
            include(VIS_PATH_TEMPLATE.'ticket_details.php');
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
        }
        return true;
    }

    function get_properties($operation, $data='',$filter='') {
		//print_r($operation);
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff_object=new class_staff($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
        $staff_access=$staff_object->get_staff('staff_id='.VIS_STAFF_ID,VIS_STAFF_ID, VIS_LOCATION_AREA);
        $staff_department=$staff_access[0]['department_access'];
         if($staff_department==-2)
        {
			$tempfilter = VIS_TABLE_PREFIX.'staff_group.group_id = '.VIS_TABLE_PREFIX.'staff.group_id and '.VIS_TABLE_PREFIX.'staff_group.group_id='.$staff_access[0]['group_id'].' and '.VIS_TABLE_PREFIX.'staff.staff_id='.VIS_STAFF_ID;
			list($staffgroup_info, $staff_group)=$setting_object->get_staffgroup_ofstaff($tempfilter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($staffgroup_info['department_access']==0)
			$staff_department_array=$staffgroup_info['department_access'];
			else
			$staff_department_array=explode(',', $staffgroup_info['department_access']);
		}
		else
		{
			$staff_department_array=explode(',', $staff_department);
		}
        switch($operation) {
            case 'get_labels':
                $filter=' is_enabled=1 ';
                $label_department=$object->get_labels_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
                $label_department1='';
				$label_id=array();
                for($i=0;$i<count($label_department); $i++)
                {
					
					$department_list=$label_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$label_department[$i];
					}
					else
					{
					$label_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($label_department[$i]['label_id'],$label_id))
						{
							if(in_array($staff_department_array[$j], $label_department1))
							{
								$ret[]=$label_department[$i];
								$label_id[]=$label_department[$i]['label_id'];
							}
						}
						
					}
					}
				}     
            break;
            case 'get_filters':
                $ret=$object->get_filters_details('vscope=1 and (owner=0 or owner='.VIS_STAFF_ID.')', VIS_STAFF_ID, VIS_LOCATION_AREA);
            break;
            case 'get_staff':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
              
                $stafflist=$staff_object->get_staff($filter,VIS_STAFF_ID, VIS_LOCATION_AREA);
                $staff_department_list1='';
                $staff_id=array();
                for($i=0;$i<count($stafflist); $i++)
                {
					if($staff_department_array==0)
					{
					$ret[]=$stafflist[$i];
					}
					else{
					if($stafflist[$i]['department_access']==-2)
					{
						$filter_group = VIS_TABLE_PREFIX.'staff_group.group_id = '.VIS_TABLE_PREFIX.'staff.group_id and '.VIS_TABLE_PREFIX.'staff_group.group_id='.$stafflist[$i]['group_id'];
						list($staffgroup_info, $staff_group)=$setting_object->get_staffgroup_ofstaff($filter_group, VIS_STAFF_ID, VIS_LOCATION_AREA);
						$department_list=$staffgroup_info['department_access'];
					}
					else
					{
						$department_list=$stafflist[$i]['department_access'];
					}
					if($department_list==0 || $staff_department==0 )
					{
						$ret[]=$stafflist[$i];
					}
					else
					{
					$staff_department_list1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($stafflist[$i]['staff_id'],$staff_id))
						{
							if(in_array($staff_department_array[$j], $staff_department_list1))
							{
								$ret[]=$stafflist[$i];
								$staff_id[]=$stafflist[$i]['staff_id'];
							}
						}
						
					}
					}
				}
				}
            break;
            case 'get_departments':
                if(defined('VIS_ANY_DEPT') && VIS_ANY_DEPT==1) 
                {
					if($staff_department_array[0]==0 || $staff_department_array==0)
					{
						$ret=$object->get_all_department(VIS_TABLE_PREFIX.'department.is_enabled=1 ',VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
					else
					{
						$dept=array();
						$department_access=array();
						for($i=0;$i<count($staff_department_array); $i++)
						{
							include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'subsetting.php');
							$sub_object=new class_subsetting($database);
							$department=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$staff_department_array[$i], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
							$dept[]=$department[0];
						}
						for($i=0;$i<count($dept); $i++)
						{
							if($dept[$i]!='')
							$department_access[]=$dept[$i]['department_id'];
						}
						$department_access=array_unique($department_access);
						$department_access=implode(',', $department_access);
						if(substr($department_access, -1)==',') $department_access=substr($department_access,0,-1);
						$ret=$object->get_all_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id in ('.$department_access.')',VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
				}
                else $ret=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 ',VIS_STAFF_ID, VIS_LOCATION_AREA);
            break;
            case 'get_status':
				$status_id=array();
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
                $status_department=$object->get_status_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
                $status_department1='';
                for($i=0;$i<count($status_department); $i++)
                {
					
					$department_list=$status_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$status_department[$i];
					}
					else
					{
					$status_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($status_department[$i]['status_id'],$status_id))
						{
							if(in_array($staff_department_array[$j], $status_department1))
							{
								$ret[]=$status_department[$i];
								$status_id[]=$status_department[$i]['status_id'];
							}
						}
						
					}
					}
				}
            break;
            case 'get_priorities':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
                $priority_department=$object->get_priorities_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter);
                $priority_department1='';
				$priority_id=array();
                for($i=0;$i<count($priority_department); $i++)
                {
					
					$department_list=$priority_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$priority_department[$i];
					}
					else
					{
					$priority_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($priority_department[$i]['priority_id'],$priority_id))
						{
							if(in_array($staff_department_array[$j], $priority_department1))
							{
								$ret[]=$priority_department[$i];
								$priority_id[]=$priority_department[$i]['priority_id'];
							}
						}
						
					}
					}
				}
                
            break;
            case 'get_flags':
                $filter='is_enabled=1';
                $flag_department=$object->get_flags_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter); 
                $flag_department1='';
				$flag_id=array();
                for($i=0;$i<count($flag_department); $i++)
                {
					
					$department_list=$flag_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$flag_department[$i];
					}
					else
					{
					$flag_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($flag_department[$i]['flag_id'],$flag_id))
						{
							if(in_array($staff_department_array[$j], $flag_department1))
							{
								$ret[]=$flag_department[$i];
								$flag_id[]=$flag_department[$i]['flag_id'];
							}
						}
						
					}
					}
				}      
            break;
            case 'get_types':
                $filter='is_enabled=1';
                $type_department=$object->get_type_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter);
                $type_department1='';
				$type_id=array();
                for($i=0;$i<count($type_department); $i++)
                {
					
					$department_list=$type_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$type_department[$i];
					}
					else
					{
					$type_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($type_department[$i]['type_id'],$type_id))
						{
							if(in_array($staff_department_array[$j], $type_department1))
							{
								$ret[]=$type_department[$i];
								$type_id[]=$type_department[$i]['type_id'];
							}
						}
						
					}
					}
				}  
            break;
            case 'get_channel':
                $filter='is_enabled=1';
                $channel_departments=$object->get_channel($filter,VIS_STAFF_ID, VIS_LOCATION_AREA,'');
                $channel_departments1='';
				$channel_id=array();
                for($i=0;$i<count($channel_departments); $i++)
                {
					
					$department_list=$channel_departments[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$channel_departments[$i];
					}
					else
					{
					$channel_departments1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($channel_departments[$i]['channel_id'],$channel_id))
						{
						
							if(in_array($staff_department_array[$j], $channel_departments1))
							{
								$ret[]=$channel_departments[$i];
								$channel_id[]=$channel_departments[$i]['channel_id'];
							}
						}
						
					}
					}
				}
            break;
			case 'get_impacts':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
				list($impact_info, $impact_department)=$setting_object->get_impact($filter, '', '', 'display_order ASC', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$impact_department1='';
				$impact_id=array();
                for($i=0;$i<count($impact_department); $i++)
                {
					
					$department_list=$impact_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$impact_department[$i];
					}
					else
					{
					$impact_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($impact_department[$i]['impact_id'],$impact_id))
						{
							if(in_array($staff_department_array[$j], $impact_department1))
							{
								$ret[]=$impact_department[$i];
								$impact_id[]=$impact_department[$i]['impact_id'];
							}
						}
						
					}
					}
				}
            break;
            case 'get_risks':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
                list($risk_info, $risk_department)=$setting_object->get_risk($filter, '', '', 'display_order ASC', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$risk_department1='';
				$risk_id=array();
                for($i=0;$i<count($risk_department); $i++)
                {
					
					$department_list=$risk_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$risk_department[$i];
					}
					else
					{
					$risk_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($risk_department[$i]['risk_id'],$risk_id))
						{
							if(in_array($staff_department_array[$j], $risk_department1))
							{
								$ret[]=$risk_department[$i];
								$risk_id[]=$risk_department[$i]['risk_id'];
							}
						}
						
					}
					}
				}
            break;
			case 'get_releasetype':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
                list($release_type_info, $releasetype_department)=$setting_object->get_release_type($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$releasetype_department1='';
				$release_type_id=array();
                for($i=0;$i<count($releasetype_department); $i++)
                {
					
					$department_list=$releasetype_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$releasetype_department[$i];
					}
					else
					{
						$releasetype_department1=explode(',', $department_list);
						for($j=0;$j<count($staff_department_array); $j++)
						{
							if(!in_array($releasetype_department[$i]['release_type_id'],$release_type_id))
							{
								if(in_array($staff_department_array[$j], $releasetype_department1))
								{
									$ret[]=$releasetype_department[$i];
									$release_type_id[]=$releasetype_department[$i]['release_type_id'];
								}
							}
						}
					}
				}
            break;
			case 'get_changetype':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
                list($release_type_info, $changetype_department)=$setting_object->get_change_type($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$changetype_department1='';
				$change_type_id=array();
                for($i=0;$i<count($changetype_department); $i++)
                {
					
					$department_list=$changetype_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$changetype_department[$i];
					}
					else
					{
						$changetype_department1=explode(',', $department_list);
						for($j=0;$j<count($staff_department_array); $j++)
						{
							if(!in_array($changetype_department[$i]['change_type_id'],$change_type_id))
							{
								if(in_array($staff_department_array[$j], $changetype_department1))
								{
									$ret[]=$changetype_department[$i];
									$change_type_id[]=$changetype_department[$i]['change_type_id'];
								}
							}
						}
					}
				}
            break;
            case 'get_licensetype':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
                list($license_type_info, $licensetype_department)=$setting_object->get_license_type($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$licensetype_department1='';
				$license_type_id=array();
                for($i=0;$i<count($licensetype_department); $i++)
                {
					
					$department_list=$licensetype_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$licensetype_department[$i];
					}
					else
					{
						$licensetype_department1=explode(',', $department_list);
						for($j=0;$j<count($staff_department_array); $j++)
						{
							if(!in_array($licensetype_department[$i]['license_type_id'],$license_type_id))
							{
								if(in_array($staff_department_array[$j], $licensetype_department1))
								{
									$ret[]=$licensetype_department[$i];
									$license_type_id[]=$licensetype_department[$i]['license_type_id'];
								}
							}
						}
					}
				}
            break;
             case 'get_contracttype':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
                list($contract_type_info, $contracttype_department)=$setting_object->get_contract_type($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$contracttype_department1='';
				$contract_type_id=array();
                for($i=0;$i<count($contracttype_department); $i++)
                {
					
					$department_list=$contracttype_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$contracttype_department[$i];
					}
					else
					{
						$contracttype_department1=explode(',', $department_list);
						for($j=0;$j<count($staff_department_array); $j++)
						{
							if(!in_array($contracttype_department[$i]['contract_type_id'],$contract_type_id))
							{
								if(in_array($staff_department_array[$j], $contracttype_department1))
								{
									$ret[]=$contracttype_department[$i];
									$contract_type_id[]=$contracttype_department[$i]['contract_type_id'];
								}
							}
						}
					}
				}
            break;
            case 'get_product':
                if($filter!='') $filter =  $filter. ' and '.VIS_TABLE_PREFIX.'itil_ci_product.is_enabled=1';
                else $filter =''.VIS_TABLE_PREFIX.'itil_ci_product.is_enabled=1';
				
                list($product_info, $product_department)=$setting_object->get_ci_product($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
                if($product_info['total']!=0)
                {
					$product_department1='';
					$product_id=array();
					for($i=0;$i<count($product_department); $i++)
					{
						
						$department_list=$product_department[$i]['department_access'];
						if($department_list==0 || $staff_department==0 || $staff_department_array==0)
						{
							$ret[]=$product_department[$i];
						}
						else
						{
							$product_department1=explode(',', $department_list);
							for($j=0;$j<count($staff_department_array); $j++)
							{
								if(!in_array($product_department[$i]['product_id'],$product_id))
								{
									if(in_array($staff_department_array[$j], $product_department1))
									{
										$ret[]=$product_department[$i];
										$product_id[]=$product_department[$i]['product_id'];
									}
								}
							}
						}
					}
				}
            break;
            case 'get_location':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				if( VIS_LOCATION_AREA==1 ) $chk.=' and access_type=0';
				else $chk='';
				$filter.=$chk;
               $location_department=$setting_object->get_locations(' and is_enabled=1',0, -1, '', VIS_STAFF_ID);
				$location_department1='';
				$location_id=array();
                for($i=0;$i<count($location_department); $i++)
                {
					
					$department_list=$location_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$location_department[$i];
					}
					else
					{
						$location_department1=explode(',', $department_list);
						for($j=0;$j<count($staff_department_array); $j++)
						{
							if(!in_array($location_department[$i]['location_id'],$location_id))
							{
								if(in_array($staff_department_array[$j], $location_department1))
								{
									$ret[]=$location_department[$i];
									$location_id[]=$location_department[$i]['location_id'];
								}
							}
						}
					}
				}
            break;
            case 'get_configuration_item':
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
                $configuration_department=$setting_object->get_configuration_item($filter, 0, -1, $sort_by='', '');
				$configuration_department1='';
				$configuration_id=array();
                for($i=0;$i<count($configuration_department); $i++)
                {
					
					$department_list=$configuration_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$configuration_department[$i];
					}
					else
					{
						$configuration_department1=explode(',', $department_list);
						for($j=0;$j<count($staff_department_array); $j++)
						{
							if(!in_array($configuration_department[$i]['item_id'],$configuration_id))
							{
								if(in_array($staff_department_array[$j], $configuration_department1))
								{
									$ret[]=$configuration_department[$i];
									$configuration_id[]=$configuration_department[$i]['item_id'];
								}
							}
						}
					}
				}
            break;
            case 'get_owner':
                $ret=$staff_object->get_staff('is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
            break;
			case 'get_macros':
                $ret = $staff_object->get_macros_list('is_enabled=1 and (department = '.$data['vis_department_id'].' or department = 0)', VIS_STAFF_ID, VIS_LOCATION_AREA);
            break;
			case 'get_category':
				$category_id=array();
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				list($parent_count,$category_department) =$setting_object->get_ticket_category_list($filter,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
                   $category_department1='';
                for($i=0;$i<count($category_department); $i++)
                {
					
					$department_list=$category_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$category_department[$i];
					}
					else
					{
					$category_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($category_department[$i]['category_id'],$category_id))
						{
							if(in_array($staff_department_array[$j], $category_department1))
							{
								$ret[]=$category_department[$i];
								$category_id[]=$category_department[$i]['category_id'];
							}
						}
						
					}
					}
				}
            break;
			
			case 'get_subcategory':
				$categorydata=$this->get_properties('get_category','');
				$category_id=array();
				if(isset($categorydata)){
				foreach($categorydata as $categorydatas){$category_id[]=$categorydatas['category_id'];}					
						$categoryid=implode(',',$category_id);
				}
				
				$subcategory_id=array();
                if($filter!='') $filter =  $filter. ' and '.VIS_TABLE_PREFIX.'ticket_subcategory.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_subcategory.category_id IN ('.$categoryid.')';
                else $filter =VIS_TABLE_PREFIX.'ticket_subcategory.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_subcategory.category_id IN ('.$categoryid.')';
				list($parent_count,$subcategory_department) =$setting_object->get_ticket_subcategory_list($filter,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
                
                $subcategory_department1='';
                for($i=0;$i<count($subcategory_department); $i++)
                {
					
					$department_list=$subcategory_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$subcategory_department[$i];
					}
					else
					{
					$subcategory_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($subcategory_department[$i]['subcategory_id'],$subcategory_id))
						{
							if(in_array($staff_department_array[$j], $subcategory_department1))
							{
								$ret[]=$subcategory_department[$i];
								$subcategory_id[]=$subcategory_department[$i]['subcategory_id'];
							}
						}
						
					}
					}
				}
            break;
			
			case 'get_item':
				$subcategorydata=$this->get_properties('get_subcategory','');
				$subcategory_id=array();
				if(isset($subcategorydata)){
				foreach($subcategorydata as $subcategorydatas){$subcategory_id[]=$subcategorydatas['subcategory_id'];}					
						$subcategoryid=implode(',',$subcategory_id);
				
				
				$item_id=array();
                if($filter!='') $filter =  $filter. ' and '.VIS_TABLE_PREFIX.'ticket_item.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_item.subcategory_id IN ('.$subcategoryid.')';
                else $filter =VIS_TABLE_PREFIX.'ticket_item.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_item.subcategory_id IN ('.$subcategoryid.')';
				list($item_count,$item_department) =$setting_object->get_ticket_item_list($filter,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
                
                $item_department1='';
                for($i=0;$i<count($item_department); $i++)
                {
					
					$department_list=$item_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$item_department[$i];
					}
					else
					{
					$item_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($item_department[$i]['item_id'],$item_id))
						{
							if(in_array($staff_department_array[$j], $item_department1))
							{
								$ret[]=$item_department[$i];
								$item_id[]=$item_department[$i]['item_id'];
							}
						}
						
					}
					}
				}
				}else{
				$ret=false;	
				}// check subcat avilable
            break;
			
			case 'get_level':
				
				$level_id=array();
                if($filter!='') $filter =  $filter. ' and is_enabled=1';
                else $filter ='is_enabled=1';
				list($parent_count,$level_department) =$setting_object->get_ticket_level_list($filter,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
                
                $level_department1='';
                for($i=0;$i<count($level_department); $i++)
                {
					
					$department_list=$level_department[$i]['department_access'];
					if($department_list==0 || $staff_department==0 || $staff_department_array==0)
					{
						$ret[]=$level_department[$i];
					}
					else
					{
					$level_department1=explode(',', $department_list);
					for($j=0;$j<count($staff_department_array); $j++)
					{
						if(!in_array($level_department[$i]['level_id'],$level_id))
						{
							if(in_array($staff_department_array[$j], $level_department1))
							{
								$ret[]=$level_department[$i];
								$level_id[]=$level_department[$i]['level_id'];
							}
						}
						
					}
					}
				}
            break;
			
			
            default: $ret=false;
        }
        return $ret;
    }

    function list_contents($operation) {
        $list=$this->get_properties($operation['vis_action'], $operation);
        $flag=$operation['vis_action'];
        include_once(VIS_PATH_TEMPLATE.'ticket_properties.php');
        return true;
    }

    function update_properties($operation) {
        global $vis_language; 
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
        $list_chk=array();
        if(isset($operation['vis_dept_id']) && $operation['vis_dept_id']!='') $department=$operation['vis_dept_id'];
        if(isset($operation['vis_dept_id']) && $operation['vis_dept_id']=='' && $operation['dept']!=''){
            $department_list=array();
            for($i=0;$i<count($operation['dept']);$i++){
                $temp=explode('-',$operation['dept'][$i]);
                $department_list[$i]=$temp[0];
            }
        }
        if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
            $property=$operation['vis_action'];
            $list_chk[]=$operation['vis_ticket_id'];
            $area=0;
        } else {
            $options=parse_form_array($operation['vis_action']);
            $property=$options['action'];
            $operation['vis_action']=$property;
            $operation['vis_total_ticket']=$options['vis_total_ticket'];
            $operation['vis_total_page']=$options['vis_total_page'];
            $operation['pageing']=$options['pageing'];
            $operation['vis_filter_id']=$options['vis_filter_id'];
            foreach($options as $data=>$value) if(preg_match('/vis_ticket_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
            $area=1;
        }         
        if(empty($list_chk)){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        if($property=='link' && (count($list_chk)<2)){
             echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNGLTKTLINK'].'");</script>';
            return false;
        }
        if(!isset($operation['vis_ticket_id']) && !is_numeric($operation['vis_ticket_id'])){
		if($property=='staff')
        {
			 $filter='is_enabled=1 and staff_id='.$operation['vis_update_id'];
			 include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
             $staff_object=new class_staff($database);
             $stafflist=$staff_object->get_staff($filter,VIS_STAFF_ID, VIS_LOCATION_AREA);
             $staff_dept_access=explode(',', $stafflist[0]['department_access']);
             if($stafflist[0]['department_access']!=0)
             {
				 if($stafflist[0]['department_access']==-2)
					{
						$filter = VIS_TABLE_PREFIX.'staff_group.group_id = '.VIS_TABLE_PREFIX.'staff.group_id and '.VIS_TABLE_PREFIX.'staff_group.group_id='.$stafflist[0]['group_id'];
						list($staffgroup_info, $staff_group)=$setting_object->get_staffgroup_ofstaff($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						$staff_dept_access=explode(',', $staffgroup_info['department_access']);
					}
				 if($department!='' && !in_array($department, $staff_dept_access)) 
				 {
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
					return false;
				 }else{
                     if($staff_dept_access[0]!=0) for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $staff_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
        if($property=='status')
        {
			 $filter='is_enabled=1 and status_id='.$operation['vis_update_id'];
             $status_department=$ticket_object->get_status_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
             $status_dept_access=explode(',', $status_department[0]['department_access']);
             if($status_department[0]['department_access']!=0)
             {
                 if($department!=''){
                    if(!in_array($department, $status_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $status_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		if($property=='priority')
        {
			 $filter='is_enabled=1 and priority_id='.$operation['vis_update_id'];
             $priority_department=$ticket_object->get_priorities_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter);
             $priority_dept_access=explode(',', $priority_department[0]['department_access']);
             if($priority_department[0]['department_access']!=0)
             {
                 if($department!=''){
                    if(!in_array($department, $priority_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $priority_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		if($property=='type')
        {
			 $filter='is_enabled=1 and type_id='.$operation['vis_update_id'];
             $type_department=$ticket_object->get_type_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter);
             $type_dept_access=explode(',', $type_department[0]['department_access']);
             if($type_department[0]['department_access']!=0)
             {
                 if($department!=''){
                    if(!in_array($department, $type_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $type_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		if($property=='flag')
        {
			 $filter='is_enabled=1 and flag_id='.$operation['vis_update_id'];
             $flag_department=$ticket_object->get_flags_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter); 
             $flag_dept_access=explode(',', $flag_department[0]['department_access']);
             if($flag_department[0]['department_access']!=0)
             {
                if($department!=''){
                    if(!in_array($department, $flag_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $flag_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		if($property=='label')
        {
			 $filter='label_id='.$operation['vis_update_id'];
             $label_department=$ticket_object->get_labels_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
             $label_dept_access=explode(',', $label_department[0]['department_access']);
             if($label_department[0]['department_access']!=0)
             {
                if($department!=''){
				 if(!in_array($department, $label_dept_access)) 
				 {
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
					return false;
				 }
                }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $label_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		if($property=='level')
        {
			 $filter='is_enabled=1 and level_id='.$operation['vis_update_id'];
             list($ticket_level_count, $type_department)=$setting_object->get_ticket_level_list( $filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,'');
             $type_dept_access=explode(',', $type_department[0]['department_access']);
             if($type_department[0]['department_access']!=0)
             {
                 if($department!=''){
                    if(!in_array($department, $type_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $type_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		if($property=='ticket_category')
        {
			 $filter='is_enabled=1 and category_id='.$operation['vis_update_id'];
			 list($ticket_cat_count,$type_department)=$setting_object->get_ticket_category_list($filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,'');
             $type_dept_access=explode(',', $type_department[0]['department_access']);
             if($type_department[0]['department_access']!=0)
             {
                 if($department!=''){
                    if(!in_array($department, $type_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $type_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		
		if($property=='assets_location')
        {
			$filter='is_enabled=1 and category_id='.$operation['vis_update_id'];
			$location_assets=$setting_object->get_locations(" AND ".VIS_TABLE_PREFIX."itil_location.location_id = ".$operation['vis_update_id'],0, -1, '', VIS_STAFF_ID);
             $type_dept_access=explode(',', $type_department[0]['department_access']);
             if($type_department[0]['department_access']!=0)
             {
                 if($department!=''){
                    if(!in_array($department, $type_dept_access)) 
                    {
                       echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
                       return false;
                    }
                 }else{
                     for($k=0;$k<count($department_list);$k++){
                         if(!in_array($department_list[$k], $type_dept_access)) {
                             unset($list_chk[$k]);
                         }
                     }
                 }
			 }
		}
		}
        $templist=array();
        $j=0;
        foreach($list_chk as $list){
            $templist[$j++]=$list;
        }
        $list_chk=$templist;
		
		$user=defined('VIS_CLIENT_ID')?VIS_CLIENT_ID:VIS_STAFF_ID;
		
        if(isset($operation['vis_update_id']) && is_numeric($operation['vis_update_id'])) {
            $database=new class_database();
            global $operation_hnd;
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
            $ticket_object=new class_ticket($database);
            $ret=$ticket_object->set_ticket_property($property, $operation, $list_chk, $user, VIS_LOCATION_AREA);
            for($i=0;$i<count($list_chk);$i++) {
                $operation['vis_ticket_id']=$list_chk[$i];
            if($property=='status' && $operation['vis_update_id']==3 && VIS_LOCATION_AREA==1){
                $data['vis_operation']='close_ticket';
                $data['vis_ticket_id']=$operation['vis_ticket_id'];
                $operation_hnd->check_automation($data, $database);
            }
                $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
				
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
				$staff_object=new class_staff($database);
				$staff_object->apply_task_automation($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
				
            }
            $database->database_disconnect();
            if(VIS_LOCATION_AREA==0) {
                echo ($ret)?'success':'error';
            }
            else {
                if(!$ret && $property=='link'){
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("[id^=\'vis_ticket_mass_chk_\']").attr("checked",false); </script>';
                }
                else if(!$ret) {
                    $msg = ($property == 'department' && VIS_DEPARTMENT_ACCESS!=0) ? $vis_language['MSGMOVETODEPT'] : $vis_language['MSGACCSSDND'];
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$msg.'");</script>';
                    return false;
                }
                else { 
					echo '<script>';
                    if($area==0) {
                        //if($property=='delete' || $property=='spam' || $property=='ban')
                        if($property=='delete' || $property=='spam')
                            echo "$('#vis_workpanel_div').visExecution('load_module', '".$vis_language['TXTTICKETS']."', {'vis_module':'ticket', 'vis_operation':'filter_ticket', 'vis_filter_id': 1});";
                        else {
                            echo ' $("#vis_details_list_'.$operation['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_action":"details", "vis_ticket_id":'.$operation['vis_ticket_id'].'});';
                        } 
                    }
                    else{
						if($options['vis_export_function'] == '3')
							echo "$('#vis_workpanel_div').visExecution('load_area', {'vis_module':'ticket', 'vis_operation':'filter_ticket', 'vis_filter_id': ".$options['vis_filter_id']."});";
						else if($options['vis_export_function'] == 'filter_queue_ticket'){
							if(isset($options['vis_filter_id']) && strstr($options['vis_filter_id'], '-')) {
								$info=explode('-', $options['vis_filter_id']);
								echo "$('#vis_workpanel_div').visExecution('load_area', {'vis_module':'ticket', 'vis_operation':'filter_queue_ticket', 'vis_department_id':".$info[1].", 'vis_status_id':".$info[0]."});";
							}
							else 
								echo "$('#vis_workpanel_div').visExecution('load_area', {'vis_module':'ticket', 'vis_operation':'filter_ticket', 'vis_filter_id': ".$options['vis_filter_id']."});";
						}
                        else if($options['vis_export_function'] == 'filter_ticket_group'){
								echo "$('#vis_workpanel_div').visExecution('load_area', {'vis_module':'ticket', 'vis_operation':'filter_ticket_group', 'vis_group_name':'".$options['vis_group_name']."', 'vis_group_id':".$options['vis_group_id']."});";
						}
						else if($property != 'department' || ($property == 'department' && VIS_DEPARTMENT_ACCESS!=0)) echo "$('#vis_workpanel_div').visExecution('load_area', {'vis_module':'ticket', 'vis_operation':'filter_ticket', 'vis_filter_id': ".$options['vis_filter_id'].",'vis_tag':'tag'});";
						else if($property == 'department' && VIS_DEPARTMENT_ACCESS==0)  echo "$('#vis_global_msg_div').visInterface('load_global_message', '".$vis_language['MSGACCSSDND']."');";
					}
                    //if($property=='department' || $property=='status' || $property=='delete' || $property=='spam' || $property=='ban' || $property=='staff') echo ' $("#vis_global_msg_div").visExecution("load_operations",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"}); ';
                    if( $property=='delete' || $property=='spam' || $property=='status' || ($property == 'department' && VIS_DEPARTMENT_ACCESS!=0) )
						echo '$("#vis_global_msg_div").visExecution("load_operations",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"});';
                    if($options['vis_export_function'] == 'filter_queue_ticket' || $options['vis_export_function'] == 'filter_ticket') { 
						if($property != 'department' || ($property == 'department' && VIS_DEPARTMENT_ACCESS!=0))
						echo '$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");'; 
						else if($property == 'department' && VIS_DEPARTMENT_ACCESS==0) echo '$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGACCSSDND'].'");'; }
                    echo '</script>';
                }
            }
            return $ret;
        }
        else {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'"); </script>';
            return false;
        }
    }

    function ticket_update($operation) {
        global $vis_language, $operation_hnd;
        if(!(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))) {
            $operation['message']=$vis_language['MSGERROPRT'];
            return $this->view_ticket($operation);
        }
        $user=defined('VIS_CLIENT_ID')?VIS_CLIENT_ID:VIS_STAFF_ID;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff=new class_staff($database);

        $ret=$ticket_object->set_ticket_property('type', $operation['vis_ticket_type'], array($operation['vis_ticket_id']), $user, VIS_LOCATION_AREA);
        if($ret!==-1) {
            $operation['vis_action']='type';
            $operation['vis_operation']='update_properties';
            $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($operation,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
        }
        $ret=$ticket_object->set_ticket_property('status', $operation['vis_ticket_status'], array($operation['vis_ticket_id']), $user, VIS_LOCATION_AREA);
        if($ret!==-1) {
            $operation['vis_action']='status';
            $operation['vis_operation']='update_properties';
            $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($operation,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);

        }
        $ret=$ticket_object->set_ticket_property('priority', $operation['vis_ticket_priority'], array($operation['vis_ticket_id']), $user, VIS_LOCATION_AREA);
        if($ret!==-1) {
            $operation['vis_action']='priority';
            $operation['vis_operation']='update_properties';
            $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($operation,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
        }
        $database->database_disconnect();
        $operation['message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
        if(VIS_LOCATION_AREA==1) echo json_encode( array('vis_msg' => $operation['message']) );
        else $this->ticket_details($operation);
        return true;
    }

    function get_details($operation) {
        global $vis_language;
        switch($operation['vis_action']) {
            case 'details':
                if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                    $database=new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$object=new class_setting($database);
					list($info, $modules)=$object->get_module('is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					foreach($modules as $var) $module[$var['module']]=1;
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $ticket_object=new class_ticket($database);
                    $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
                    list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					if($ticket_details==-1) {
                        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTNTACC'].'"); $(this).visInterface("remove_tab", "vis_module_ticket_div"); </script>';
                        return false;
                    }
					$module_setting1=$object->get_module_setting('domain_id='.$ticket_details[0]['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		
                    $setting=new class_setting($database);
					
					if(VIS_ITIL==1 && isset($module['itil']) && $module['itil']==1)$itil_enabled=1;
					if($itil_enabled==1){
						 $filter1='ticket_id='.$operation['vis_ticket_id'];
						 $service_ticket_details=$ticket_object->get_service_ticket_list($filter1,'', VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						 $filter3='parent_id='.$operation['vis_ticket_id'].' and attach_type=0';
						 $attach_ci_details = $setting->get_attach_relation_list($filter3,'',VIS_STAFF_ID, VIS_LOCATION_AREA); 
						
						 $filter6='parent_id='.$operation['vis_ticket_id'].' and attach_type=1';
						 $attach_problem_details = $setting->get_attach_relation_list($filter6,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						 $filter8='parent_id='.$operation['vis_ticket_id'].' and attach_type=6';

						 $attach_changes_details = $setting->get_attach_relation_list($filter8,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
				
					}
						 $filter9='parent_id='.$operation['vis_ticket_id'].' and attach_type=12';
						 $attach_task_details = $setting->get_attach_relation_list($filter9,'',VIS_STAFF_ID, VIS_LOCATION_AREA);
							
								//THIS ONE FOR APPROVAL TICKET
						$filter = " approvals_type=0 AND ".VIS_TABLE_PREFIX."ticket_approvals.is_enabled=1 AND parent_id=".$operation['vis_ticket_id'];
						list($total_approvals, $approvals_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						$filter = " approvals_type=0 AND ".VIS_TABLE_PREFIX."ticket_approvals.is_enabled=1 AND ".VIS_TABLE_PREFIX."ticket_approvals.staff_id=".VIS_STAFF_ID." AND parent_id=".$operation['vis_ticket_id'];
						list($single_approvals, $single_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						 
						$filter = " approvals_type=0 AND remark!='' AND parent_id=".$operation['vis_ticket_id'];
						list($total_remark, $remark_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID,VIS_LOCATION_AREA);

						$filter= ' is_enabled=1 AND parent_id='.$operation['vis_ticket_id'];
						$approvals_status=$ticket_object->get_approvals_status($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						//THIS ONE FOR APPROVAL TICKET ENDS
					
                    $filter=VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$operation['vis_ticket_id'];
                    $owner_details=$ticket_object->get_ticket_owner($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
                    $label_details = $ticket_object->get_ticket_labels($operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                    $tag_details = $ticket_object->get_ticket_tag($operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$sett_obj=new class_setting($database);
                    $module_setting=$sett_obj->get_module_setting('(title="vis_show_note" or title="vis_show_custom_field") and domain_id='.$ticket_details[0]['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA); 
                    if(VIS_LOCATION_AREA==0) $module_setting['vis_show_note']=1;
					$note_details=(VIS_NOTE_ACCESS==0 || !$module_setting['vis_show_note'])?-1:$ticket_object->get_note($ticket_details[0]['ticket_id'], $ticket_details[0]['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
					$invoices=$ticket_object->get_billing_counts($ticket_details[0]['ticket_id'], $ticket_details[0]['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                    if(isset($operation['vis_readonly']) && $operation['vis_readonly']==1) $readonly=1;
                    else $readonly=0;
                    
                    $location11=array(0=>'1', 1=>'2',2=>'11');
                    $custom_field_var=(!$module_setting['vis_show_custom_field'])?-1:$this->edit_custom_fields($location11, $operation['vis_ticket_id'], $ticket_details[0]['department_id'], $database,$readonly);
                    $location22=array(0=>'0', 1=>'3', 2=>'3');
                    if($custom_field_var == 'Data not available'){$nodata = 1 ;$custom_field_var='';}
                    $custom_field_varfeedback=(!$module_setting['vis_show_custom_field'])?-1:$this->edit_custom_fields($location22, $operation['vis_ticket_id'], $ticket_details[0]['department_id'], $database,1); 
					if($custom_field_varfeedback == 'Data not available'){$nodata = 1 ;$custom_field_varfeedback='';}
                    if($custom_field_var == ''){$custom_field_var=$vis_language['MSGRECORDMISS'];}
					 if($custom_field_varfeedback == ''){$custom_field_varfeedback=$vis_language['MSGRECORDMISS'];}
                    $custIds = $ticket_object->get_custom_fields_id($ticket_details[0]['ticket_id']); //feedback details
                    if(!$ticket_details) {
                        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
                        return false;
                    }		
                    $ticket_details=$ticket_details[0];                                   
                    $database->database_disconnect();
                    if(VIS_LOCATION_AREA==0) {
                        $ret=array();
                        if($label_details!=-1) $ret['label']=$label_details;
                        if($tag_details!=-1) $ret['tag']=$tag_details;
                        if($note_details!=-1) $ret['note']=$note_details;
                        echo get_xml($ret, 'ticket_details');
                        return true;
                    }
                    else {
                        include_once(VIS_PATH_TEMPLATE.'ticket_details.php');
                        return true;
                    }
                }
                else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
                    return false;
                }
            break;
												
												case 'approvals':
			       
				   if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                    $database=new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $ticket_object=new class_ticket($database);
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
					$problem_object=new class_problem($database);
					
                    $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
					list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					if($ticket_details==-1) {
                        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCHANGESIDMISS'].'"); $(this).visInterface("remove_tab", "vis_module_ticket_div"); </script>';
                        return false;
                    }
					
					$ticket_details=$ticket_details[0];
					$filter = " approvals_type=0 AND ".VIS_TABLE_PREFIX."ticket_approvals.is_enabled=1 AND parent_id=".$ticket_details['ticket_id'];
					list($total_approvals, $approvals_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
					
					$filter2 = " approvals_type=0 AND remark!='' AND parent_id=".$ticket_details['ticket_id'];
					list($total_remark, $remark_details)=$ticket_object->get_approvals($filter2, VIS_STAFF_ID, VIS_LOCATION_AREA);
					
					
                    $database->database_disconnect();
                    include_once(VIS_PATH_TEMPLATE.'ticket_approvals_list.php');
                    return true;
                }
                else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCHANGESIDMISS'].'"); </script>';
                    return false;
                }
				break;
            case 'audit_log':
                if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                    $database=new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $object=new class_ticket($database);
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');  
                    $staff=new class_staff($database);
					list($view_info, $view_details)=$staff->get_ticket_view(VIS_STAFF_ID, VIS_LOCATION_AREA);
                    $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;     
					$limit=($page*$view_info['page_count']).','.$view_info['page_count'];	
                    list($audit_log_info, $audit_log)=$object->audit_log($operation['vis_ticket_id'], $limit, $page, VIS_STAFF_ID, VIS_LOCATION_AREA);
                    $view_info['page_count']=($audit_log_info['total']==0)?0:ceil($audit_log_info['total']/$view_info['page_count']);
					$audit_log_info['page']=$page;
					$view_info['view_count']=count($view_details);
                    $audit_count=($audit_log==-1)?0:count($audit_log);
                    for($i=0 ; $i<$audit_count ; $i++)
                    {
							 switch($audit_log[$i]['operation_id']) {
								case '0':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGNEWTKTCRT'];
									break;
									
								case '1':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTKTRPLD'];
									break;
								
								case '2':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTSTATUSCHANGEDFROM'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
									
								case '3':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTPRIORITYCHANGEDFROM'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
									
								case '4':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTDEPARTMENTCHANGEDFROM'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
									
								case '5':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTTICKETTYPECHANGEDFROM'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
									
								case '6':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTFLAGCHANGEDFROM'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
									
								case '7':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');  
									$object=new class_setting($database);
									$staff_new_info=$object->get_staff(VIS_TABLE_PREFIX.'staff.staff_id='.$audit_log[$i]['new_info'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA,1);
									$new_info =  $staff_new_info[1][0]['first_name'].' '.$staff_new_info[1][0]['last_name'];
									if($audit_log[$i]['new_info']!=0 && $staff_new_info[1]!=-1)
                                        $audit_log[$i]['audit_log_operation'] = $vis_language['MSGTKTASSIG'].' '.$vis_language['TXTTO'].' '. $new_info;
                                    elseif($audit_log[$i]['new_info']==0 && $audit_log[$i]['old_info']>0){ 
                                        $staff_old_info=$object->get_staff(VIS_TABLE_PREFIX.'staff.staff_id='.$audit_log[$i]['old_info'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA,1);
                                        $old_info =  $staff_old_info[1][0]['first_name'].' '.$staff_old_info[1][0]['last_name'];
                                        $audit_log[$i]['audit_log_operation'] = $vis_language['TXTTICKETUNASSIGNEDFROM'].' '. $old_info;
                                    }
									else
                                        $audit_log[$i]['audit_log_operation'] = $vis_language['TXTTICKETASSIGNEDTONOBODY'];
									break;
									
								case '8':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');  
									$object=new class_setting($database);
									$staff_details=$object->get_staff(VIS_TABLE_PREFIX.'staff.staff_id='.$audit_log[$i]['operator_id'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
									$staff_name =  $staff_details[1][0]['first_name'].' '.$staff_details[1][0]['last_name'];
									if($audit_log[$i]['old_info']!=0 )
										$audit_log[$i]['audit_log_operation']=$vis_language['MSGTKTTRSH'];
									elseif($audit_log[$i]['old_info']==0 )
										$audit_log[$i]['audit_log_operation']=$vis_language['TXTTKTMOVEINBOCFROMTRASH'];
									break;
									
								case '9':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');  
									$object=new class_setting($database);
									$staff_details=$object->get_staff(VIS_TABLE_PREFIX.'staff.staff_id='.$audit_log[$i]['operator_id'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
									$staff_name =  $staff_details[1][0]['first_name'].' '.$staff_details[1][0]['last_name'];
									$audit_log[$i]['audit_log_operation']=$audit_log[$i+1]['old_info'] .' deleted';
									break;

								case '10':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
									$object=new class_ticket($database);
									$audit_log[$i]['audit_log_operation']=$audit_log[$i]['new_info'] .' merged to '.$audit_log[$i]['old_info'];
									break;
									
								case '11':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTKTFRWD'];
									break;
									
								case '12':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTKTDELETED'];
									break;
									
								case '13':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');  
									$object=new class_setting($database);
									$sla_old_info=$object->get_sla(VIS_TABLE_PREFIX.'sla.sla_id='.$audit_log[$i]['old_info'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
									$sla_new_info=$object->get_sla(VIS_TABLE_PREFIX.'sla.sla_id='.$audit_log[$i]['new_info'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
								    $old_info =  $sla_old_info[1][0]['sla_name'];
									$new_info =  $sla_new_info[1][0]['sla_name'];
									if($audit_log[$i]['new_info']==-1){$new_info=$vis_language['TXTNONE'];}
									if($audit_log[$i]['new_info']!=0 && $audit_log[$i]['old_info']!=0)
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTSLACHANGEDFROM'].' '. $old_info. ' to '. $new_info;
									else if($audit_log[$i]['old_info']==0 && $audit_log[$i]['new_info']!=0)
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTSLASETTO'].' '. $new_info;
									else if($audit_log[$i]['new_info']==0)
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTAPPLIEDCUSTOMSLAPLAN'];
									else if($audit_log[$i]['new_info']==-1)
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTAPPLIEDCUSTOMSLAPLAN'].' '.$vis_language['TXTNONE'];
									break;
									
								case '14':
									if($audit_log[$i]['new_info']!=0 && $audit_log[$i]['old_info']==0)
										$audit_log[$i]['audit_log_operation']=$vis_language['MSGSPAMMRK'];
									elseif($audit_log[$i]['new_info']==0 && $audit_log[$i]['old_info']!=0)
										$audit_log[$i]['audit_log_operation']=$vis_language['TXTNOTSPAMMARKED'];
									break;
									
								case '15':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGUNSPAM'];
									break;
								case '16':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTNEWTASKATTACHED'].' '. $audit_log[$i]['old_info'];
									break;
								case '17':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTDETACHEDATTACHEDTASK'].' '. $audit_log[$i]['old_info'];
									break;
								case '18':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTNEWCIATTACHED'].' '. $audit_log[$i]['old_info'];
									break;
								case '19':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTDETACHEDATTACHEDCI'].' '. $audit_log[$i]['old_info'];
									break;
								case '20':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTNEWPROBLEMATTACHED'].' '. $audit_log[$i]['old_info'];
									break;
								case '21':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTDETACHEDATTACHEDPROBLEM'].' '. $audit_log[$i]['old_info'];
									break;
								case '22':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTNEWCHANGEATTACHED'].' '. $audit_log[$i]['old_info'];
									break;
								case '23':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTDETACHEDATTACHEDCHANGE'].' '. $audit_log[$i]['old_info'];
									break;	
								case '24':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
									$object=new class_ticket($database);
									$audit_log[$i]['audit_log_operation']=$audit_log[$i]['new_info'] .' '.$vis_language['TXTLINKEDTO'].' '.$audit_log[$i]['old_info'];
									break;	
								case '25':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
									$object=new class_ticket($database);
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETPOSTDELETE'];
									break;	
								case '26':
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
									$object=new class_ticket($database);
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTTICKETPOSTSPLITWITH'].' '.$audit_log[$i]['new_info'];
									break;	
								case '27':
									$audit_log[$i]['audit_log_operation'] = $vis_language['TXTCHANNELCHANGEDFROM'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
								case '28':
									$audit_log[$i]['audit_log_operation']=$audit_log[$i]['old_info'] .' '.$vis_language['TXTUNLINKEDFROM'].' '.$audit_log[$i]['new_info'];
									break;	
								case '29':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTSET'].' '.$audit_log[$i]['new_info'] .' '.$vis_language['TXTLABEL'];
									break;	
								case '30':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTPINNED'].' '.$audit_log[$i]['old_info'];
									break;
								case '31':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTREMOVEDLABEL'].' '.$audit_log[$i]['new_info'];
									break;
								case '32':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETPROPERTYUPDATED'];
									break;
								case '33':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETNOTEADDED'];
									break;
								case '34':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETNOTEDELETED'];
									break;
								case '35':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETCOMMENTADDED'];
									break;
								case '36':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETCOMMENTDELETED'];
									break;
								case '37':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKETPOSTUPDATED'];
									break;
								case '38':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGADDEDNEWRECIPIENT'].' '.$audit_log[$i]['new_info'];
									break;
								case '39':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGADDEDNEWPEOPLE'].' '.$audit_log[$i]['new_info'];
									break;
								case '40':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGREMOVEDRECIPIENT'].' '.$audit_log[$i]['new_info'];
									break;
								case '41':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGREMOVEDPEOPLE'].' '.$audit_log[$i]['new_info'];
									break;
								case '42':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGADDEDNEWTAG'].' '.$audit_log[$i]['new_info'];
									break;
								case '43':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGTICKHASHLINK'].' '.$audit_log[$i]['new_info'];
									break;
								case '44':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGNEWSCHEDULETKTCRT'];
									break;
								case '45':
									$audit_log[$i]['audit_log_operation']=($audit_log[$i]['old_info'] == '')?$vis_language['MSGTICKETLEVELCHANGED'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info']:$vis_language['MSGTICKETLEVELCHANGED'].' from '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
								case '46':
									$audit_log[$i]['audit_log_operation']=($audit_log[$i]['old_info'] == '')?$vis_language['MSGTICKETCATEGORYCHANGED'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info']:$vis_language['MSGTICKETCATEGORYCHANGED'].' from '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
								case '47':
									$audit_log[$i]['audit_log_operation']=($audit_log[$i]['old_info'] == '')?$vis_language['MSGTICKETSUBCATEGORYCHANGED'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info']:$vis_language['MSGTICKETSUBCATEGORYCHANGED'].' from '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
								case '48':
									$audit_log[$i]['audit_log_operation']=($audit_log[$i]['old_info'] == '')?$vis_language['MSGTICKETITEMCHANGED'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info']:$vis_language['MSGTICKETITEMCHANGED'].' from '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
								case '49':
									$audit_log[$i]['audit_log_operation']=($audit_log[$i]['old_info'] == '')?$vis_language['MSGITILLOCATIONCHANGED'].' '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info']:$vis_language['MSGITILLOCATIONCHANGED'].' from '. $audit_log[$i]['old_info']. ' to '. $audit_log[$i]['new_info'];
									break;
								case '50':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTSLAPAUSED'];
									break;
								case '51':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTSLARESUMED'];
									break;
								case '52':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTREADTICKETFORSTAFF'];
									break;
									case '53':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTSENDTICKETAPPROVAL'].' to '.$audit_log[$i]['old_info'];
									break;
								case '54':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTCHANGETICKETAPPROVALSTATUS'].' by '.$audit_log[$i]['old_info'];
									break;
								case '55':
									$audit_log[$i]['audit_log_operation']=$vis_language['TXTSENDTICKETAPPROVALREMINDER'].' to '.$audit_log[$i]['old_info'];
									break;
							    case '56':
									$audit_log[$i]['audit_log_operation']=$vis_language['MSGCUSTOMEFIELDDATAMODIFIED'].' by '.$audit_log[$i]['old_info'];
									break;
							}
					}
                    $database->database_disconnect();
                    if(VIS_LOCATION_AREA==0) {
                        echo get_xml($audit_log, 'audit_log');
                        return true;
                    }
                    else {
                        include_once(VIS_PATH_TEMPLATE.'audit_log.php');
                        return true;
                    }
                }
                else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
                    return false;
                }
            break;
            case 'history':
                if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id'])) {
                    $page=0;
                    $sort_by='modify_date desc';
                    $limit='';
                    $database=new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $ticket_object=new class_ticket($database);
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
                    $client_object=new class_client($database);
                    $client='';
                    if(!isset($operation['vis_parent_id']) || $operation['vis_parent_id']==0){
                        $client_details=$client_object->get_client_list('parent_id='.$operation['vis_client_id'], '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                        if($client_details!=-1) for($i=0;$i<count($client_details);$i++) if($client_details[$i]['client_id']!=VIS_CLIENT_ID) $client.=$client_details[$i]['client_id'].',';
                    }
                    if($client!='') $filter=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$operation['vis_client_id'].')';
                    else $filter=VIS_TABLE_PREFIX.'ticket.client_id='.$operation['vis_client_id'];
                    $filter.=' and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam=0 and draft_id=0';
                    $staff=new class_staff($database);
					list($view_info, $view_details)=$staff->get_ticket_view(VIS_STAFF_ID, VIS_LOCATION_AREA);
                    $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;     
					$limit=($page*$view_info['page_count']).','.$view_info['page_count'];	
                    list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, $limit, $page, $sort_by, VIS_STAFF_ID, VIS_LOCATION_AREA);
                    if(!$ticket_details || !$view_details) {
                        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
                        return false;
                    }
                    if(VIS_LOCATION_AREA==0) {
                        echo get_xml($ticket_details, 'ticket');
                        return true;
                    }
                    else {
                        $view_info['page_count']=($ticket_info['total']==0)?0:ceil($ticket_info['total']/$view_info['page_count']);
                        $ticket_info['ticket_count']=(!$ticket_details || $ticket_details==-1)?0:count($ticket_details);
                        if($operation['vis_ticket']==1)
                        $ticket_info['page']=$page;
                        else
                        $ticket_info['page']=$page*$view_info['page_count'];
                        $view_info['view_count']=count($view_details);
                        if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) $ticket_id=$operation['vis_ticket_id'];
                        else $ticket_id=0;
                        foreach($view_details as $v){
							if($ticket_details!=-1){			
								for($i=0;$i<count($ticket_details);$i++){
									switch($v['tab_name']){
										case 'link': 	
											$link_data=array('vis_ticket_id'=>$ticket_details[$i]['ticket_id'], 'case'=>1);	
											$link = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
											$ticket_details[$i]['link_present']=($link == -1)?0:1;
											break;
										case 'label':	
											$label_details[$i] = $ticket_object->get_ticket_labels($ticket_details[$i]['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
											break;
										default: // this case will execute at last
											$ticket_lock[$i] = $ticket_object->get_ticket_lock($ticket_details[$i]['ticket_id'], 'staff_id!='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
									}
								}
							}
						}
                        include_once(VIS_PATH_TEMPLATE.'ticket_list.php');
                    }
                    $database->database_disconnect();
                    return true;
                }
                else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCLIENDIDMISS'].'"); </script>';
                    return false;
                }
            break;
            case 'notes':
				if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                    $database=new class_database();
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $ticket_object=new class_ticket($database);
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$sett_obj=new class_setting($database);
                    $module_setting=$sett_obj->get_module_setting('title="vis_show_note" and domain_id='.$operation['vis_domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA); 
					$note_details=(VIS_NOTE_ACCESS==0)?-1:$ticket_object->get_note($operation['vis_ticket_id'], $operation['vis_client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
					include(VIS_PATH_TEMPLATE."ticket_note_details.php");
					return true;
				}
                else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
                    return false;
                }
            break;
            case 'link':
				if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                    $database=new class_database();
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $ticket_object=new class_ticket($database);
                    $link_data=array('vis_ticket_id'=>$operation['vis_ticket_id'], 'case'=>1);
                    $link_arr = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
					
                    if($link_arr!=-1){
                        foreach($link_arr as $link){ 
                            $ticket_id_arr=explode(",", $link['ticket_ids']);
                            if(!empty($ticket_id_arr)){
								if(in_array($operation['vis_ticket_id'], $ticket_id_arr)){
										$ticket_id = $link['parent_ticket_id'];
										$del_type ='child';
										$link_data=array('vis_ticket_id'=>$ticket_id, 'case'=>2, 'filter'=>'link_id='.$link['link_id']);
										$temp = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
										$temp[0]['del_type']=$del_type;
										$link_details[]=$temp[0];
								}else{		
									foreach($ticket_id_arr as $ticket_id){ 
										$del_type ='parent';
										$link_data=array('vis_ticket_id'=>$ticket_id, 'case'=>2, 'filter'=>'link_id='.$link['link_id']);
										$temp = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
										$temp[0]['del_type']=$del_type;
										$link_details[]=$temp[0];
									}    
								}
                            }
                        }
                    }
					include(VIS_PATH_TEMPLATE."ticket_link_list.php");
					return true;
				}
                else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
                    return false;
                }
            break;
             case 'attachments':
                if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                    $database=new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
					$obj_ticket=new class_ticket($database);
					$post_details=$obj_ticket->get_ticket_post($operation['vis_ticket_id'], 0, $userid, VIS_LOCATION_AREA);
					$k=0;
       				for($i=0;$i<count($post_details);$i++)
       				{
						
						if($post_details[$i]['attachment']!=-1)
						{
								for($j=0;$j<count($post_details[$i]['attachment']);$j++)
								{
									$ticket_attachment_info[$k]=$post_details[$i]['attachment'][$j];
									$k++;
								}
						}
					}
					include(VIS_PATH_TEMPLATE."ticket_attach_list.php");
					return true;
				}
				else {
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
                    return false;
                }
            break;
        }
        if(VIS_LOCATION_AREA==2) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVOPT'].' '.$operation['vis_action'].'"); </script>';
        else echo 'error';
        return false;
    }

    function new_ticket($operation) { 
		global $vis_language;	
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);
		$check_redmine_status	=	$setting_object->get_redmine('check_status'); 
		$selfhelp=$setting_object->get_settings(' module_id=4 and title="vis_suggetion" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(($selfhelp[0]['content']!=0 && $selfhelp[0]['content']!=1) || $selfhelp==-1) $selfhelp=1;
        ##vtiger				
		$dom = explode(':',$operation['department_id']);			
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND domain_id='.$dom[0]);		
		###vtiger
		if($check_redmine_status!=-1){
			$projectAll	=	$setting_object->get_redmine('projectAll'); 
			//$userAll	=	$setting_object->get_redmine('userAll');
			//$trackerAll	=	$setting_object->get_redmine('trackerAll');		
			//$issue_statusAll	=	$setting_object->get_redmine('issue_statusAll');
			//$issuePriorityAll	=	$setting_object->get_redmine('issuePriorityAll');		
		}
        if(VIS_LOCATION_AREA==2 && !isset($operation['department_id'])) {
            if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
                list($info, $draft)=$ticket->get_ticket('ticket_id='.$operation['vis_ticket_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            }
            elseif(isset($operation['vis_action']) && $operation['vis_action']!='') {
                $spliter=(strstr($operation['vis_action'], '/'))?'/':',';
                $action=explode($spliter, $operation['vis_action']);
                list($info, $draft)=$ticket->get_ticket('ticket_id='.$action[4], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
                $operation['ticket_id']=$action[4];
                if($action[3]==$vis_language['TXTOPENNEWTICKETS']) $operation['vis_draft']=1;
            }
            $draft_info='';
            if($draft!=-1) {
                $operation['department_id']=$draft[0]['domain_id'].':'.$draft[0]['department_id'];
                $subject=$draft[0]['subject'];
                $client['email']=$draft[0]['email'];
                $operation['vis_email_id']=$draft[0]['recipients'];
				$staff_id =($draft[0]['is_deleted'] ==2)?$draft[0]['draft_id'] : VIS_STAFF_ID;
                $post_details=$ticket->get_ticket_draftpost($draft[0]['ticket_id'], 0, $staff_id, VIS_LOCATION_AREA);
                $content=$post_details['draft_data'];
                $draft_info='<input type="hidden" name="vis_draft_id" value="'.$draft[0]['ticket_id'].':'.$post_details['draft_id'].'" />';               	
					if($draft[0]['is_deleted'] ==2){ if(VIS_SCHEDULE_TICKET_MANAGE_ACCESS == 0 && VIS_SCHEDULE_TICKET_VIEW_ACCESS == 0 ){
		   					 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGACCSSDND'].'"); </script>';
						return false;
					}
				}
            }
        }
		//Live chat Inc get message data from API Start
        if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==8){
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
			$filter='integration_type=19 AND domain_id='.$operation['vis_domain_id'];
			list($livechat_info, $livechat_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$livechat_details=$livechat_details[0];
			list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			try {
				include(VIS_PATH_PLUGINS.'livechatinc/lib/LiveChat_API.php');
				$API = new LiveChat_API($livechat_details['api_key'],$livechat_details['admin_user']);
				$chat_object = $API->chats->getSingleChat($operation['vis_chat_id']);
			}
			catch (Exception $e) {
				die($e->getCode().' '.$e->getMessage());
			}
		}
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==9){
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
            $staff_object=new class_staff($database);
			$filter='integration_type=20 AND domain_id='.$operation['vis_domain_id'];
			list($livechat_info, $livechat_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$livechat_details=$livechat_details[0];
			list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$dom = (!isset($operation['vis_domain']))?VIS_DOMAIN:$operation['vis_domain'];
		    $temp_filter='remoteapp_type=20 and (domain_id =0)';
		    $remotescreen_details=$staff_object->get_remotescreen_setting($temp_filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		    if($remotescreen_details==-1){
			$temp_filter='remoteapp_type=20 and (domain_id ='.$dom.')';
			$remotescreen_details = $staff_object->get_remotescreen_setting($temp_filter, VIS_STAFF_ID,LOCATION_AREA);
		}
		//print_r($remotescreen_details);
		$user_details = $remotescreen_details[0];
			$livezillaURL = $livechat_details['billing_url'];
			$apiURL = $livezillaURL . "api/v2/api.php";
			//$postd["p_user"]=$livechat_details['admin_user'];
			//$postd["p_pass"]=$livechat_details['api_key'];
			$postd["p_user"]=$user_details['user_name'];
			$postd["p_pass"]=$user_details['user_password'];
			$postd["p_chatid"]=''.$operation['vis_chat_id'].'';
			// function parameter
			$postd["p_chats_list"]=1;
			$postd["p_json_pretty"]=1;
			// filter parameters to include yesterday's tickets (100 maximum)
			$postd["p_output"]="Plaintext";
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,$apiURL);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($postd));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			//print_r(http_build_query($postd));
			$server_output = curl_exec($ch);
			if($server_output === false)
			exit(curl_error($ch));
			curl_close($ch);
			$response = json_decode($server_output);
			$livezilla_chat_object = $response->Chats[0]->Chat;
		}
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==10){
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
			$filter='integration_type=22 AND domain_id='.$operation['vis_domain_id'];
			list($livechat_info, $livechat_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$userlike_details=$livechat_details[0];
			list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "http://www.userlike.com/api/external/message/transcript/".$operation['vis_chat_id']."");
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json',
				'Authorization:'.$userlike_details['api_key'].'',
				)
			);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); 
			$result = curl_exec($ch);
			
			if($result === false)
					exit(curl_error($ch));
			$userlike_chat =  json_decode($result);
		}
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==11){
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
			$filter='integration_type=21 AND domain_id='.$operation['vis_domain_id'];
			list($livechat_info, $livechat_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$comm100_details=$livechat_details[0];
			list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$ch = curl_init(); 
			curl_setopt($ch, CURLOPT_URL, "https://hosted.comm100.com/livechatapi/chats/".$operation['vis_chat_id']."");
			curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			curl_setopt($ch, CURLOPT_USERPWD, "".$comm100_details['admin_user'].":".$comm100_details['api_key']."");
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);															   
			$result = curl_exec($ch);
			if($result === false)
					exit(curl_error($ch));
			$comm100_data =  json_decode($result);
		}
		
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==12){
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'remoteaccess.php');
			$remoteaccess_object=new class_remoteaccess($database);
			
			$filter='integration_type=23 AND domain_id='.$operation['vis_domain_id'];
			$access_details = $remoteaccess_object->get_access_token($operation['vis_domain_id'], '23');
			
			if($access_details->access_token){
				$goto_meetings = $remoteaccess_object->get_meeting_details($access_details->access_token, $operation['vis_chat_id'], $operation['vis_domain_id']);
			}
		}
		
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==13){
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'remoteaccess.php');
			$remoteaccess_object=new class_remoteaccess($database);
			
			$filter='integration_type=24 AND domain_id='.$operation['vis_domain_id'];
			$access_details = $remoteaccess_object->get_access_token($operation['vis_domain_id'], '24');
			
			if($access_details->access_token){
				$goto_assist = $remoteaccess_object->get_assist_session_details($access_details->access_token, $operation['vis_chat_id'], $operation['vis_domain_id']);
			}
		}
		
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==15){ //for webex ticket 
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'remoteaccess.php');
			$remoteaccess_object=new class_remoteaccess($database);
			$webex_meeting_details = $remoteaccess_object->webex_meeting_details($operation['vis_domain_id'], $operation['vis_chat_id']);
		}
		
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==16){ //for twilio call ticket 
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'remoteaccess.php');
			$remoteaccess_object=new class_remoteaccess($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'voip.php');
			$voip_object=new class_voip($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
		
			list($vis_all_domain, $twilio_details)=$object->integation_app_availability('27', $operation['vis_domain_id']);
			if($twilio_details==-1) {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
				return false;
			}else{
				 try {
					if($operation['vis_twilio_msg']){
						$twilio_message_details = $voip_object->get_twilio_msg_details($twilio_details[0]['host_name'], $twilio_details[0]['user_name'], $twilio_details[0]['db_name'], $operation['vis_chat_id']);
					}else{
						$twilio_call_details = $voip_object->get_twilio_call_details($twilio_details[0]['host_name'], $twilio_details[0]['user_name'], $twilio_details[0]['db_name'], $operation['vis_chat_id']);
						$twilio_call_recording = $voip_object->get_recording($twilio_details[0]['host_name'], $twilio_details[0]['user_name'], $twilio_details[0]['db_name'], $operation['vis_chat_id']);
					}
					
				}catch (Exception $e) {
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
					return false;
				}
			}
		}
		if(isset($operation['vis_chat_type'])  && $operation['channel_id']==17){ // for clickdesk chat
                        $database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
			$filter='integration_type=30 AND domain_id='.$operation['vis_domain_id'];
			list($clickdesk_info, $clickdesk_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$clickdesk_details=$clickdesk_details[0];
			list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
                        $url = "https://my.clickdesk.com/rest/dev/api/getchats/".$operation['vis_email_id'];
                        ob_start();

                        $curl_request = curl_init();          
                        curl_setopt($curl_request, CURLOPT_URL, $url);
                        curl_setopt($curl_request, CURLOPT_POST, 0);
                        curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

                        curl_setopt($curl_request, CURLOPT_HTTPHEADER, array("Accept: application/json"));              
                        curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);

                        curl_setopt($curl_request, CURLOPT_USERPWD, $clickdesk_details['user_name'].":".$clickdesk_details['api_key']);
                        $clickdesk_chat = curl_exec($curl_request);               

                        if($clickdesk_chat === false)
                        exit(curl_error($ch));
                        curl_close($ch);
                        $response = json_decode($clickdesk_chat, true);  
                        $clickdesk_chat_details = $response[$operation['vis_position']];
                }
				if(isset($operation['vis_chat_id']) && isset($operation['vis_chat_type'])  && $operation['channel_id']==18){ // for zopim chat
                        $database=new class_database();
						include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
						$object=new class_setting($database);
						$filter='integration_type=32 AND domain_id='.$operation['vis_domain_id'];
						list($zopim_info, $zopim_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						$zopim_details=$zopim_details[0];
						list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
                        $url = "https://www.zopim.com/api/v2/chats/".$operation['vis_chat_id'];
                        $curl_request = curl_init();               
                        curl_setopt($curl_request, CURLOPT_URL, $url);
                        curl_setopt($curl_request, CURLOPT_POST, 0);
                        curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);               
                        curl_setopt($curl_request, CURLOPT_HTTPHEADER, array("Accept: application/json"));              
                        curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);

                        curl_setopt($curl_request, CURLOPT_USERPWD, $zopim_details['user_name'].":".$zopim_details['api_key']);
                        $server_output = curl_exec($curl_request);
                        curl_close($curl_request); 

                        if($server_output === false)
                            exit(curl_error($curl_request));
                        $zopim_chat_data =  json_decode($server_output);
                }
          if(isset($operation['vis_chat_type']) && $operation['vis_chat_type']=='googlecalender'  && $operation['channel_id']==20){ // for google calender
                $database=new class_database();
				include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'staff.php');
				$staff_object=new staff($database);
				$gcal_details = $staff_object->get_gcal_details($operation);
                }
				if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==19){ //for exotel call ticket 
					$database=new class_database();					
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'voip.php');
					$voip_object=new class_voip($database);
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$object=new class_setting($database);
					include_once(VIS_PATH_PLUGINS.'exotel/class_exotel.php'); ##exotel integration	
					$obj_exotel	=	new class_exotel();		
					$exotel_filter='integration_type=38 AND is_enabled=1 AND (domain_id=0 || domain_id='.VIS_DOMAIN.') ';		
					list($exo_count, $exotel_details)=$object->get_integration_setting($exotel_filter, VIS_STAFF_ID, VIS_LOCATION_AREA,' ORDER bY domain_id DESC');		
					$exotel_details=$exotel_details[0];				
					
					if($exotel_details==-1) {
						echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
						return false;
					}else{
						$exo_data = array("exotel_sid"=>$exotel_details['host_name'],
						  "exotel_token"=>$exotel_details['user_name'],
						 );
						$call_details = $obj_exotel->get_call_details($operation['vis_chat_id'],$exo_data); 
						if(isset($call_details['RestException'])){ $call_details = $obj_exotel->get_sms_details($operation['vis_chat_id'],$exo_data); }						
					}
				}
				
				
				
				
				//crisp message get
				if(isset($operation['vis_chat_type']) && $operation['vis_chat_type']=='crisp'  && $operation['channel_id']==21){
					  
					$database=new class_database();
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$object=new class_setting($database);
					$filter=' integration_type=46';
					$crisp_detail=$object->intergration_crisp($data, $userid, $user,$filter);  
					$crisp_detail=$crisp_detail[0];
					$vis_domain=$crisp_detail['domain_id'];
				list($dpinf, $department)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
				//echo'<pre>';
					$curl = curl_init();  
					curl_setopt($curl, CURLOPT_URL, 'https://api.crisp.im/v1/website/'.$operation['vis_session_id'].'/conversation/'.$operation['vis_website_id'].'');
					curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json','Authorization: Basic '. base64_encode($crisp_detail['user_name'].':'.$crisp_detail['admin_password'] )));
					curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
					$allchat = curl_exec($curl);
					$allchat=json_decode($allchat,true); 
					$curl = curl_init();
					
				
				}
				
				if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==22){ //for aircall call ticket 
					$database=new class_database();					
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'voip.php');
					$voip_object=new class_voip($database);
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$object=new class_setting($database);
					include_once(VIS_PATH_PLUGINS.'aircall/class_aircall.php'); ##aircall integration	
					$obj_aircall	=	new class_aircall();
					$dept_arr = explode(':',$operation['department_id']);

					$aircall_filter='integration_type=50 AND is_enabled=1 AND  domain_id='.$operation['vis_aircall_domain_id'];		
					list($aircall_count, $aircall_details)=$object->get_integration_setting($aircall_filter, VIS_STAFF_ID, VIS_LOCATION_AREA,' ORDER bY domain_id DESC');
				
					$aircall_details=$aircall_details[0];				
					
					if($aircall_details==-1) {
						echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
						return false;
					}else{						
							$apiId = $aircall_details['host_name'];
							$apiToken = $aircall_details['user_name'];
							
							$aircall_call_details = $obj_aircall->get_aircall($apiId,$apiToken,'/calls/'.$operation['vis_chat_id']);
							//echo '<pre>';print_r($call_details);echo '</pre>';	
					}
				}
				if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==23){ //for Asterisk call ticket 
					$database=new class_database();					
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'voip.php');
					$voip_object=new class_voip($database);
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$object=new class_setting($database);
					//include_once(VIS_PATH_PLUGINS.'aircall/class_aircall.php'); ##Asterisk integration	
					//$obj_aircall	=	new class_aircall();
					include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'voip.php');	
					$object_mod_voip = new voip();
					$dept_arr = explode(':',$operation['department_id']);

					$asterisk_filter='integration_type=51 AND is_enabled=1 AND  domain_id='.$operation['vis_asterisk_domain_id'];		
					list($asterisk_count, $asterisk_details)=$object->get_integration_setting($asterisk_filter, VIS_STAFF_ID, VIS_LOCATION_AREA,' ORDER bY domain_id DESC');
					$asterisk_details=$asterisk_details[0];				
					
					if($asterisk_details==-1) {
						echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
						return false;
					}else{						
							$db_host_name	= $asterisk_details['host_name'];
							$db_user_name	= $asterisk_details['user_name'];
							$db_password	= $asterisk_details['db_password'];
							$db_name		= $asterisk_details['db_name'];
							$rec_url_path	= $asterisk_details['rec_path'];
							$con = $object_mod_voip->dbconnect_asterisk($db_host_name,$db_user_name,$db_password,$db_name);	
										
							$sql="SELECT * FROM `cdr` WHERE uniqueid='".$operation['vis_chat_id']."'";
							$rec_arr = array();
							
							$result=mysqli_query($con,$sql);		
							$asterisk_count = mysqli_num_rows($result); 		
							if ($result)
							{
								while ($row=mysqli_fetch_assoc($result))
								{
									$rec_arr[] = $row;
								}
							}		
							$asterisk_call_details =  $rec_arr;		
							//echo '<pre>'; print_r($asterisk_call_details); die; echo '</pre>';
						}
				}
				
				
				
		if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==14 && $operation['vis_chat_type']=='teamviewer'){		
			$database=new class_database();
			include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'remoteaccess.php');
			$remoteaccess_object=new remoteaccess($database);
			$filter='integration_type=25 AND domain_id='.$operation['vis_domain_id'];
			$api_token = $remoteaccess_object->get_teamviewer_api_token($operation['vis_domain_id']);
			$teamviewer_meetings = $remoteaccess_object->get_teamviewer_meeting_details($api_token,$operation['vis_chat_id'],$operation['vis_domain_id']);	
		}
		else if(isset($operation['vis_chat_id']) && $operation['vis_chat_id']!='' && $operation['channel_id']==14 && $operation['vis_chat_type']=='teamviewersession'){
			$database=new class_database();
			echo VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX;
			echo $operation['vis_session'];
			include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'remoteaccess.php');
			$remoteaccess_object=new remoteaccess($database);
			$filter='integration_type=25 AND domain_id='.$operation['vis_domain_id'];
			$api_token = $remoteaccess_object->get_teamviewer_api_token($operation['vis_domain_id']);
			$teamviewer_sessions = $remoteaccess_object->get_teamviewer_session_details($api_token,$operation['vis_chat_id'],$operation['vis_domain_id']);	
		}
		
		
		//Live chat Inc get message data from API End
	    list($operation['domain_id'], $operation['department_id'])=explode(':', $operation['department_id']);
        $status=$ticket->get_status_list('is_enabled=1 and (department_access=0 or find_in_set('.$operation['department_id'].', department_access))', VIS_STAFF_ID, VIS_LOCATION_AREA);
 		$module_setting=$setting_object->get_module_setting('domain_id='.$operation['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$filter = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['department_id'].', department_access))';
		if(!isset($module_setting['vis_show_priority']) || $module_setting['vis_show_priority']==1 || $module_setting['vis_show_priority']==2){
			$module_setting['vis_priority']='';
			$priorities=$ticket->get_priorities_list(VIS_STAFF_ID, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['department_id'].', department_access))');
		}
		if(!isset($module_setting['vis_show_tickettype']) || $module_setting['vis_show_tickettype']==1 || $module_setting['vis_show_tickettype']==2){
			$module_setting['vis_tickettype']='';
			$ticket_types=$ticket->get_type_list(VIS_STAFF_ID, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['department_id'].', department_access))');
		}
		if(isset($module_setting['vis_show_level']) && ($module_setting['vis_show_level']==1 || $module_setting['vis_show_level']==2)){
			$module_setting['vis_level']='';
			list($ticket_level_count, $ticket_level_details)=$setting_object->get_ticket_level_list( $filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		}
		if(isset($module_setting['vis_show_category']) && ($module_setting['vis_show_category']==1 || $module_setting['vis_show_category']==2)){
			$module_setting['vis_category']='';
			list($ticket_cat_count,$ticket_cat_details)=$setting_object->get_ticket_category_list($filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		}
		if(VIS_ITIL==1){
			if(!isset ($module_setting['vis_show_location']) || $module_setting['vis_show_location']==1 || $module_setting['vis_show_location']==2){
			
				$module_setting['vis_assets_location']='';
			$location_assets=$setting_object->get_locations(" AND (".VIS_TABLE_PREFIX."itil_location.department_access = 0 OR FIND_IN_SET(".$operation['department_id'].", ".VIS_TABLE_PREFIX."itil_location.department_access)>0)",0, -1, '', VIS_STAFF_ID);
			}
		}
		
		
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff_object=new class_staff($database);					
		$staff_list = $staff_object->get_staff('is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA, $operation['department_id']);
		$from_email=$ticket->get_from_email($operation['department_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $location[0] = 2;
        $vis_department_id= $operation['department_id'];
        $domain=$operation['domain_id'];
	    $vis_channel_id= ($draft!=-1 && $draft!='')?$draft[0]['channel_id']:$operation['channel_id'];
        if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id'])) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            list($info, $client)=$client_object->get_client('client_id='.$operation['vis_client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $client=$client[0];
        }
		$ticketid=0;
		if(isset($operation['ticket_id']) && $operation['ticket_id']!='')
			$ticketid=$operation['ticket_id'];
        $custom_field_var=$this->get_custom_fields($location, 0, $operation['department_id'], $ticketid, $database);
		$admin_access=$staff_object->get_staff_access('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($admin_access==-1 || (isset($admin_access[0]['level']) && $admin_access[0]['level']!=1))$filter_macro.=' and staff_id = ' . VIS_STAFF_ID.' or access = "0"';
		$macro_count = $staff_object->get_macros_list('is_enabled=1 and (department = '.$operation['department_id'].' or department = 0) '.$filter_macro, VIS_STAFF_ID, VIS_LOCATION_AREA,'','','',1);
        $signaturedata=$staff_object->get_signature('staff_id='.VIS_STAFF_ID.' and department_id='.$operation['department_id'].' and is_forum=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($signaturedata!=-1) $signature=$signaturedata[0]['content'];
         if (defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR != 1) { 
		  $signature = get_plain_text('<br /><br />'.$signature);
	    }
	    else $signature = '<p><br /></p>'.$signature;
		#get data when edit schedule/draft ticket
		$ticket_schedule_data	=	$ticket->get_ticket_schedule($operation['ticket_id']);
		$ticket_details_arr	=	$ticket->get_ticket_details($operation['ticket_id']);		
		$attachnemt_details_arr	=	$ticket->get_attachment("parent_id=(SELECT `post_id` FROM `".VIS_TABLE_PREFIX."ticket_post`WHERE `ticket_id` = '".$operation['ticket_id']."' ORDER BY `post_id` DESC LIMIT 0,1 )",VIS_STAFF_ID, VIS_LOCATION_AREA,1); 
		$ticket_ass_data_arr	=	$ticket->get_assigned_tickets($operation['ticket_id']);
		if(VIS_ITIL==1 && VIS_MODULE_ACCESS_ITIL==1) $itil_enabled=1;
		if($itil_enabled==1){
				$filter3='parent_id= "'.$operation['ticket_id'].'" and attach_type=0';
		 		$attach_ci_details = $ticket->get_attach_ci_list($filter3,'',VIS_STAFF_ID, VIS_LOCATION_AREA);						
		}
	    list($module_info, $drive_setting1)=$setting_object->get_module('module_id=13', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(($drive_setting1[0]['is_enabled']=='1' && $drive_setting1[0]['is_enabled']!='') || !empty($drive_setting)) $drive_setting=1;
        
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'ticket_new_step_two.php');
        return true;
    }

    function custom_field_details($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        if(isset($operation['vis_readonly']) && $operation['vis_readonly']==1) $readonly=1;
        else $readonly=0;
        $displayedit=1;
        $location=array(0=>1, 1=>2, 2=>11);
        $custom_field_var=$this->edit_custom_fields($location, $operation['vis_ticket_id'], $operation['vis_department_id'], $database,$readonly);
        if($custom_field_var==$vis_language['MSGRECORDMISS']) $displayedit=0;
       
        $database->database_disconnect();
        if($readonly==1  && $custom_field_var!=$vis_language['MSGRECORDMISS'] && $displayedit==1) echo '<header class="col-sm-12"><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><div class="pull-right"><a class="link" onclick="load_edit_customfields();" href="javascript:void(0);">'.$vis_language['TXTEDIT'].'</a></div></header>';
        if($custom_field_var!='') echo '<form class="form-horizontal" name="frm_edit_custom" id="frm_edit_custom" method="post">'.$custom_field_var.'</form>';
        else echo '<section class="wrapper fullFrame" id="no_record_yet"><div class="fullMiddle">'.$vis_language['TXTNOTHINGTODISPLAY'].'</div></section>';
        return true;
    }

    function edit_custom_fields($location, $parent_id, $department_id, $database, $readonly=0, $showsubmit=0,$btn_chk=0) {
        global $vis_language;
        $custom_field_var='';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object = new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object = new class_ticket($database);
        $filter=' (location="'.$location[0].'" or location="'.$location[1].'" or location="'.$location[2].'" ) and (department_access=0 or find_in_set('.$department_id.', department_access)) and is_enabled=1 ';
        $custom_group = $setting_object->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($custom_group != -1)
        {
            for($i=0; $i<count($custom_group); $i++)
            {
                $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$i]['customgroup_id'].' and '.VIS_TABLE_PREFIX.'customfield.is_enabled=1 and '.VIS_TABLE_PREFIX.'customfield.ci_type=0';
                list($custom_field_info, $custom_fields_details)=$setting_object->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                
                if($custom_fields_details != -1)
                {
                    $cc_count=0;
                    if($location[0] == 3  && VIS_LOCATION_AREA == 2) $custom_field_var .='<form name="frm_edit_custom" id="frm_edit_custom" class="form-horizontal" method="post" >';
                    else $custom_field_var .=(VIS_LOCATION_AREA == 1 && $readonly==1 && $btn_chk==0)?'':'<form name="frm_edit_custom" id="frm_edit_custom" method="post" >';
                    
                    if($location[0] == 3  && VIS_LOCATION_AREA == 2)
                    {
                        $custom_field_var .= '<div class="col-md-12"><div class="form-group"><label class="col-sm-12">'.$custom_group[$i]['customgroup_name'].'</label></div>';
                    }
                    else
                    {  $bb = ($i<(count($custom_group)-1))?'b-b':'';
						if(VIS_LOCATION_AREA == 1) $custom_field_var .= '<div class="col-md-12 
'.$bb.' b-1x m-b"><div class="wrapper"><div class="form-group"><label class="col-sm-12">'.$custom_group[$i]['customgroup_name'].'</label></div>';
                        else $custom_field_var .= '<div class="col-md-12 
'.$bb.' b-1x m-b"><div class="form-group"><label class="col-sm-12 m-t">'.$custom_group[$i]['customgroup_name'].'</label></div>';
                    }
                    for($j=0; $j<count($custom_fields_details); $j++)
                    {  
                        $val='';
                        if($custom_fields_details[$j]['field_type']<4 || $custom_fields_details[$j]['field_type']==8 || $custom_fields_details[$j]['field_type']==10)
                        {
                            $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                            if($custom_data != -1)  $val = $custom_data['content'];
                            else $val = $custom_fields_details[$j]['default_value'];
                            $req = ($custom_fields_details[$j]['is_required']==1)?' *':'';
                            if($custom_fields_details[$j]['field_type']==1){
                                  if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                  {   
                                      $custom_field_var.= $feedback = '<div class="form-group"><label class="col-sm-2 control-label">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8"><label class="control-label">'.$val.'</label></div></div>';
                                  }
                                  else
                                  { 
                                      if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {      
                                          $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.$val.'</label>':'<input type="text" id="field'.$custom_fields_details[$j]['customfield_id'].'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'">').'</div></div>';
                                      }
                                                                      
                                      else
                                      {
										  $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.$val.'</label>':'<input type="text" id="field'.$custom_fields_details[$j]['customfield_id'].'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'" readonly>').'</div></div>';
                                      }
                                  }
                            }
                            if($custom_fields_details[$j]['field_type']==2)
                            {
                                 if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                 {
                                    $custom_field_var.= $feedback = '<div class="form-group"><label class="col-sm-2 control-label">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8"><label class="control-label">'.$val.'</label></div></div>';
                                 }
                                 else
                                 {
                                      if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {    
										  $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.$val.'</label>':'<input type="'.(VIS_LOCATION_AREA==2?'text':'password').'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'"  >').'</div></div>'; 
                                      }
                                      else
                                      {
										 $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].'<br/></label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.$val.'</label>':'<input type="'.(VIS_LOCATION_AREA==2?'text':'password').'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'" readonly>').'</div></div>'; 
                                      }
                                 }
                            }
                            if( $custom_fields_details[$j]['field_type']==3){
                                if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                {
                                    $custom_field_var.= $feedback = '<div class="form-group"><label class="col-sm-2 control-label">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8"><label class="control-label">'.$val.'</label></div></div>';
                                }
                                else
                                {
                                     if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {     
										  $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.$val.'</label>':'<textarea id="field'.$custom_fields_details[$j]['customfield_id'].'"  name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" >'.$val.'</textarea>').'</div></div>'; 
                                
                                      }
                                      else
                                      {
										  $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.$val.'</label>':'<textarea id="field'.$custom_fields_details[$j]['customfield_id'].'"  name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" readonly >'.$val.'</textarea>').'</div></div>'; 
                                      }
                                }
                            }
                            if($custom_fields_details[$j]['field_type']==8){
							
						 	if(VIS_LOCATION_AREA == 2){ echo '<script>$(".start").datetimepicker(); </script>';}
                                    if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                    { 
                                         $custom_field_var.= $feedback = '<div class="form-group"><label class="col-sm-2 control-label">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8"><label control-label">'.format_datetime(strtotime($val)).'</label></div></div>';
                                    }
                                    else
                                    {
                                        if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                        { 
                                            $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.format_datetime(strtotime($val)).'</label>':'<span class="input-group-addon no-padder no-borders start"><input type="text" id="field'.$custom_fields_details[$j]['customfield_id'].'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'"></span>').'</div></div>';
                                        }else{
                                            $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label">'.$custom_fields_details[$j]['field_name'].'</label><div class="col-sm-8">'.(($readonly==1)?'<label class="control-label">'.format_datetime(strtotime($val)).'</label>':'<span class="input-group-addon no-padder no-borders start"><input type="text" id="field'.$custom_fields_details[$j]['customfield_id'].'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'" disabled></span>').'</div></div>';
                                        }
                                    }
                                $cc_count++;
                            }
     if($custom_fields_details[$j]['field_type']==10){
  $custom_field_var.='<div class="form-group"><div class="col-sm-12">'.stripslashes($custom_fields_details[$j]['field_description']).'</div></div>';                       
						}
					   }
                        else
                        {
                           
                            $filter='field_group='.$custom_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA,'edit_page');
							
							list($sub_customfield_info_lang ,$sub_customfields_details_lang)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
							 
                        
                                if($sub_customfields_details != -1)
                                {
                                    if(($location[0] == 3  && VIS_LOCATION_AREA == 2 ))          
                                    {
                                        if($custom_fields_details[$j]['field_type']==4)
                                        {   
                                            $custom_field_check_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                            for($k=0;$k< count($sub_customfields_details);$k++)
                                            {
                                                  $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                                  if($custom_data != -1)
                                                  {   
                                                         $vis_check[$k] = 1; 
                                                  }
                                                  if($custom_data['content'] === $sub_customfields_details[$k]['default_value'])$custom_field_check_var.='<span class="vis_label_in">'.$sub_customfields_details_lang[$k]['default_value'].'</span>';
                                            }
                                            $custom_field_check_var .= '</div></div>';
                                            if(count($vis_check) > 0) $custom_field_var  .= $feedback = $custom_field_check_var ;          
                                            
                                        }
                                        if($custom_fields_details[$j]['field_type']==5)
                                        {
                                            $custom_field_radio_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';

                                            
                                            for($k=0;$k<count($sub_customfields_details);$k++)
                                            {
                                              $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                                if($custom_data != -1)
                                                {
                                                    $radio[$k] = 1;
                                                }
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value'])
													$custom_field_radio_var.='<span class="vis_label_in">'.$sub_customfields_details_lang[$k]['default_value'].'</span>';
                                                   
                                                $cc_count++;
                                            }
                                           
                                             $custom_field_radio_var .= '</div></div>';  
                                             if(count($radio) > 0) $custom_field_var  .= $feedback = $custom_field_radio_var ;
                                        }
                                        if($custom_fields_details[$j]['field_type']==6)
                                        {
                                            
                                            $custom_field_select_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                                if($custom_data != -1)
                                                {
                                                    $vis_select[$k] = 1;
                                                }
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value'])$custom_field_select_var.='<span class="vis_label_in">'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</span>';
                                            }
                                            
                                            $custom_field_select_var.='</div></div>';
                                            if(count($vis_select) > 0 ) $custom_field_var  .= $feedback = $custom_field_select_var ;  
                                            $cc_count++;
                                        }
                                        if($custom_fields_details[$j]['field_type']==7)
                                        { 
                                           $custom_field_mulvar.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                                for($k=0;$k<count($sub_customfields_details);$k++) 
                                                {
                                                    $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']); 
                                                    if($custom_data != -1)
                                                    {
                                                         $vis_multiple[$k] = 1;         
                                                    }
                                                    if($custom_data['content'] == $sub_customfields_details[$k]['default_value'])  $custom_field_mulvar.='<span class="vis_label_in">'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</span>';
                                                } 
                                             $custom_field_var.='</div></div>';
                                             if(count($vis_multiple) > 0 ) $custom_field_var  .= $feedback = $custom_field_mulvar ;  
                                             $cc_count++;   
                                        }
                                      
                                    }  
                                    else
                                    {    
                                        $flag = array();   
                                        if($custom_fields_details[$j]['field_type']==4)
                                        {
											$custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                            for($cnt=0;$cnt<count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }
                                            for($k=0;$k< count($sub_customfields_details);$k++)
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);   
                                                if($custom_data['content'] === $sub_customfields_details[$k]['default_value'])
                                                {  
                                                    $sel = 'checked="checked"';
                                                   
                                                }
                                                else $sel='';  
                                                if(count($flag) <= 0 && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'checked="checked"';
                                                if($readonly==1) {
													$custom_field_var.=($sel!='')?'<label class="control-label">'.$sub_customfields_details_lang[$k]['default_value'].'</label>   ':' ';
												}else {
                                                    if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1)) {
                                                        $custom_field_var.='<label class="checkbox-inline i-checks"><input type="checkbox" '.$sel.' name="field'.$sub_customfields_details[$k]['customfield_id'].'" id="field'.$sub_customfields_details[$k]['customfield_id'].'" value="'.addslashes($sub_customfields_details[$k]['default_value']).'">  <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label> ';
                                                    }else{
                                                        $custom_field_var.='<label class="checkbox-inline i-checks"><input type="checkbox" '.$sel.' name="field'.$sub_customfields_details[$k]['customfield_id'].'" id="field'.$sub_customfields_details[$k]['customfield_id'].'" disabled value="'.addslashes($sub_customfields_details[$k]['default_value']).'">  <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label> ';
                                                    }
												}
                                                $cc_count++;
                                            }
                                            $custom_field_var .= '</div></div>';
                                        }
                                        if($custom_fields_details[$j]['field_type']==5)
                                        {
											$custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                            for($k=0;$k<count($sub_customfields_details);$k++)
                                            {
                                              $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value']) 
                                                {
                                                    $flag[$k] = 1;
                                                    $sel = 'checked="checked"';
                                                }
                                                else $sel='';  
                                                if(($sel == '' && ($flag == 0)) && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'checked="checked"';  
                                                if($readonly==1) {
													$custom_field_var.=($sel!='')?'<label class="control-label">'.$sub_customfields_details_lang[$k]['default_value'].'</label>':'';
												}else { 
                                                    if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1)) {
                                                        $custom_field_var.='<div class="radio i-checks m-r-lg pull-left"><label><input type="radio" '.$sel.' name="field'.$custom_fields_details[$j]['customfield_id'].'[]" id="field'.$sub_customfields_details[$k]['customfield_id'].'" value="'.addslashes($sub_customfields_details[$k]['customfield_id'].'-'.$sub_customfields_details[$k]['default_value']).'"> <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label></div>';
                                                        
                                                    }else{
                                                        $custom_field_var.='<div class="radio i-checks m-r-lg pull-left"><label><input type="radio" '.$sel.' name="field'.$custom_fields_details[$j]['customfield_id'].'[]" id="field'.$sub_customfields_details[$k]['customfield_id'].'" disabled value="'.addslashes($sub_customfields_details[$k]['customfield_id'].'-'.$sub_customfields_details[$k]['default_value']).'"> <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label></div>';
                                                    }
												}
                                               $cc_count++;
                                            }
                                            $custom_field_var .= '</div></div>';
                                        }
                                        if($custom_fields_details[$j]['field_type']==6)
                                        {   
											$temp_custom_field_var='';
											$custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
											if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1)) $temp_custom_field_var='<select name="field'.$custom_fields_details[$j]['customfield_id'].'" class="input-sm form-control selectpicker">';
                                            else $temp_custom_field_var='<select disabled name="field'.$custom_fields_details[$j]['customfield_id'].'" class="input-sm form-control selectpicker">';
											$temp='';
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value']) 
                                                {
                                                    $sel = 'selected="selected"';
                                                    $flag = 1;    
                                                }
                                                else $sel='';
                                                if($flag == '' && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'selected="selected"';
                                                if($readonly==1) {
													$temp.=($sel!='')?'<label class="control-label">'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</label>':'';
												}else {             
                                                   $temp_custom_field_var.='<option value="'.addslashes($sub_customfields_details[$k]['default_value']).'" '.$sel.'>'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</option>';
												}
                                            }
                                            if($readonly==1)
                                                $custom_field_var.=$temp.'</div></div>';
                                            else $custom_field_var.=$temp_custom_field_var.'</select></div></div>';
                                            $cc_count++;
                                        }
                                        if($custom_fields_details[$j]['field_type']==7)
                                        {  
                                            if($sub_customfields_details[$k]['is_selected'] == 1 )$selDefault = 'selected="selected"';  
                                            $temp_custom_field_var='';  
                                            $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
											if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  $temp_custom_field_var='<select name="field'.$custom_fields_details[$j]['customfield_id'].'[]" multiple="multiple" size="5" class="input-sm form-control">';
                                            else $temp_custom_field_var='<select disabled name="field'.$custom_fields_details[$j]['customfield_id'].'[]" multiple="multiple" size="5" class="input-sm form-control">';
                                           
                                            for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }
                                            $temp='';
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);   
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value']  ) { $sel  ='selected="selected"'; }
                                                else  $sel='';
                                                    
                                                  if(count($flag) <= 0 && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'selected="selected"';
                                                  if($readonly==1) {
													$temp.=($sel!='')?'<label class="control-label">'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</label>  ':' ';
												  }else {
													$temp_custom_field_var.='<option value="'.addslashes($sub_customfields_details[$k]['customfield_id'].'-'.$sub_customfields_details[$k]['default_value']).'" '.$sel.'>'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</option>';
												}
                                            }
                                            if($readonly==1)
                                                $custom_field_var.=$temp.'</div></div>';
                                            else $custom_field_var.=$temp_custom_field_var.'</select></div></div>';
                                            $cc_count++;
                                        }
                                    }
                                }
                            }
                       }
                        if(VIS_LOCATION_AREA == 1) $custom_field_var.='</div></div>';
                        else $custom_field_var.='</div>';
                  }
            }
        }
        if($custom_field_var!='')
        {
               if(VIS_LOCATION_AREA ==1) {
                    if($readonly!=1) {
						if($btn_chk!=0)
							$custom_field_var.='<input type="hidden" value="ticket" name="vis_module" /><input type="hidden" value="update_customfields" name="vis_operation" /><input type="hidden" value="'.$parent_id.'" name="vis_parent_id" /><input type="hidden" value="'.base64_encode(serialize($location)).'" name="vis_location" /><input type="hidden" value="'.$custom_group[0]['visible_to'].'" name="vis_visible_to" /><input type="hidden" value="'.$department_id.'" name="vis_department" />';
						else
							$custom_field_var.='<div class="col-lg-offset-2 col-lg-8 m-b-lg"><button type="submit" class="btn btn-primary m-r" onclick="return check_customdata();">'.$vis_language['TXTUPDATE'].'</button></div><input type="hidden" value="ticket" name="vis_module" /><input type="hidden" value="update_customfields" name="vis_operation" /><input type="hidden" value="'.$parent_id.'" name="vis_parent_id" /><input type="hidden" value="'.base64_encode(serialize($location)).'" name="vis_location" /><input type="hidden" value="'.$custom_group[0]['visible_to'].'" name="vis_visible_to" /><input type="hidden" value="'.$department_id.'" name="vis_department" /></form>';
					} 
			   }
               if((VIS_LOCATION_AREA==2) && $location[0]!=3){
                    if($readonly!=1 && $showsubmit==0) $custom_field_var.='<div class="col-lg-offset-2 col-lg-8 m-b-lg"><span class="btn btn-primary btn-sm" onclick="$(this).visExecution(\'submit_form\',{\'vis_module\':\'ticket\', \'vis_operation\':\'update_customfields\', \'vis_form\':\'frm_edit_custom\', \'vis_department\':'.$department_id.', \'vis_parent_id\':\''.$parent_id.'\', \'vis_location\':\''.base64_encode(serialize($location)).'\'})">'.$vis_language['TXTUPDATE'].'</span> </div></form>';
                    elseif($showsubmit==1) $custom_field_var.='<input type="hidden" name="vis_department_id" value="'.$department_id.'"/><input type="hidden" name="vis_parent_id" value="'.$parent_id.'"/><input type="hidden" name="vis_location" value="'.base64_encode(serialize($location)).'"/><input type="hidden" value="'.$custom_group[0]['visible_to'].'" name="vis_visible_to" />';
               } 
               if((VIS_LOCATION_AREA==3) && $location[0]!=3)
                    $custom_field_var.='<tr><td colspan="2"><input type="Submit" class="vis_button" value="'.$vis_language['TXTUPDATE'].'" /><input type="hidden" name="vis_module" value="ticket" /><input type="hidden" name="vis_operation" value="update_customfields" /><input type="hidden" name="vis_department" value="'.$department_id.'" /><input type="hidden" name="vis_parent_id" value="'.$parent_id.'"/><input type="hidden" name="vis_location" value="'.base64_encode(serialize($location)).'" /><input type="hidden" value="'.$custom_group[0]['visible_to'].'" name="vis_visible_to" /></td></tr> </table></form>';
               if(VIS_LOCATION_AREA == 2 && $location[0] == 3 )
               {
                     $custom_field_var.='</fieldset>';
               } 
        }
        
        else $custom_field_var='';

        if($location[0] != 3)
        if($custom_field_var=='' && VIS_LOCATION_AREA!=1) $custom_field_var=$vis_language['MSGRECORDMISS']; 
        if( $feedback == "" &&  ($location[0] == 3  && VIS_LOCATION_AREA == 2) ) 
        {
           $custom_field_var= "";    
        }     
        return $custom_field_var;
   
}
    function get_custom_fields($location, $type, $department_id, $parent_id, $database){
        $custom_field_var='';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object = new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object = new class_ticket($database);
        //for($i=0;$i<count($location); )
		$both_view = ($location[0]==1 || $location[0] == 2)? ' OR location=11 ' : '';
        if($location[0] == 4)
        {
			$filter=' location='.$location[0].' and customgroup_id = '.$location[1].' and is_enabled=1 ';
		}
		else
		{
			$filter=' (location='.$location[0].$both_view.') and (department_access=0 or find_in_set('.$department_id.', department_access)) and is_enabled=1 ';
		}
		//if($location[0] == 0){$filter=$filter.' and visible_to = 0';}
	    //if($location[0] == 1){$filter=$filter.' and (visible_to = 1 or visible_to = 0)';}
		//if($location[0] == 2){$filter=$filter.' and (visible_to = 2 or visible_to = 0)';}
		
        $custom_group = $setting_object->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		
	    if($custom_group != -1){
            for($i=0; $i<count($custom_group); $i++){
                $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$i]['customgroup_id'].' and '.VIS_TABLE_PREFIX.'customfield.is_enabled=1 ';;
                list($custom_field_info, $custom_fields_details)=$setting_object->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
			    if($custom_fields_details != -1){
                    $cc_count=0;
                   
                     $custom_field_var .='<div class="form-group"><label class="col-sm-12" for="'.$custom_group[$i]['customgroup_name'].'">'.$custom_group[$i]['customgroup_name'].'</label><input type="hidden" name="vis_visible_to" id="vis_visible_to" value="'.$custom_group[0]['visible_to'].'"><input type="hidden" name="vis_location" value="'.base64_encode(serialize($location)).'" /></div>'; 
                    for($j=0; $j<count($custom_fields_details); $j++){
                         $val='';   
                        if($custom_fields_details[$j]['field_type']<4 || $custom_fields_details[$j]['field_type']==8 || $custom_fields_details[$j]['field_type']==10){
                            $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                            if($custom_data != -1)  $val = $custom_data['content'];
                            else $val = $custom_fields_details[$j]['default_value'];
                            $req = ($custom_fields_details[$j]['is_required']==1)?' *':'';
							if($custom_fields_details[$j]['field_type']==1)
                            {
							   $custom_field_var.='<input type="hidden" value="'.$custom_fields_details[$j]['customfield_id'].'" id="custom_field_id" name="custom_field_id" class="form-control input-sm">';
                                if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><input type="text" value="'.$val.'" id="field'.$custom_fields_details[$j]['customfield_id'].'" name="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm"></div></div>';
                                }
                                else
                                {
                                     $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><input type="text" value="'.$val.'" readonly name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm"></div></div>';
                                }
                           }
                            if($custom_fields_details[$j]['field_type']==2)
                            {
                               if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><input type="password" name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'"></div></div>';
                                } 
                                else
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><input type="password" name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'" readonly ></div></div>';
                                }  
                            }
                            if( $custom_fields_details[$j]['field_type']==3)
                            {
                                if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><textarea name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" >'.$val.'</textarea></div></div>';
                                }
                                else
                                {
                                     $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><textarea name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" readonly>'.$val.'</textarea></div></div>';
                                }  
                            }
                            if($custom_fields_details[$j]['field_type']==8)
                            {
							  if(VIS_LOCATION_AREA == 2){echo '<script>$("#field'.$custom_fields_details[$j]['customfield_id'].'").datetimepicker({showButtonPanel: true, dateFormat: "dd-mm-yyyy h:i"})</script>';}
                               if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                     $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><span class="input-group-addon no-padder no-borders start"><input type="text" name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'"></span></div></div>';
                                }
								else
								{
									 $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$custom_fields_details[$j]['field_description'].'">'.$custom_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><span class="input-group-addon no-padder no-borders"><input type="text" name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm" value="'.$val.'" readonly ></span></div></div>';
								}
                                  
                            }   
if($custom_fields_details[$j]['field_type']==10)
                            {
							       $custom_field_var.='<div class="form-group"><div class="col-sm-12">'.stripslashes($custom_fields_details[$j]['field_description']).'</div></div>';
                                
                           }							
                            $cc_count++;
                        }
                        else{
                             $flag = array();     
                            $filter='field_group='.$custom_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA,'edit_page');
							
							list($sub_customfield_info_lang ,$sub_customfields_details_lang)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
							
                            if($sub_customfields_details != -1){
                                if($custom_fields_details[$j]['field_type']==4){
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                    for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                    {
                                          $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                          if($custom_data != -1)  
                                          {
                                                     $flag[$cnt] =  1;
                                          }
                                    }
                                    for($k=0;$k< count($sub_customfields_details);$k++){
                                       $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);   
                                        if(($custom_data['content'] === $sub_customfields_details[$k]['default_value'])) $sel = 'checked="checked"';
                                        else if(count($flag) <= 0 &&  $sub_customfields_details[$k]['is_selected'] == 1)  $sel = 'checked="checked"';   
                                        else $sel='';
										 if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))                                 		 {
                                        	$custom_field_var.='<label class="checkbox-inline i-checks"><input type="checkbox" '.$sel.' name="field'.$sub_customfields_details[$k]['customfield_id'].'" id="field'.$sub_customfields_details[$k]['customfield_id'].'" value="'.$sub_customfields_details[$k]['default_value'].'" > <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label> ';
										}
										else 
										{
											$custom_field_var.='<label class="checkbox-inline i-checks"><input type="checkbox" '.$sel.' name="field'.$sub_customfields_details[$k]['customfield_id'].'" id="field'.$sub_customfields_details[$k]['customfield_id'].'" value="'.$sub_customfields_details[$k]['default_value'].'" disabled="disabled"> <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label> ';
										}
                                        $cc_count++;
                                    }
                                    $custom_field_var .= '</div></div>';
                                }
                                if($custom_fields_details[$j]['field_type']==5){
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
									
									 for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                    {
                                          $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                          if($custom_data != -1)  
                                          {
                                                     $flag[$cnt] =  1;
                                          }
                                    }
									
									
                                    for($k=0;$k<count($sub_customfields_details);$k++){
                                        $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
										$sel='';									
										 
										
										 if(($custom_data['content'] === $sub_customfields_details[$k]['default_value'])) $sel = 'checked="checked"';
                                        else if(count($flag) <= 0 &&  $sub_customfields_details[$k]['is_selected'] == 1)  $sel = 'checked="checked"';   
                                        else $sel='';
										 if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))                                 		 {
                                          $custom_field_var.='<div class="radio i-checks m-r-lg pull-left"><label><input type="radio" '.$sel.' name="field'.$custom_fields_details[$j]['customfield_id'].'[]" id="field'.$sub_customfields_details[$k]['customfield_id'].'" value="'.addslashes($sub_customfields_details[$k]['customfield_id'].'-'.$sub_customfields_details[$k]['default_value']).'"> <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label></div>';
										 }
										 else
										 {
										 	$custom_field_var.='<div class="radio i-checks m-r-lg pull-left"><label><input type="radio" '.$sel.' name="field'.$custom_fields_details[$j]['customfield_id'].'[]" id="field'.$sub_customfields_details[$k]['customfield_id'].'" value="'.addslashes($sub_customfields_details[$k]['customfield_id'].'-'.$sub_customfields_details[$k]['default_value']).'" disabled="disabled"> <i></i> '.$sub_customfields_details_lang[$k]['default_value'].'</label></div>';
										 }
                                        $cc_count++;
                                    }
                                    $custom_field_var .= '</div></div>';
                                }
                                if($custom_fields_details[$j]['field_type']==6){
								if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))                                 	 {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8"><select name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm selectpicker">';
									 }
									 else
									 {
									 	 $custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8"><select disabled="disabled" name="field'.$custom_fields_details[$j]['customfield_id'].'" id="field'.$custom_fields_details[$j]['customfield_id'].'" class="form-control input-sm selectpicker">';
									 }
                                    for($k=0;$k<count($sub_customfields_details);$k++) {
                                         $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                        if(($custom_data['content']== $sub_customfields_details[$k]['default_value']) || $sub_customfields_details[$k]['is_selected'] == 1) $sel = 'selected="selected"';
                                        else $sel='';										
                                        	$custom_field_var.='<option value="'.addslashes($sub_customfields_details[$k]['default_value']).'" '.$sel.'>'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</option>';
                                    }
                                    
                                    $custom_field_var.='</select></div></div>';
                                    $cc_count++;
                                }
                                if($custom_fields_details[$j]['field_type']==7){
								if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))                                 	 {
                                    	$custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8"><select name="field'.$custom_fields_details[$j]['customfield_id'].'[]" id="field'.$custom_fields_details[$j]['customfield_id'].'" multiple="multiple" size="5" class="form-control input-sm selectpicker">';
									 }
									 else
									 {
									 	$custom_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'" title="'.$custom_fields_details[$j]['field_description'].'">'.addslashes($custom_fields_details[$j]['field_name']).'</label><div class="col-sm-8"><select disabled="disabled" name="field'.$custom_fields_details[$j]['customfield_id'].'[]" id="field'.$custom_fields_details[$j]['customfield_id'].'" multiple="multiple" size="5" class="form-control input-sm selectpicker">';
									 }
                                    for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                    {
                                          $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                          if($custom_data != -1)  
                                          {
                                                     $flag[$cnt] =  1;
                                          }
                                    }
                                    for($k=0;$k<count($sub_customfields_details);$k++) {
                                        $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                        
                                        if(($custom_data['content']== $sub_customfields_details[$k]['default_value'])) {$sel = 'selected="selected"'; }
                                       
                                        else $sel='';  
                                        if(count($flag) == 0 && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'selected="selected"'; 
                                           $custom_field_var.='<option value="'.addslashes($sub_customfields_details[$k]['customfield_id'].'-'.$sub_customfields_details[$k]['default_value']).'" '.$sel.'>'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</option>';
                                    }
                                    $custom_field_var.='</select></div></div>';
                                    $cc_count++;
                                }
                            }
                        }
                    }
                }
                //else $custom_field_var='';
            }
        }
        else $custom_field_var='';
        return $custom_field_var;
    }

    function ticket_feedback($operation) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
		list($info, $modules)=$object->get_module('is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        foreach($modules as $var) $module[$var['module']]=1;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $userid=(defined('VIS_CLIENT_ID'))?VIS_CLIENT_ID:VIS_STAFF_ID;
        if(isset($operation['vis_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			$operation['ticket_id'] = $data[4];
			$operation['department_id'] = $data[6];
		}
		else
		{
			$operation['ticket_id'] = $operation['vis_ticket_id'];
			$operation['department_id'] = $operation['vis_department'];
		}
        if(VIS_LOCATION_AREA==1 && $userid==0){
             if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
             include(VIS_PATH_TEMPLATE.'login.php');
             include(VIS_PATH_TEMPLATE.'footer.php');
             break;
         }
        $type_list=$ticket_object->get_type_list($userid, VIS_LOCATION_AREA, 'is_enabled=1');
        $status_list=$ticket_object->get_status_list('is_enabled=1', $userid, VIS_LOCATION_AREA);
        $priority_list=$ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1');
        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['ticket_id']; //' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
        if(VIS_LOCATION_AREA==1) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            if(VIS_VIEW_TICKET==1 && VIS_VIEW_SELFTICKET==0) {
                $parent=(VIS_CLIENT_PARENT==0 || VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client='';
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) if($client_details[$i]['client_id']!=VIS_CLIENT_ID) $client.=$client_details[$i]['client_id'].',';
                if($client!='') $filter=VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';
                else $filter=VIS_TABLE_PREFIX.'ticket.client_id='.$parent;
            }
            elseif(VIS_VIEW_TICKET==1 && VIS_VIEW_SELFTICKET==1) {
                $client='';
                $parent=(VIS_CLIENT_PARENT==-1 || VIS_CLIENT_PARENT==0)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
                $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($client_details!=-1) for($i=0;$i<count($client_details);$i++) $client.=$client_details[$i]['client_id'].',';
                if($client!='') $filter.=' and '.VIS_TABLE_PREFIX.'ticket.client_id in ('.$client.$parent.')';
                else $filter.=' and '.VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID;
            }
            else $filter.=' and '.VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID;
        }
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', $userid, VIS_LOCATION_AREA);
        $ticket_details=$ticket_details[0];
        $post_details=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, $userid, VIS_LOCATION_AREA);
        $post_count=count($post_details);
        $header_title='Feedback';
        $location=array(0=>3, 1=>3);
        $ticket_feedback =  (isset($data[2]))?$data[2] :'ticket-feedback';        
        $custom_field_var = $this->get_custom_fields($location, 0, $operation['department_id'], $operation['ticket_id'], $database);
		$staffSettings=$object->get_settings('title="vis_head_menu_staffNm" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
        else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'ticket_details.php'); 
        else include(VIS_PATH_TEMPLATE.'ticket_custom.php');
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
    }

    function export_ticket($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket('ticket_id='.$operation['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_details=$ticket_details[0];
        $domain_details=$ticket_object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$ticket_details['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $post_details=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $post_count=count($post_details);
        $note_details=(VIS_NOTE_ACCESS==0)?-1:$ticket_object->get_note($ticket_details['ticket_id'], $ticket_details['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
           
        for($i=0;$i<count($post_details);$i++){
          $comment_details[$i]=(VIS_COMMENT_ACCESS==0)?-1:$ticket_object->get_post_comment($post_details[$i]['post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);	
          $post_details[$i]['content'] = preg_replace('/(<[^>]*) style=("[^"]+"|\'[^\']+\')([^>]*>)/i', '$1$3', $post_details[$i]['content']);
       
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        $user_details=$client_object->get_client(VIS_TABLE_PREFIX.'client.client_id='.$ticket_details['client_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        
        $location=array(0=>1, 1=>2);
        $custom_field_var.=$this->show_custom_fields($location, $ticket_details['ticket_id'], $ticket_details['department_id'], $database);
        /*$location=array(0=>3, 1=>3);
        $custom_field_var.=$this->show_custom_fields($location, $ticket_details['ticket_id'], $ticket_details['department_id'], $database); */
        $html=get_include_contents(VIS_PATH_TEMPLATE.'ticket_export.php', array($ticket_details, $post_details, $post_count,$note_details,$domain_details[0],$comment_details,$user_details[1][0],$custom_field_var));
        if($ticket_details==-1 || $post_details==-1) {
            echo $vis_language['MSGERROPRT'];
            return false;
        }
        else {
            if($operation['vis_type']=='pdf') {
                require_once('../plugins/tcpdf/config/lang/eng.php');
                require_once('../plugins/tcpdf/tcpdf.php');
                $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
                $pdf->SetCreator(PDF_CREATOR);
                $pdf->SetAuthor('Vision helpdesk');
                $pdf->SetTitle($ticket_details['ticket_hash']);
                $pdf->SetSubject($ticket_details['subject']);
                $pdf->SetKeywords('Vision helpdesk, PDF, '.$ticket_details['ticket_hash']);
                $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
                $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
                $pdf->SetPrintHeader(false);
                $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
                $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
                $pdf->setLanguageArray($l);
                $pdf->SetFont('helvetica', '', 9);
                $pdf->AddPage();
                $pdf->writeHTML($html, true, false, true, false, '');
                $pdf->lastPage();
                $pdf->Output($ticket_details['ticket_hash'].'.pdf', 'I');
            }
            else {
                //header('Content-Disposition: attachment; filename="'.$ticket_details['ticket_id'].' - '.$ticket_details['subject'].'.pdf"');
            }
            return true;
        }
    }

    function new_ticket_step_one($operation) { 
	    //print_r($operation);
        global $vis_language;
        if(isset($operation['vis_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			//$operation['departmentid'] = $data[4];
			
			if($data[3] == 'domain') 
				$operation['dom_id'] = $data[4];
			
			if($data[3] == 'department') {
				$operation['departmentid'] = $data[4];
				if(isset($data[5]) && $data[5] == 'domain')
					$operation['dom_id'] = $data[6];
			}
			
			if(VIS_LOCATION_AREA == 1 && IS_LOGIN!=1 )
			{	
				$action=explode("/", $operation['vis_action']);
				if(count($action) > 3 && $action[2]!='get-department' && VIS_IS_WHMCS != 1)
				{
					$operation['message']='<div class="vis_message">#'.$action[3].' - '.$vis_language['MSGSUCCOTKT'].'</div>';
				}
			}
			
			if(VIS_LOCATION_AREA==1 && strstr($operation['vis_action'],'get-department'))
			{
			$is_nofollow=1;
			}
		}
		$domain_id = (VIS_LOCATION_AREA == 1 && VIS_SATELLITE_HELPDESK == 3 && isset($operation['dom_id'])) ? $operation['dom_id'] : VIS_DOMAIN;
        if(VIS_LOCATION_AREA==1 && VIS_VIEW_SELFTICKET==0) {
            $header_title=$vis_language['TXTSUBMITTICKET'];
            include(VIS_PATH_TEMPLATE.'header.php');
            echo '<script> $("#vis_submit_err_div").show(); $("#vis_submit_err_div").html("'.$vis_language['MSGACCSSDND'].'");</script>'; 
            include(VIS_PATH_TEMPLATE.'submit_ticket.php');
            include(VIS_PATH_TEMPLATE.'footer.php');
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'cmdb.php');
        $cmdb_object=new class_cmdb($database);
        $ticket=new class_ticket($database);
        $client_obj=new class_client($database);
        $setting_obj=new class_setting($database);
        $filter=' module_id=3 and title="vis_captcha" and domain_id='.$domain_id;
        $setting_details=$setting_obj->get_settings($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $selfhelp=$setting_obj->get_settings(' module_id=4 and title="vis_suggetion" and domain_id='.$domain_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(($selfhelp[0]['content']!=0 && $selfhelp[0]['content']!=2) || $selfhelp==-1) $selfhelp=1;
        $config_details = $setting_obj->get_configuration_item('',0, -1, '', VIS_STAFF_ID);// Newly added line by Sachin E.
        $attachment=$setting_obj->get_settings(' module_id=2 and title="vis_attachment" and domain_id='.$domain_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $attachment=is_numeric($attachment[0]['content'])?$attachment[0]['content']:100;
        $filter=(VIS_LOCATION_AREA==1)?(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1 and access_type=0 and '.VIS_TABLE_PREFIX.'department.domain_id='.$domain_id):(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1');
        if(VIS_LOCATION_AREA==2 && isset($operation['vis_domain_id']) && $operation['vis_domain_id']!='') $filter.=' and '.VIS_TABLE_PREFIX.'department.domain_id='.$operation['vis_domain_id'];
        if(VIS_LOCATION_AREA==1 || (VIS_LOCATION_AREA==2 && $operation['vis_current_operation'] == 'manage_client_add_ticket')) {
              if((defined('VIS_CLIENT_ID') && VIS_CLIENT_ID>0) ||  $operation['vis_client_id']>0){
                $userid=(VIS_CLIENT_ID>0)?VIS_CLIENT_ID:$operation['vis_client_id'];
                list($client_info, $client)=$client_obj->get_client('client_id='.$userid, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                $client=$client[0];
               //$userid=VIS_CLIENT_ID;
                if(VIS_LOCATION_AREA==1){
					if($client['department_access']!=0 && $client['parent_id']==0)
						$filter.=' and '.VIS_TABLE_PREFIX.'department.department_id in ('.$client['department_access'].') ';
					elseif($client['parent_id']!=0){
						list($parentclient_info, $parentclient)=$client_obj->get_client('client_id='.$client['parent_id'], '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
						if($parentclient[0]['department_access']!=0)
						$filter.=' and '.VIS_TABLE_PREFIX.'department.department_id in ('.$parentclient[0]['department_access'].') ';
					}
				}
            }
            else $userid=0;
        }  
        if(isset($operation['vis_client']) && $operation['vis_client']==1 && $operation['vis_chat_type']!='crisp' )
        $filter.=' and '.VIS_TABLE_PREFIX.'domain.domain_id='.$operation['vis_domain_id'];
		 else
		$filter.="";
	    $departments=$ticket->get_department($filter, VIS_STAFF_ID, VIS_LOCATION_AREA, '');
        if(isset($operation['departmentid'])) { $departmentid = $operation['departmentid']; $department_get= $operation['departmentid'];}
        else $departmentid = $departments[0]['department_id'];
        $domain = (isset($operation['domain_id']) && $operation['domain_id']!='')?$operation['domain_id']:VIS_DOMAIN;
        $module_setting=$setting_obj->get_module_setting('domain_id='.$domain.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(VIS_LOCATION_AREA==1) {            
            if(!isset($module_setting['vis_show_tickettype']) || (isset($module_setting['vis_show_tickettype']) && $module_setting['vis_show_tickettype']==2))
            {
				$ticket_type=$ticket->get_type_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))');
			 }
			 else
			 {
				$ticket_type = -1;
			 }
            if(!isset($module_setting['vis_show_priority']) || (isset($module_setting['vis_show_priority']) && $module_setting['vis_show_priority']==2))
            {
				$ticket_priority=$ticket->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))');
			}
			else
			{
				$ticket_priority = -1;
			}
			if(!isset($module_setting['vis_show_level']) || (isset($module_setting['vis_show_level']) && $module_setting['vis_show_level']==2)){
			$module_setting['vis_level']='';
			list($ticket_level_count, $ticket_level_details)=$setting_obj->get_ticket_level_list( 'is_enabled=1','',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
			}
			if(!isset($module_setting['vis_show_category']) || (isset($module_setting['vis_show_category']) && $module_setting['vis_show_category']==2)){
				$filter = 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))';
				$module_setting['vis_category']='';
				list($ticket_cat_count,$ticket_cat_details)=$setting_obj->get_ticket_category_list($filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
			}
        }
        $channels=$ticket->get_channel( 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$filter = 'is_enabled=1 and (department_access=0 or find_in_set('.$departmentid.', department_access))';
		if(!isset($module_setting['vis_show_level']) || $module_setting['vis_show_level']==0 || $module_setting['vis_show_level']==1){
			$module_setting['vis_level']='';
			list($ticket_level_count, $ticket_level_details)=$setting_obj->get_ticket_level_list( 'is_enabled=1','',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		}
		if(!isset($module_setting['vis_show_category']) || $module_setting['vis_show_category']==0 || $module_setting['vis_show_category']==1){
			$module_setting['vis_category']='';
			list($ticket_cat_count,$ticket_cat_details)=$setting_obj->get_ticket_category_list($filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		}
		if(VIS_ITIL==1){
			if(!isset($module_setting['vis_show_location']) || (isset($module_setting['vis_show_location']) && $module_setting['vis_show_location']==2))
            {
			$location_assets=$setting_obj->get_locations(" AND (".VIS_TABLE_PREFIX."itil_location.department_access = 0 OR FIND_IN_SET(".$departmentid.", ".VIS_TABLE_PREFIX."itil_location.department_access)>0)",0, -1, '', VIS_STAFF_ID);
			}
			else
			{
				$location_assets = -1;
			}
			
		}
        if(VIS_LOCATION_AREA==1) { 
            $location=array(0=>1, 1=>1);
            $custom_field_var=$this->get_custom_fields($location, 0, $departmentid, 0, $database);     
			if(VIS_SATELLITE_HELPDESK == 3)
				$domains = $ticket->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
        }
       
        if(VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3){
            include(VIS_PATH_TEMPLATE.'ticket_new_step_one.php');
        }
        elseif(VIS_LOCATION_AREA==1) {
			$filter =VIS_TABLE_PREFIX."client.client_id=".VIS_CLIENT_ID;
			$assets_details=$cmdb_object->get_assets($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA,1);
			$module_setting_assetsvar=$setting_obj->get_module_setting('module_id=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
			if(isset($operation['vis_action']) && $operation['vis_action']!='')
			$data = explode('/',$operation['vis_action']);
			if($data[3]!='' && $data[3] != 'department' && $data[3] != 'domain')
			$operation['message']='<div class="vis_message">#'.$data[3].' - '.$vis_language['MSGSUCCOTKT'].'</div>';
            $domainid=$domain_id;
            $header_title=$vis_language['TXTSUBMITTICKET'];
            $vis_title=$vis_language['TXTSUBMITTICKET'];	
			$breadcrumb['Home'] = 'index.php'; 
			$breadcrumb[$vis_language['TXTSUBMITTICKET']] = '';
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
			include(VIS_PATH_TEMPLATE.'submit_ticket.php');
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
        }$database->database_disconnect();
        return true;
    }

    function ticket_reply_form($operation) { 
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);
	    $staffSettings=$sett_obj->get_settings('title="vis_head_menu_staffNm"', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $from_email=$ticket_object->get_from_email($operation['vis_department_id'] ,VIS_STAFF_ID, VIS_LOCATION_AREA);
		
		list($tinfo, $tdetails)=$ticket_object->get_ticket('ticket_id='.$operation['vis_ticket_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        ##
		$departments=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.domain_id='.$operation['vis_domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
       	$statuses=$ticket_object->get_status_list('is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))', VIS_STAFF_ID, VIS_LOCATION_AREA);
			
		$module_setting=$sett_obj->get_module_setting('domain_id='.$operation['vis_domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$filter = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))';
		if(!isset($module_setting['vis_show_priority']) || $module_setting['vis_show_priority']==2 || $module_setting['vis_show_priority']==1){
			$module_setting['vis_priority']='';
			$priorities=$ticket_object->get_priorities_list(VIS_STAFF_ID, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))');
		}
		if(!isset($module_setting['vis_show_tickettype']) || $module_setting['vis_show_tickettype']==2 || $module_setting['vis_show_tickettype']==1){
			$module_setting['vis_tickettype']='';
			$ticket_types=$ticket_object->get_type_list(VIS_STAFF_ID, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))');
		}
		if(isset($module_setting['vis_show_level']) && ($module_setting['vis_show_level']==2 || $module_setting['vis_show_level']==1)){
			$module_setting['vis_level']='';
			list($ticket_level_count, $ticket_level_details)=$sett_obj->get_ticket_level_list( 'is_enabled=1','',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		}
		if(isset($module_setting['vis_show_category']) && ($module_setting['vis_show_category']==2 || $module_setting['vis_show_category']==1)){
			$module_setting['vis_category']='';
			list($ticket_cat_count,$ticket_cat_details)=$sett_obj->get_ticket_category_list($filter,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		
			if(isset($module_setting['vis_show_subcategory']) && ($module_setting['vis_show_subcategory']==1 || $module_setting['vis_show_subcategory']==2)){
				$module_setting['vis_subcategory']='';
				$filter_condtn = ($tdetails[0]['category_id'] == 0) ? VIS_TABLE_PREFIX.'ticket_subcategory.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_subcategory.category_id=0' : VIS_TABLE_PREFIX.'ticket_subcategory.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_subcategory.category_id='.$tdetails[0]['category_id'];
				list($cat_count,$subcategory_list)=$sett_obj->get_ticket_subcategory_list($filter_condtn,$data='', VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
		
				if(isset($module_setting['vis_show_item']) && ($module_setting['vis_show_item']==1 || $module_setting['vis_show_item']==2)){
					$module_setting['vis_item']='';
					$filter_condtn = ($tdetails[0]['subcategory_id'] == 0) ? VIS_TABLE_PREFIX.'ticket_item.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_item.subcategory_id=0' : VIS_TABLE_PREFIX.'ticket_item.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_item.subcategory_id='.$tdetails[0]['subcategory_id'];
					list($item_count,$item_list)=$sett_obj->get_ticket_item_list($filter_condtn,$data='', VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
				}
			}
		}
		
		if(VIS_ITIL==1 && VIS_MODULE_ACCESS_ITIL==1) $itil_enabled=1;
		if($itil_enabled==1){
			if(!isset($module_setting['vis_show_location']) || $module_setting['vis_show_location']==2 || $module_setting['vis_show_location']==1){
			$module_setting['vis_assets_location']='';
			$location_assets=$sett_obj->get_locations(" AND (".VIS_TABLE_PREFIX."itil_location.department_access = 0 OR FIND_IN_SET(".$operation['vis_department_id'].", ".VIS_TABLE_PREFIX."itil_location.department_access)>0)",0, -1, '', VIS_STAFF_ID);
			}
			
		}	
		#		
		
        $ticket_details=$tdetails[0];
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff_object=new class_staff($database);					
		$staff_list = $staff_object->get_staff('is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA, $ticket_details['department_id']);

if(VIS_LOCATION_AREA==2){
				$autoticketlockflag=0;
			$staffsetting=$staff_object->get_staff_group('group_id='.VIS_STAFF_GROUP, VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($staffsetting!=-1){ 
				$access=explode(',', $staffsetting[0]['access']); 
				if(isset($access[100])){$autoticketlockflag=$access[100];}else{$autoticketlockflag=0;}
				}
				else{$autoticketlockflag=0;}
			}
		$owner_details=$ticket_object->get_ticket_owner(VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $draftpost_details=$ticket_object->get_ticket_draftpost($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $attachments=$ticket_object->get_attachment('parent_type=0 and  '.VIS_TABLE_PREFIX.'attachment.parent_id='.$draftpost_details['draft_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
         list($mail_cnt, $mailQueue_ret)=$sett_obj->get_mailqueue(VIS_TABLE_PREFIX.'mailqueue.is_enabled=1 and '.VIS_TABLE_PREFIX.'mailqueue.department_id='.$operation['vis_department_id'], '', 0, '', 0, 0);
         $mailQueueId = '';
        if($mailQueue_ret!=-1){
			 for($i = 0;$i< count($mailQueue_ret);$i++) $mailQueueId[] = $mailQueue_ret[$i]['email'];
		}
		$selfhelp=$sett_obj->get_settings(' module_id=4 and title="vis_suggetion" and domain_id='.$ticket_details['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		
					
				
		if(($selfhelp[0]['content']!=0 && $selfhelp[0]['content']!=1) || $selfhelp==-1) $selfhelp=1;
        if($operation['vis_action']!='replyall' && trim($ticket_details['recipients'])=='') $ticket_details['recipients']=$ticket_details['email'];
        elseif($operation['vis_action']=='replyall'){
            if(trim($ticket_details['recipients'])=='') $ticket_details['recipients']=$ticket_details['email'];
        }
		if($ticket_details['email']=='' && $ticket_details['channel_id']==4){
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        	$client_object=new class_client($database);
			$filter='salt="'.$ticket_details['salt'].'"';
			list($client_info, $client_details)=$client_object->get_client($filter, 1, 0, '', '', VIS_LOCATION_AREA);
			$ticket_details['recipients']=$client_details[0]['user_name'];	
			$ticket_details['client_id']=$client_details[0]['client_id'];			
		}
		if($ticket_details['email']=='' && $ticket_details['channel_id']==3){
			$ticket_details['recipients']=$ticket_details['last_replier_email'];
		}
        $signaturedata=$staff_object->get_signature('staff_id='.VIS_STAFF_ID.' and department_id='.$operation['vis_department_id'].' and is_forum=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($signaturedata!=-1) $signature=$signaturedata[0]['content'];
        $ticket_details['recipients']=trim($ticket_details['recipients'], ' ,');
        $ticket_posts=(isset($signature) && $signature!='')?'<p><br /></p><br />'.$signature:'';
        if((($operation['vis_action']=='forward' || $operation['vis_action']=='reply' || $operation['vis_action']=='replyall') && (isset($operation['vis_post_id']) && $operation['vis_post_id']>0)) || ($operation['vis_action']=='forward' && isset($operation['vis_ticket_id']) && $operation['vis_ticket_id']>0))
         {
            if(isset($operation['vis_post_id']) && $operation['vis_post_id']>0)
				$postdetails=$ticket_object->get_ticket_post(0, $operation['vis_post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			else
				$postdetails=$ticket_object->get_ticket_post($operation['vis_ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
            $postids=' ';
            for($i=0;$i<count($postdetails);$i++) {
                $postids.=$postdetails[$i]['post_id'].',';
                $ticket_posts.='<p><br></p>--------------------------------------------------------------------<br><br><strong>'.$postdetails[$i]['submitter_name'].' ('.$postdetails[$i]['submitter_email'].')<br>'.format_datetime($postdetails[$i]['receive_date']).'</strong><br><br>'.$postdetails[$i]['content'];
            }
            $postids=substr($postids, 0, -1);
            if($draftpost_details['draft_id'] !='')$attachmentCondition = ' or '. VIS_TABLE_PREFIX.'attachment.parent_id='.$draftpost_details['draft_id'];
            $attachments=$ticket_object->get_attachment('parent_type=0 and '.VIS_TABLE_PREFIX.'attachment.parent_id in ('.$postids.')'.$attachmentCondition, VIS_STAFF_ID, VIS_LOCATION_AREA);
        }
       // echo "++>>";
      //  print_r($postdetails);
       // for($i=0;$i<count($postdetails);$i++)
       // {
			//$rpl_post_content.=$postdetails[$i]['content'];
		//}
        
		$admin_access=$staff_object->get_staff_access('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($admin_access==-1)$filter_macro.=' and staff_id = ' . VIS_STAFF_ID.' or access = "0"';
		$macro_count = $staff_object->get_macros_list('is_enabled=1 and (department = '.$operation['vis_department_id'].' or department = 0) '.$filter_macro, VIS_STAFF_ID, VIS_LOCATION_AREA,'','','',1);
		
		//$macro_count = $staff_object->get_macros_list('is_enabled=1 and (department = '.$operation['vis_department_id'].' or department = 0)', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if (defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR != 1) {  
			$ticket_posts = get_plain_text($ticket_posts);
			 if($draftpost_details['draft_data'] !='') $draftpost_details['draft_data'] = get_plain_text($draftpost_details['draft_data']);
	    }
	    
	    list($module_info, $drive_setting1)=$sett_obj->get_module('module_id=13', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(($drive_setting1[0]['is_enabled']=='1' && $drive_setting1[0]['is_enabled']!='') || !empty($drive_setting)) $drive_setting=1;
       
        $database->database_disconnect();
	    if($operation['vis_action']=='forward')
            include(VIS_PATH_TEMPLATE.'ticket_forward.php');
        else
            include(VIS_PATH_TEMPLATE.'ticket_reply.php');
    }

    function reply_ticket($operation) {
	
		global $vis_language;
	    $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff=new class_staff($database);
        if(VIS_LOCATION_AREA==2) {
            $data=parse_form_array($operation['vis_action']);
            $data=array_merge($operation, $data);
        }
	    else $data= array_map("addslashes", $operation);
	 	   if(!(isset($data['vis_ticket_id']) && is_numeric($data['vis_ticket_id']))) {
            echo '<script>$("#vis_reply_ticket_button").removeAttr("disabled");  $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
            return false;
        } 
        if((VIS_LOCATION_AREA==2 && isset($data['vis_internal_ticket']) && !$data['vis_internal_ticket']) && $data['vis_channel']!=2) { // To/Recipients field validation
			$char=substr(trim($data['vis_to_email']), -1);
			if($char==','){
				$data['vis_to_email']=substr(trim($data['vis_to_email']), 0, -1);
			}
			if(strpos($data['vis_to_email'],',')){
				$email=explode(',', $data['vis_to_email']);
			}
			else $email[0]= $data['vis_to_email'];
			if($data['vis_channel']!=4 && $data['vis_channel']!=3){
				foreach($email as $key=>$val){
					if(isset($val) && trim($val)!='')
					 {
						list($message, $flag) = check_email_validation($val);
						if(!$flag) {
							echo '<script> $("#vis_reply_ticket_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
							return false;
						} 
					 }					 
				}
			}
		}
		if(((VIS_LOCATION_AREA==2 && isset($data['vis_internal_ticket']) && !$data['vis_internal_ticket'] ) && $data['vis_channel']!=2) || VIS_LOCATION_AREA==0 ) { // people validation
			$char=substr(trim($data['vis_people']), -1);
			if($char==',') {
				$data['vis_people']=substr(trim($data['vis_people']), 0, -1);
			}
			if(strpos($data['vis_people'],','))	{
				$email=explode(',', $data['vis_people']);
			}
			else $email[0]= $data['vis_people'];
				foreach($email as $key=>$val){
					if(isset($val) && trim($val)!='')
					 {
						list($message, $flag) = check_email_validation($val);
						if(!$flag) {
							echo '<script>$("#vis_reply_ticket_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
							return false;
						} 
					 }
				}
		} 		
        if(!isset($data['vis_ticket_post']) || (isset($data['vis_ticket_post']) && trim(strip_tags($data['vis_ticket_post'],"<img>")) == '')) { 

             echo '<script>$("#vis_reply_ticket_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGPOSTMESSAGENOTFOUND'].'"); </script>';
            return false;
        }
        if(VIS_LOCATION_AREA==0 || VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3) { // from field validation
            if(!isset($data['vis_from'])) {
                echo '<script>$("#vis_reply_ticket_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNDRMISS'].'"); </script>';
                return false;
            }
            else {
                if(preg_match("/^(.*)<(.*)@(.*)>/", $data['vis_from'], $match)) {
                    $data['vis_from_name']=trim($match[1], "\x22\x27 \t\"\\\'\;\>\<");
                    $data['vis_from_email']=trim($match[2], "\x22\x27 \t\"\\\'\;").'@'.trim($match[3], "\x22\x27 \t\"\\\'\;");
                }
                else {
                    $data['vis_from_name']='';
                    $data['vis_from_email']=trim($data['vis_from'], "\x22\x27 \t\"\\\'\;");
                }
            }
            $user=VIS_STAFF_ID;
        }
        if(VIS_LOCATION_AREA!=2) {
		if(defined('VIS_HEAD_MENU_HTML_EDITOR') && VIS_HEAD_MENU_HTML_EDITOR==0)
		 $data['vis_ticket_post'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_ticket_post']);
        }
        if(VIS_LOCATION_AREA==1) {
            $user=VIS_CLIENT_ID;
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $data['vis_draft']=(isset($operation['vis_draft']))?$operation['vis_draft']:0;
        $ticket_object=new class_ticket($database);
        list($info, $ticket)=$ticket_object->get_ticket('ticket_id='.$data['vis_ticket_id'], '', 0, '', $user, VIS_LOCATION_AREA);
		$tickets=array_merge($data, $ticket[0]);
        if(VIS_LOCATION_AREA ==1){
            if(VIS_REPLY_TICKET == 0 && $tickets['client_id'] != VIS_CLIENT_ID){
                $operation['message']=$vis_language['MSGACCSSDND'];                
                $this->new_ticket_step_one($operation);
                return false;
            }
        }
        if((VIS_LOCATION_AREA==0 || VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3) && $operation['vis_draft']!=1){
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
            $staff=new class_staff($database);
            if((defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR==0) || VIS_LOCATION_AREA==0)
			$tickets['vis_ticket_post'] = str_replace(array("\r\n","\r","\n"),"<br>",$tickets['vis_ticket_post']);
			$tickets['vis_comment'] = str_replace(array("\r\n","\r","\n"),"<br>",$tickets['vis_comment']);
            $staff_info=$staff->get_staff('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
            $tickets['vis_from_name']=trim($staff_info[0]['first_name'].' '.$staff_info[0]['last_name'], ' "-');
        }
        $tickets['received_via'] = (VIS_LOCATION_AREA == 1 || VIS_LOCATION_AREA == 2) ? 1 : 0;
		if(VIS_LOCATION_AREA == 0) {
			$tickets['received_via'] = 3;
			$tickets['vis_to_email'] = $tickets['email'];
		}
		if(VIS_LOCATION_AREA == 1) {
			$from_email = $ticket_object->get_from_email($tickets['department_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			$tickets['vis_to_email'] = $from_email[0]['override_email'];
		} 
		#sub-contact mail setting
		if(VIS_LOCATION_AREA==2){ //print_r($tickets); die;
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
			$client_obj=new class_client($database);
			$subdetails=$client_obj->get_subclient_setting($tickets['client_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
			$sc_parent_id = $tickets['client_id'];
			$sc_cc ='';
			if($tickets['parent_id']!=0) {	
				$sc_parent_id = $tickets['parent_id'];
				list($pclinfo, $parent_client)=$client_obj->get_client('client_id='.$tickets['parent_id'], '', 0, '', $tickets['client_id'], VIS_LOCATION_AREA);
				if($subdetails[6]==1){ 
					//Parent client should receive a copy of emails submitted by this contact
					$sc_cc =	trim($parent_client[0]['email']);						
				}				
			}
			//Receive a copy of emails submitted by parent client and other contacts
			//for seting id 7
			$sub_contatct_emaillist = $client_obj->get_subcontact_email("AND ct.parent_id =".$sc_parent_id." AND ct.client_id!=".$tickets['client_id']);			
			if($sub_contatct_emaillist!=-1){
				for($sc=0;$sc<count($sub_contatct_emaillist);$sc++){
					$sc_cc .= ','.trim($sub_contatct_emaillist[$sc]['email']);
				}
			}
			$tickets['sub_contact_cc'] = trim($sc_cc,','); 		
		}
		
	    $ret=$ticket_object->reply_ticket($tickets, $user, VIS_LOCATION_AREA);
		
		if(VIS_LOCATION_AREA==1 && isset($operation['vis_ticket_priority'])){
            $ret1=$ticket_object->set_ticket_property('priority', $operation['vis_ticket_priority'], array($operation['vis_ticket_id']), $user, VIS_LOCATION_AREA);
            if($ret1!=-1) {
				global $operation_hnd;
                $operation['vis_action']='priority';
                $operation['vis_operation']='update_properties';
                $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			    $staff->apply_task_automation($operation,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
            }
        }
		
	    if($ret && $data['vis_draft']!=1) {
            $data['vis_operation']='reply_ticket';
            $tickets['vis_post_id']=(is_numeric($ret))?$ret:$data['vis_post_id'];
            if(VIS_LOCATION_AREA!=1 && $tickets['channel_id']==4 && isset($data['vis_private']) && $data['vis_private']==1) {
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        		$mail_object=new class_mail($database);
		        $tweet=$ticket_object->add_reply_tweet($tickets, $user, VIS_LOCATION_AREA);
				$message_id=$mail_object->set_fetchmail('tw_'.$tweet->id, 0, VIS_LOCATION_AREA);
            }
            elseif(VIS_LOCATION_AREA!=1 && $tickets['channel_id']==3 && isset($data['vis_private']) && $data['vis_private']==1) {
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        		$mail_object=new class_mail($database);
			    $fb_msg=$ticket_object->add_reply_fb_comment($tickets, $user, VIS_LOCATION_AREA);
				$message_id=$mail_object->set_fetchmail($fb_msg, 0, VIS_LOCATION_AREA);
		    }
            global $operation_hnd;
            $operation_hnd->check_automation($tickets);
            $operation_hnd->operation_flow($tickets, $user, VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($tickets,$user, VIS_LOCATION_AREA, $database);
		 

			
			 //Send notification reply ticket
            if($ret)
            {
	        $this->send_notification($data['vis_ticket_id'],2,$data['vis_department']);
            }
        }
	
        if(VIS_LOCATION_AREA==2) {
            if(!$ret) {
                echo '<script> $("#vis_reply_ticket_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            }
            else {
				$operationlock = array();
				$operationlock=$operation;
			    $operationlock['vis_action']='unlock';
				$operationlock['vis_ticket_id']=($operation['vis_ticket_id']!='')?$operation['vis_ticket_id']:$data['vis_ticket_id'];
		        $this->lock_onreplyticket($operationlock);
				if(VIS_GAMIFICATION_ACCESS == 1 && $operation['vis_draft']!=1) 
				{
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
					$setting_object=new class_setting($database);
					$event = '' ;

				    $response_diff  =  time() - $tickets['receive_date'] ;
					
				    $time_diff = ($response_diff/60);
					
					if($time_diff <= 10 && $tickets['user_replied'] == 1){
						$event[] = 1;
				    }
				    if($tickets['resolution_time'] >0 && $tickets['user_replied'] == 1 && $tickets['status_id']!=3){
						$event[] = 2;
					}
					if($tickets['due_time']<=0 && $tickets['user_replied'] == 1 && $tickets['status_id']!=3 && $tickets['sdue_time']!=0){
						$event[] = 3;
					}
					if(!empty($event))
					{
						for($i=0;$i< count($event);$i++){ 
							$points = $setting_object->calculate_points($staff_info[0],$event[$i],IS_STAFF_ID,VIS_LOCATION_AREA); 
						}
					}
					$details_quest =  $setting_object->calculate_game_points($tickets,$staff_info[0],1,IS_STAFF_ID, VIS_LOCATION_AREA); 
				} 
				
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
			  	$database=new class_database();
				if (($database instanceof class_database) != true ) {
  				  $database = new class_database();
				}
					$staff_obj=new class_staff($database);
					$staffsetting=$staff_obj->get_staff_group('group_id='.VIS_STAFF_GROUP, $userid, $user);
					
				//$backtolist=$setting_obj->get_settings(' module_id=2 and title="vis_back_to_listing" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($staffsetting!=-1){ 
				$access=explode(',', $staffsetting[0]['access']); 
				
				if(isset($access[101])){$backflag=$access[101];}else{$backflag=0;}
				
				}
				else{$backflag=0;}
				
				if(!isset($operation['vis_ticket_mass'])){
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");'; 
					echo '$("#vis_ticket_reply_'.$data['vis_ticket_id'].'").html("").hide();';
					if($data['vis_draft']!=1){
						
						//echo '$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":'.$data['vis_ticket_id'].'});';
						if($backflag==1){
							echo 'history.back(); var bku=window.location.href; if(bku.toLowerCase().indexOf("ticket")<=0){ $("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTTICKETS'].'",{"vis_module":"ticket", "vis_operation":"filter_ticket" , "vis_action":"#/ticket/filter_ticket/'.$vis_language['TXTTICKETS'].'/1"});}';
						}else{
						echo "$('#vis_details_list_".$data['vis_ticket_id']."').visExecution('load_area',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':".$data['vis_ticket_id'].", 'vis_department_id':".$tickets['department_id'].", 'vis_readonly':1, 'ticket_reply_call':'reply'});";
						echo "$('#vis_ticket_post_forms').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_ticket_post', 'vis_ticket_id':".$data['vis_ticket_id']."});";
						}
					}
					
					echo '$("#vis_global_msg_div").visExecution("load_area",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"});';
					echo '</script>';
				}
            }
        }
        elseif(VIS_LOCATION_AREA==3) {
            $operation['vis_message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
            $this->filter_ticket($operation);
        }
        elseif(VIS_LOCATION_AREA==0) {
            echo (!$ret)?'error':'success';
        }
        else { 
            $operation['message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
			$_SESSION['message'] =  $operation['message'];
			
            $operation['vis_status']='';
            if($ticket_object->error!='') $operation['message']='<div class="vis_error_message">'.$ticket_object->error.'</div>';
            //$this->view_ticket($operation);
           /* if(VIS_LOCATION_AREA == 1)
            {
				echo "<script>window.location = 'index.php?/ticket/view-ticket'; </script>";
			}
			else
			{*/
			 if(!defined('IS_WHMCS')) echo json_encode( array('vis_msg' => $operation['message']));
			 else echo '<script>window.location = "supporttickets.php";</script>';
			//}
        }
		if(!isset($operation['vis_ticket_mass'])){
			$database->database_disconnect();
		}
        return $ret;
    }

    function ticket_reply($operation) {
		global $vis_language;
        $userid=(defined('VIS_CLIENT_ID'))?VIS_CLIENT_ID:VIS_STAFF_ID;
        if(isset($operation['vis_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			$operation['ticket_id'] = $data[4];
		}
        if(VIS_LOCATION_AREA==1 && $userid==0){
             if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
             include(VIS_PATH_TEMPLATE.'login.php');
             include(VIS_PATH_TEMPLATE.'footer.php');
             break;
         }
         if($operation['ticket_id'] == '' && VIS_LOCATION_AREA == 1){
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                echo '<div class="vis_error_message"><br/>'.$vis_language['TXTNOMATCHFOUND'].'<br/><br/></div>';
                include(VIS_PATH_TEMPLATE.'footer.php');
                break;
         }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $ticket_object=new class_ticket($database);
        $client_object=new class_client($database);
        $staff_object=new class_staff($database);
        $setting_obj=new class_setting($database);
        list($info, $modules)=$setting_obj->get_module('is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        foreach($modules as $var) $module[$var['module']]=1;
        $staffSettings=$setting_obj->get_settings('title="vis_head_menu_staffNm" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $attachment=$setting_obj->get_settings(' module_id=2 and title="vis_attachment" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $attachment=is_numeric($attachment[0]['content'])?$attachment[0]['content']:100;
        $ticketCloseSetting=$setting_obj->get_settings('title="vis_head_menu_close_ticket" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticketCloseSetting != -1 && $ticketCloseSetting[0]['content'] == 0) $ticketCloseSettings = -1; 

        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['ticket_id'];
        if(VIS_VIEW_SELFTICKET==0 && defined('VIS_REPLY_TICKET') && VIS_REPLY_TICKET==1 && VIS_LOCATION_AREA==1) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            $client='';
            $parent=(VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
            $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            if($client_details!=-1) for($i=0;$i<count($client_details);$i++) if($client_details[$i]['client_id']!=VIS_CLIENT_ID) $client.=$client_details[$i]['client_id'].',';
            if($client!='') $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id in ('.$client.$parent.')';
            else $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.$parent;
        }elseif(VIS_VIEW_SELFTICKET==1 && defined('VIS_REPLY_TICKET') && VIS_REPLY_TICKET==1 && VIS_LOCATION_AREA==1) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            $client='';
            $parent=(VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
            $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            if($client_details!=-1) for($i=0;$i<count($client_details);$i++) $client.=$client_details[$i]['client_id'].',';
            if($client!='') $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id in ('.$client.$parent.')';
            else $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
        }
        elseif(VIS_LOCATION_AREA!=3){
            if(VIS_LOCATION_AREA==1){
                if(VIS_REPLY_TICKET==0 && VIS_VIEW_SELFTICKET==0) $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id!='.VIS_CLIENT_ID.' AND '.VIS_TABLE_PREFIX.'client.client_id!='.VIS_CLIENT_PARENT;
                else $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
            }else $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
        }
		
		$client_detail=$client_object->get_client_list(VIS_CLIENT_ID , '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
		if(VIS_LOCATION_AREA==1){
			for($i=0;$i<count($client_detail);$i++){
				if($client_detail[$i]['is_manager']==1)
				{
					$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['ticket_id'];
				}
			}
		}
		
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', $userid, VIS_LOCATION_AREA);

        $filter=' (location in (1,2,3)) and (department_access=0 or find_in_set('.$ticket_details[0]['department_id'].', department_access)) and is_enabled=1 ';
        $custom_group=$setting_obj->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);

       

	   if($ticket_details==-1) {
            $operation['err_message']=$vis_language['MSGACCSSDND'];
            return $this->view_ticket($operation);
        }
        $ticket_details=$ticket_details[0];
        if(VIS_LOCATION_AREA==1) {
            list($client_info, $client_details)=$client_object->get_client('client_id='.VIS_CLIENT_ID, 1, 0, '', $userid, VIS_LOCATION_AREA);
            $client_details=$client_details[0];
            $priority_list=$ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))');
        }
        if(VIS_LOCATION_AREA==3) {
            $departments=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.domain_id='.$ticket_details['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $from_email=$ticket_object->get_from_email( $ticket_details['department_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $status=$ticket_object->get_status_list('is_enabled=1 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $priorities=$ticket_object->get_priorities_list(VIS_STAFF_ID, VIS_LOCATION_AREA, 'is_enabled=1 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))');
            $draftpost_details=$ticket_object->get_ticket_draftpost($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
        }
		$location=array(0=>3, 1=>3);
        $custom_field_var = $this->get_custom_fields($location, 0, $ticket_details['department_id'], $ticket_details['ticket_id'], $database);
        $post_details=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, $userid, VIS_LOCATION_AREA);
		$module_setting=$setting_obj->get_module_setting('domain_id='.$ticket_details['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(isset($module_setting['vis_show_priority']) && ($module_setting['vis_show_priority']==0 ||$module_setting['vis_show_priority']==1))
			    $ticket_priority = -1;
		 if(isset($module_setting['vis_show_tickettype']) && ($module_setting['vis_show_tickettype']==0 || $module_setting['vis_show_tickettype']==1))
				$ticket_type = -1;
        $database->database_disconnect();
        $post_count=count($post_details);
        $ticket_reply = $data[2];
        $header_title=$vis_language['TXTREPLYTICKET'];		
			$breadcrumb['Home'] = 'index.php'; 
			$breadcrumb[$vis_language['TXTVIEWTICKETS']] = '?/ticket/view-ticket'; 
			$breadcrumb[$ticket_details['ticket_hash']] = '';
			$vis_title = $vis_language['TXTVIEWTICKETS'];
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
        else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
        if(defined('IS_WHMCS') && IS_WHMCS==1) include(VIS_PATH_TEMPLATE.'ticket_reply.php');
        else include(VIS_PATH_TEMPLATE.'ticket_details.php');    
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
        return true;
    }

    function ticket_edit($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $userid=(defined('VIS_CLIENT_ID') && VIS_LOCATION_AREA==1)?VIS_CLIENT_ID:VIS_STAFF_ID;
        if(VIS_LOCATION_AREA==1 && $userid==0){
             if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
             include(VIS_PATH_TEMPLATE.'login.php');
             include(VIS_PATH_TEMPLATE.'footer.php');
             break;
         }

        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['ticket_id'];
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', $userid, VIS_LOCATION_AREA);
        $ticket_details=$ticket_details[0];
        if(VIS_LOCATION_AREA==1) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            $client='';
       
            if(IS_LOGIN && !empty($ticket_details) && $ticket_details['client_id'] != VIS_CLIENT_ID){
                $operation['message']=$vis_language['MSGACCSSDND'];                
                $this->new_ticket_step_one($operation);
                return false;
            }
            if(VIS_CLIENT_ID==0) exit;
            if(VIS_CLIENT_ID != $ticket_details['client_id'] && !empty($ticket_details) &&  VIS_LOCATION_AREA==1){
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
                else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
                echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
                if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
                break;
            }
            $parent=(VIS_CLIENT_PARENT==-1)?VIS_CLIENT_ID:VIS_CLIENT_PARENT;
            $client_details=$client_object->get_client_list('parent_id='.$parent, '', 0, '', VIS_CLIENT_ID, VIS_LOCATION_AREA);
            if($client_details!=-1) for($i=0;$i<count($client_details);$i++) $client.=$client_details[$i]['client_id'].',';
            if($client!='') $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id in ('.$client.$parent.')';
            else $filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;

            $type_list=$ticket_object->get_type_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))');
            $status_list=$ticket_object->get_status_list('is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))', $userid, VIS_LOCATION_AREA);
            $priority_list=$ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1 and access_type=0 and (department_access=0 or find_in_set('.$ticket_details['department_id'].', department_access))');

        }
        else {
            $type_list=$ticket_object->get_type_list($userid, VIS_LOCATION_AREA, 'is_enabled=1');
            $status_list=$ticket_object->get_status_list('is_enabled=1', $userid, VIS_LOCATION_AREA);
            $priority_list=$ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, 'is_enabled=1');
        }
        //$filter.=' and '.VIS_TABLE_PREFIX.'client.client_id='.$userid;

        $post_details=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, $userid, VIS_LOCATION_AREA);
        $post_count=count($post_details);
        $header_title=$vis_language['TXTEDITTICKET'];
        $location=array(0=>1, 1=>2);
        $custom_field_var = $this->edit_custom_fields($location, $operation['ticket_id'], $ticket_details['department_id'], $database);
        $database->database_disconnect();
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
        else echo '<link href="'.VIS_PORTAL_URL.VIS_PATH_STYLE.'vis_style.css" rel="stylesheet" />';
        include(VIS_PATH_TEMPLATE.'ticket_edit.php');
        if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'footer.php');
    }

    function forward_ticket($operation) {
        global $vis_language;
        $data=array_merge($operation, parse_form_array($operation['vis_action']));
        if(!(isset($data['vis_ticket_id']) && is_numeric($data['vis_ticket_id']))) {
            echo '<script> $("#vis_ticket_forward_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
            return false;
        }
         $char=substr(trim($data['vis_to_email']), -1);
        if($char==',')
        {
			$data['vis_to_email']=substr(trim($data['vis_to_email']), 0, -1);
		}
        if(strpos($data['vis_to_email'],','))
        {
			$email=explode(',', $data['vis_to_email']);
		}
		else 
		{
			$email[0]= $data['vis_to_email'];
			
			if((isset($data['vis_to_email']) || trim($data['vis_to_email'])!=''))
			{
				list($message, $flag) = check_email_validation($data['vis_to_email']);
				if(!$flag) {
					echo '<script>  $("#vis_ticket_forward_button").removeAttr("disabled");  $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
					return false;
				} 
			}
		}
		
		
		
		
        foreach($email as $key=>$val)
        {
				if(isset($val) && trim($val)!='')
					 {
						list($message, $flag) = check_email_validation($val);
						if(!$flag) {
							echo '<script>  $("#vis_ticket_forward_button").removeAttr("disabled");  $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
							return false;
						} 
					 }
		}
		if(VIS_LOCATION_AREA==2)
		{
				$char=substr(trim($data['vis_people']), -1);
				if($char==',')
				{
					$data['vis_people']=substr(trim($data['vis_people']), 0, -1);
				}
				if(strpos($data['vis_people'],','))
				{
					$email=explode(',', $data['vis_people']);
				}
				else $email[0]= $data['vis_people'];
				foreach($email as $key=>$val)
				{
					if(isset($val) && trim($val)!='')
					 {
						list($message, $flag) = check_email_validation($val);
						if(!$flag) {
							echo '<script> $("#vis_ticket_forward_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
							return false;
						} 
					 }
				}
		}
        if(!isset($data['vis_from'])) {
            echo '<script> $("#vis_ticket_forward_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNDRMISS'].'"); </script>';
            return false;
        }
        else {
            if(preg_match("/^(.*)<(.*)@(.*)>/", $data['vis_from'], $match)) {
                $data['vis_from_name']=trim($match[1], "\x22\x27 \t\"\\\'\;\>\<");
                $data['vis_from_email']=trim($match[2], "\x22\x27 \t\"\\\'\;").'@'.trim($match[3], "\x22\x27 \t\"\\\'\;");
            }
            else {
                $data['vis_from_name']='';
                $data['vis_from_email']=trim($addr, "\x22\x27 \t\"\\\'\;");
            }
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        if((VIS_LOCATION_AREA==0 || VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3) && $operation['vis_draft']!=1){
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
            $staff=new class_staff($database);
            $staff_info=$staff->get_staff('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
            $data['vis_from_name']=trim($staff_info[0]['first_name'].' '.$staff_info[0]['last_name'], ' "-');
        }
        $data['received_via']=(VIS_LOCATION_AREA == 1 || VIS_LOCATION_AREA==2)?1:0;		
        $data = $ticket_object->check_all_field_deptaccess($data);
        if(defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR==0)
		$data['vis_ticket_post'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_ticket_post']);
		$data['vis_comment'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_comment']);
        $ret=$ticket_object->forward_ticket($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ret) {
            global $operation_hnd;
            $data=array_merge($data, $operation);
            $data['vis_post_id']=$ret;
            $operation_hnd->check_automation($data);
            $operation_hnd->operation_flow($data, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
        }
								
								include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
					$staff_obj=new class_staff($database);
					$staffsetting=$staff_obj->get_staff_group('group_id='.VIS_STAFF_GROUP, $userid, $user);
				//$backtolist=$setting_obj->get_settings(' module_id=2 and title="vis_back_to_listing" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($staffsetting!=-1){ 
				$access=explode(',', $staffsetting[0]['access']); 
				if(isset($access[94])){$backflag=$access[94];}else{$backflag=0;}
				}else{$backflag=0;}
								
        $database->database_disconnect();
        if(!$ret) echo '<script>$("#vis_ticket_forward_button").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        else 
								if($backflag==1){
										echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
										echo ' history.back(); var bku=window.location.href; if(bku.toLowerCase().indexOf("ticket")<=0){ $("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTTICKETS'].'",{"vis_module":"ticket", "vis_operation":"filter_ticket" , "vis_action":"#/ticket/filter_ticket/'.$vis_language['TXTTICKETS'].'/1"});}';
										echo '</script>';
								}else{
										echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":'.$data['vis_ticket_id'].'}); $("#vis_global_msg_div").visExecution("load_area",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"}); </script>';
								}
        return $ret;
    }

    function open_new_ticket($operation) { 
	//echo "open_new_ticket==>  ";print_r($operation);
	    global $vis_language, $operation_hnd;
	    $is_approved=1;
        $is_banned=0;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $database=new class_database();
        if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4)) $data=parse_form_array($operation['vis_action']);
        else 
        {
			  foreach($operation as $key=>$val) {
				  if(!is_array($val))
				  $data[$key] = addslashes($val);
				  else
				  $data[$key] = $val;
			  }
		}
		if(!isset($data['vis_firstname']) && isset($data['vis_fullname'])){
			$vis_fullname = explode(' ',$data['vis_fullname']);
			$data['vis_firstname'] = $vis_fullname[0];
			$data['vis_lastname'] = $vis_fullname[1];
		}
	    $client_obj=new class_client($database);
        $ticket_object=new class_ticket($database);
        $bill_check=$ticket_object->check_billing($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $userid=defined('VIS_CLIENT_ID')?VIS_CLIENT_ID:VIS_STAFF_ID;
		$vis_domain =  (VIS_SATELLITE_HELPDESK == 2 || VIS_SATELLITE_HELPDESK == 3) ? 1 : $data['vis_domain'];
		if(VIS_LOCATION_AREA == 4){ $userid = $data['vis_staff']; }
		if(VIS_LOCATION_AREA==0){
				$fid=2;
				for($f=0;$f<100;$f++){
					if($data['field'.$fid.'']!=''){
						$data['custom_field'][$f]['cid']='field'.$fid;
						$data['custom_field'][$f]['value']=$data['field'.$fid.''];
						$data['field'.$fid.'']=$data['field'.$fid.''];
					}
					$fid++;					
				}
		}
        if(VIS_LOCATION_AREA == 1){
            if(IS_LOGIN && $data['vis_client'] != VIS_CLIENT_ID){
                $operation['message']=$vis_language['MSGINFOMISS'];
                $operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].'</div>';
                $this->new_ticket_step_one($operation);
                return false;
            }
        }
        $check_custom = true;
		if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) || VIS_LOCATION_AREA == 0 || VIS_LOCATION_AREA == 3){
				if(isset($data['vis_service_item_id']) && $data['vis_service_item_id']>0)
				{
					
				$check_custom=$ticket_object->check_custom_data($data, 2, $data['vis_service_item_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
				}
				else
				{
				$check_custom=$ticket_object->check_custom_data($data, 2,0, VIS_STAFF_ID, VIS_LOCATION_AREA); 
				}
		}
        if(VIS_LOCATION_AREA == 1){  
            for($i=0;$i<count($data['custom_field']);$i++){
                $data[$data['custom_field'][$i]['cid']]=$data['custom_field'][$i]['value'];
            }
            $check_custom=$ticket_object->check_custom_data($data, 1, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
			////
			##get data from custom form
			if(isset($data['form_field']) && count($data['form_field'])>0){
				//print_r($data['form_field']); 
				$field_data = array();
				for($f=0;$f<count($data['form_field']);$f++){
					$field_id = trim(str_replace('field','',$data['form_field'][$f]['cid']));
					$field_data[$field_id] = $data['form_field'][$f]['value'];
					
				}
				$data['field_data'] = $field_data;
				$validate_form_data = $ticket_object->validate_form_data($data, VIS_STAFF_ID, VIS_LOCATION_AREA,$vis_language);
				
				$str_ids = implode(',',array_keys($field_data));				
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
				$setting_object = new class_setting($database);
				
				$query = 'SELECT fld.*,grp.form_name FROM `avis_formfield` as fld LEFT JOIN `avis_formgroup` as grp on fld.formgroup_id=grp.formgroup_id   WHERE fld.formfield_id IN ('.$str_ids.')  order by display_order asc ';
				$result = $database->query_exec($query);
				$form_fields_details= $database->fetch_result_array($result);
				$body_msg = '';
				$field_group = 0;
				//$body_msg .= $form_fields_details[0]['form_name'];
				for($m=0;$m<count($form_fields_details);$m++){
					 $que='select title from avis_language_data where language_id='.VIS_LANGUAGE.' and location=26 and data_id='.$form_fields_details[$m]['field_group'];
					$result = $database->query_exec($que);
				$fieldname= $database->fetch_result_array($result);
					if($form_fields_details[$m]['field_type']==7){
						$body_msg .= '<br/>'.$fieldname[0]['title'].' :  '.implode(', ',$field_data[$form_fields_details[$m]['formfield_id']]);
					}if(trim($form_fields_details[$m]['field_type'])==4 ){						
						if($field_group==0 || $field_group !== $form_fields_details[$m]['field_group']){
							$body_msg .= '<br/>'.$fieldname[0]['title'].' :  '.$field_data[$form_fields_details[$m]['formfield_id']];
							$field_group = $form_fields_details[$m]['field_group'];
						}else if($field_group == $form_fields_details[$m]['field_group']){
							$body_msg .= ', '.$field_data[$form_fields_details[$m]['formfield_id']];
							$field_group = $form_fields_details[$m]['field_group'];
						}
						
					}else if($form_fields_details[$m]['field_type']!=7 && $form_fields_details[$m]['field_type']!=4){
						$body_msg .= '<br/>'.$fieldname[0]['title'].' :  '.$field_data[$form_fields_details[$m]['formfield_id']];
					}
				}
				
				//print_r($form_fields_details);			
				$data['vis_ticket_post'] = $body_msg;	
			}
			//$data['vis_ticket_post'] = $body_msg;
			###get data from custom form
		}
		$customerrormessage=' ('.$check_custom[1].')';
		if($check_custom!=1 && $check_custom[0]==0){ $check_custom=false; }
		//+++
        if(VIS_LOCATION_AREA == 2 && $check_custom == false){
            echo '<script> $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'"); </script>';
            return false;
        }  
        if((VIS_LOCATION_AREA == 1 && !IS_LOGIN)|| $data['vis_custom_form']==1){   
			$data['vis_firstname']=strip_tags($data['vis_firstname']);
			$data['vis_lastname']=strip_tags($data['vis_lastname']);   
			$data['vis_email']=strip_tags($data['vis_email']);  
		}
        ##Form creation tool
		if(isset($data['vis_custom_form']) && $data['vis_custom_form']==1 ){		
			if($data['vis_form_type']==0){
				$data['vis_firstname']=strip_tags($data['vis_firstname']);
				$data['vis_lastname']=strip_tags($data['vis_lastname']);   
				$data['vis_contact_number']=strip_tags($data['vis_contact_number']);  
			}			
		}
		###Form creation tool   
		
        if(VIS_LOCATION_AREA == 1 && $data['vis_honeypot']!=''){
            $operation['message']=$vis_language['MSGINFOMISS'];
            $operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>';
            echo json_encode( array('vis_error_msg' => $operation['vis_message']) );
            return false;
        }
        $data['vis_subject']=strip_tags($data['vis_subject']);   
        if((VIS_LOCATION_AREA == 1 || VIS_LOCATION_AREA == 3) && $check_custom == false && (!isset($data['vis_custom_form']) && $data['vis_custom_form']!=1) && (!isset($data['vis_service_item_id']))){
			//++++
            $operation['message']=$vis_language['MSGINFOMISS'].''.$customerrormessage;
            $operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'</div>';
            echo json_encode( array('vis_error_msg' => $operation['vis_message']) );
            return false;
        }
		
        if(VIS_LOCATION_AREA == 1 && isset($data['vis_department']) && $data['vis_department']=='') {
			$operation['message']=$vis_language['MSGDEPTMISS'];
			echo json_encode( array('vis_error_msg' => $operation['message']) );
			return false;
		}
        if(VIS_LOCATION_AREA == 1 && isset($data['vis_firstname']) && $data['vis_firstname']=='') {
			$operation['message']=$vis_language['MSGFNAMEMISS'];
			echo json_encode( array('vis_error_msg' => $operation['message']) );
			return false;
		}		
		if((isset($data['vis_email']) || trim($data['vis_email'])!='')&& !isset($data['vis_custom_form']))
		{
			list($message, $flag) = check_email_validation($data['vis_email']);
			if(!$flag) {
				 $operation['message']=$message;
                echo json_encode( array('vis_error_msg' => $operation['message']) );
                return false;
			} 
		}
		// ==================== Validation for asset name at client side starts ==========================
        if(VIS_LOCATION_AREA == 1 && isset($data['vis_ci_type']) && $data['vis_ci_type']!=''){
			// Validation for asset name at client side
			if(VIS_LOCATION_AREA == 1 && (isset($data['vis_cilist_visible']) && $data['vis_cilist_visible']==1) && (isset($data['vis_ci_attach']) && $data['vis_ci_attach']=='-1')) {
				$operation['message']=$vis_language['TXTCISELECT'];
				echo json_encode( array('vis_error_msg' => $operation['message']) );
				return false;
			}
		}
		// ==================== Validation for asset name at client side ends ============================
		
		if(VIS_LOCATION_AREA == 1 && isset($data['vis_subject']) && $data['vis_subject']=='') {
			$operation['message']=$vis_language['MSGSUBJECTMISS'];
			echo json_encode( array('vis_error_msg' => $operation['message']) );
			return false;
		}
		if(VIS_LOCATION_AREA == 1 && isset($data['vis_custom_form']) && $data['vis_custom_form']==1){
			
			if($data['vis_form_type']==1 && IS_LOGIN !=1){ //email
				if(isset($data['vis_email']) || trim($data['vis_email'])!='')
				 {
					list($message, $flag) = check_email_validation($data['vis_email']);
					if(!$flag) {
						 $operation['message']=$message;
						echo json_encode( array('vis_error_msg' => $operation['message']) );
						return false;
					} 
				 }
			} 
			if( $data['vis_form_type']==0 && IS_LOGIN !=1){//call
				if($data['vis_contact_number']=='') {
					$operation['message']=$vis_language['MSGCONTACTNO'];
					echo json_encode( array('vis_error_msg' => $operation['message']) );
					return false;
			   }else if(!is_numeric($data['vis_contact_number'])){
				   $operation['message']=$vis_language['TXTCONTXTNUMERIC'];
					echo json_encode( array('vis_error_msg' => $operation['message']) );
					return false;
			   }else if(strlen($data['vis_contact_number'])>20){
				   $operation['message']=$vis_language['TXTMAXCONTACT'];
					echo json_encode( array('vis_error_msg' => $operation['message']) );
					return false;
			   }				
			}
			
			
			
			//validation messages for custom forms
			if($validate_form_data!=1 && $validate_form_data[0]==0){ 
			if(isset($validate_form_data[1])){$operation['message']=$vis_language['MSGINFOMISS'].' ('.$validate_form_data[1].')';
            $operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].' ('.$validate_form_data[1].')'.'</div>';
            echo json_encode( array('vis_error_msg' => $operation['vis_message']) );
            return false; }
			}
		}
        if(VIS_LOCATION_AREA == 1 && isset($data['vis_ticket_post']) && $data['vis_ticket_post']==''&&$data['vis_custom_form']!=1) {
			$operation['message']=$vis_language['MSGPOSTMESSAGENOTFOUND'];
			echo json_encode( array('vis_error_msg' => $operation['message']) );
			return false;
		}
		if(VIS_LOCATION_AREA == 1 && (isset($data['captchacode']) && ((trim($data['captchacode'])!=strtoupper($_SESSION['random_number'])) && (trim($data['captchacode'])!=$_SESSION['random_number'])))) {
			$operation['message']=$vis_language['MSGIMGVERIFY'];
			echo json_encode( array('vis_error_msg' => $operation['message']) );
			return false;
		}		
		if(VIS_LOCATION_AREA == 2 && (isset($data['vis_service_email']) || trim($data['vis_service_email'])!='') && $data['vis_channel']==7)
		 {
			list($message, $flag) = check_email_validation($data['vis_service_email']);
			if(!$flag) {
				echo '<script> $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
				return false;
			} 
		 }
		if(VIS_LOCATION_AREA == 2 && !isset($data['vis_service_item_id']) && $data['vis_channel']==7) {
            echo '<script> $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQFLDCATEGORY'].'"); </script>';
		    return false;
        }
		
		##Asterisk
		if(VIS_LOCATION_AREA == 2){
			if($data['vis_channel']==22 || $data['vis_channel']==23){
				if((isset($data['vis_new_ticket_list_client']) || trim($data['vis_new_ticket_list_client'])!='') && !is_numeric($data['vis_new_ticket_list_client']))
				 {  
					list($message, $flag) = check_email_validation($data['vis_new_ticket_list_client']);
					if(!$flag) {
						 $operation['message']=$message;
						 echo '<script> $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$operation['message'].'"); </script>';
						return false;
					} 
				 }
			}			
		}		
		###Asterisk		
	
		if(isset($data['vis_service_quantity']) && (!is_numeric($data['vis_service_quantity']) || $data['vis_service_quantity']=='') && $data['vis_channel']==7) {
			if(VIS_LOCATION_AREA==1){
				$operation['message']=$vis_language['MSGREQFLDQUANTITYMUSTBENUM'];
				echo json_encode( array('vis_error_msg' => $operation['message']) );
			}else{
            	echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQFLDQUANTITYMUSTBENUM'].'"); </script>';
			}
		    return false;
        }
        if((VIS_LOCATION_AREA==1 || VIS_LOCATION_AREA==0 )&& !$data['vis_internal_ticket']) {
            $newlyaddedclient=0;
            if(!isset($data['vis_client']) || !is_numeric($data['vis_client'])) {   
				list($message, $flag) = check_email_validation($data['vis_email']);           
				if(!$flag && !isset($data['vis_custom_form'])) {
						$operation['message']=$vis_language['MSGEMAILMISS'];
                     echo json_encode( array('vis_error_msg' => $operation['message']) );
                     return false;
				} 
                elseif(isset($data['vis_captcha_code']) && ((trim($data['captchacode'])!=strtoupper($_SESSION['random_number'])) && (trim($data['captchacode'])!=$_SESSION['random_number']))) {
                    $operation['message']=$vis_language['MSGIMGVERIFY'];
                    echo json_encode( array('vis_error_msg' => $operation['message']) );
                    return false;
                }
                else {
																	$emilclientticket_res=$client_obj->get_check_additionalemailclient('additional_email="'.$data['vis_email'].'"  and '.VIS_TABLE_PREFIX.'client.domain_id='.$vis_domain,' limit 0,1',VIS_CLIENT_ID, VIS_LOCATION_AREA);
																	if($emilclientticket_res!=-1)
																	{
																		$client=$emilclientticket_res;
																	}else{
																		   if($data['vis_custom_form']==1 && $data['vis_form_type']==0){
																			   $filter = 'contact_number="'.$data['vis_contact_number'].'" and '.VIS_TABLE_PREFIX.'client.domain_id='.$vis_domain;
																		   }else{
																			   $filter = 'email="'.$data['vis_email'].'" and '.VIS_TABLE_PREFIX.'client.domain_id='.$vis_domain;
																		   }
																		
                   list($clinfo, $client)=$client_obj->get_client($filter, '', 0, '', VIS_DOMAIN, VIS_LOCATION_AREA);
																	}
                    if($client==-1) {
                        $data['vis_is_approved']=1;
                        $val=$client_obj->get_setting('module_id=3 and title="vis_approval" and domain_id='.$data['vis_domain'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                        if(isset($val['content']) && $val['content']==0) $data['vis_is_approved']=0;
                        $is_approved=$data['vis_is_approved'];
                        $department=$departments=$ticket_object->get_department('department_id='.$data['vis_department'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                        if($department[0]['registration']==1) {
                            $operation['message']=$vis_language['TXTREGISTRATIONREQUIRED'];
                            if(VIS_LOCATION_AREA==0) echo $operation['message'];
                            else echo json_encode( array('vis_error_msg' => $operation['message']) );
                            return false;
                        }
                        
                        $data['vis_client']=$client_obj->add_client($data, VIS_DOMAIN, VIS_LOCATION_AREA);
                        if(!$data['vis_client']) {
                            $operation['message']=$vis_language['MSGERROPRT'];
                            if(VIS_LOCATION_AREA==0) echo $operation['message'];
                            else echo json_encode( array('vis_error_msg' => $operation['message']) );
                            return false;
                        }
                        $newlyaddedclient=1;
                        $userid=$data['vis_client'];
                        $data['is_approved']=$data['vis_is_approved'];
                        $data['vis_from_name']=$data['vis_firstname'].' '.$data['vis_lastname'];
                        $data['vis_from_email']=$data['vis_email'];
						
						if(isset($data['vis_from']) && $data['vis_from']!="")
						{
							$stringtoget=$data['vis_from'];
						   	list($first) = explode("<", $stringtoget);
							if(empty($data['vis_from_name']))
							{   
							  $data['vis_from_name'] =$first;
							}
 						}
						$data['receiver_to']=$data['vis_email'];
						
                        $data['vis_module']='client';
                        $data['vis_operation']='add_client';
                        $data['vis_client_id']=$data['vis_client'];
                        $operation_hnd->operation_flow($data, $userid, VIS_LOCATION_AREA, $database);
                        $operation_hnd->check_automation($data, $database);
			        }
                    else {
                        $userid=$data['vis_client']=$client[0]['client_id'];
                        $data['vis_from_name']=$client[0]['first_name'].' '.$client[0]['last_name'];
                        $data['vis_from_email']=$client[0]['email'];
                        $is_approved=$data['is_approved']=$client[0]['is_approved'];
                        $is_banned=$client[0]['is_banned'];
                        if($client[0]['parent_id']!=0) {
                            $subdetails=$client_obj->get_subclient_setting($client[0]['client_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
                            if($subdetails[3]==0) $is_banned=1;
                        }
                    }
                    $data['vis_client_email']=$data['vis_email'];
                }
            }
            else {
                $userid=$data['vis_client'];
                list($clinfo, $client)=$client_obj->get_client('client_id='.$data['vis_client'], '', 0, '', $data['vis_client'], VIS_LOCATION_AREA);
                $is_banned=$client[0]['is_banned'];
            }
        }	
        if(VIS_LOCATION_AREA==1 && (($is_approved==0 && $newlyaddedclient==1) || $is_banned==1)) {
            $operation['message']=($is_approved==0)?$vis_language['MSGAPPROVEPENDING']:$vis_language['MSGACCSSDND'];
            if(VIS_LOCATION_AREA==0) echo $operation['message'];
            else echo json_encode( array('vis_error_msg' => $operation['message']) );
            return false;
        }
        if(VIS_LOCATION_AREA==1 || VIS_LOCATION_AREA==3) {
		   if(defined('VIS_HEAD_MENU_HTML_EDITOR') && VIS_HEAD_MENU_HTML_EDITOR==0)
		   $data['vis_ticket_post'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_ticket_post']);
        }
        if(VIS_LOCATION_AREA==0 || (VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) || VIS_LOCATION_AREA==3) {
            if($data['vis_channel']==4) {
                $tweet=unserialize(base64_decode($data['vis_tweet_details']));
                $data['last_replier_id']=$tweet->id_str;
            }
            if((defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR==0) || VIS_LOCATION_AREA==0)
            $data['vis_ticket_post'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_ticket_post']);
            $data['vis_comment'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_comment']);
            $char=substr(trim($data['vis_new_ticket_list_client']), -1);
			if($char==',')
			{
				$data['vis_new_ticket_list_client']=substr(trim($data['vis_new_ticket_list_client']), 0, -1);
			}
			if(strpos($data['vis_new_ticket_list_client'],','))
			{
				$email=explode(',', $data['vis_new_ticket_list_client']);
			}
			else $email[0]= $data['vis_new_ticket_list_client'];
		    if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) && !$data['vis_internal_ticket'] && (($data['vis_channel']==1 || $data['vis_channel']==5 || $data['vis_channel']==7) ||($data['vis_channel']!=1 && $data['vis_new_ticket_list_client']==''))) {
				 foreach($email as $key=>$val)
				{
					if(isset($val) || trim($val)!='')
					 {
						list($message, $flag) = check_email_validation($val);
						if(!$flag) {
							if(VIS_LOCATION_AREA == 2 && ($data['vis_channel']!=2 || $data['vis_channel']!=19 )) {
								echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGEMAILMISS'].'"); </script>';
								return false;
							} 
							elseif(VIS_LOCATION_AREA==3) {
								$operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGEMAILMISS'].'</div>';
								return $this->new_ticket_step_one($operation);
							}
							elseif(VIS_LOCATION_AREA==0) {
								echo $vis_language['MSGEMAILMISS'];
								return false;
							}
						}
						
					 }				
                }
            }	
            else if($data['vis_channel']==2 || $data['vis_channel']==19)
            { 
				 foreach($email as $key=>$val)
				{
					if(isset($val) || trim($val)!='')
					 { 
						list($message, $flag) = check_email_validation($val);
						if($flag == 1) {
							
							echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCONTACTNOINVALIDEORMISSING'].'"); </script>';
                            return false;
						}
					}
				}
			}
            else if(VIS_LOCATION_AREA == 2 &&  !$data['vis_internal_ticket'] && ($data['vis_channel']!=1 && $data['vis_channel']!=5 && $data['vis_channel']!=7 && $data['vis_channel']!=2 && $data['vis_channel']!=19 ) && $data['vis_new_ticket_list_client']!='') { 
 foreach($email as $key=>$val)
				{ 
					
					if(isset($val) || trim($val)!='')
					 {
						
						list($message, $flag) =  check_email_validation($val);
							if($flag==1){
									$client_detail['vis_email']=$data['vis_new_ticket_list_client'];
								}
								else {
									$blankEmailCheck = 1;
									$additionalChannelVariables=array();
									if($data['vis_channel']==3){
										$client_detail['vis_facebook_id'] =$data['vis_new_ticket_list_client'];
										$client_detail['vis_username'] = $data['vis_new_ticket_list_client'];
										$additionalChannelVariables['vis_facebook_id'] = $client_detail['vis_facebook_id'];
										$additionalChannelVariables['vis_username'] = $client_detail['vis_username'];
									}
							        else { 
										$client_detail['vis_username'] = $data['vis_new_ticket_list_client'];
										$additionalChannelVariables['vis_username'] = $client_detail['vis_username'];
								    }
								}
                        }
					}
				}
				
                //{
                    if($data['vis_channel']==4) { $temp	= $data['vis_client'];
                        $data['reply_to']=$tweet->id_str;
                        $filterCondition = (VIS_LOCATION_AREA==2)?'or user_name="'.$data['vis_new_ticket_list_client'].'"':'';
                        list($client_i, $client_d)=$client_obj->get_client('(email="'.$data['vis_new_ticket_list_client'].'" '.$filterCondition.' or twitter_id="'.$data['vis_new_ticket_list_client'].'") and '.VIS_TABLE_PREFIX.'client.domain_id='.$data['vis_domain'].'', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
                        if($client_d!=-1) $data['vis_client']=$client_d[0]['client_id'];
                        else {
                            $client_detail=array('vis_domain'=>VIS_DOMAIN);
                            if(isset($data['vis_tweet_details']) && $data['vis_tweet_details']!='') {
                                $client_detail['vis_email']='@'.$tweet->user->screen_name;
                                $client_detail['vis_username']='@'.$tweet->user->screen_name;
                                $client_detail['vis_firstname']=$tweet->user->name;
                                $client_detail['vis_domain']=$data['vis_domain'];
                            }
                            if(strpos($data['vis_new_ticket_list_client'], '@')===0) $client_detail['vis_twitter_id']=$data['vis_new_ticket_list_client'];
                            else
                            {
								list($message, $flag) = check_email_validation($data['vis_new_ticket_list_client']);
								if($flag){
									$client_detail['vis_email']=$data['vis_new_ticket_list_client'];
								}
								else $client_detail['vis_twitter_id']=$data['vis_new_ticket_list_client'];
							}

                            if(defined('VIS_ADD_CLIENT_ACCESS') && VIS_ADD_CLIENT_ACCESS==0) {
                                echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' ('.$vis_language['MSGACCSSDND'].').'.'"); </script>';
                                return false;
                            }
                            $client_detail['vis_channel'] = $data['vis_channel'];
                            $data['vis_client']=$client_obj->add_client($client_detail, VIS_STAFF_ID, VIS_LOCATION_AREA);
                        } if(($data['vis_client']=='' || $data['vis_client']== 0) && $data['vis_ticket_schedule_ref_id']!=0){ $data['vis_client']=$temp; }
                    }
                    else {               					
                        if($data['vis_new_ticket_list_client']!='') 
										$emilclient_res=$client_obj->get_check_additionalemailclient('additional_email="'.$data['vis_new_ticket_list_client'].'"  and '.VIS_TABLE_PREFIX.'client.domain_id='.$vis_domain,' limit 0,1',VIS_CLIENT_ID, VIS_LOCATION_AREA);
																	if($emilclient_res!=-1)
																	{
																		$client_d=$emilclient_res;
																	}else{
																		
                   $filterCon = (($data['vis_channel'] == 2 || $data['vis_channel'] == 19) && $isCallClientEmailvalid != 1 )?'contact_number="'.$data['vis_new_ticket_list_client'].'"':'( email="'.$data['vis_new_ticket_list_client'].'" or user_name="'.$data['vis_new_ticket_list_client'].'")';
                   
                   list($client_i, $client_d)=$client_obj->get_client($filterCon.' and '.VIS_TABLE_PREFIX.'client.domain_id='.$vis_domain, '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			   }
										  
                        if($client_d!=-1 && is_array($client_d)) {
							$data['vis_client'] = $client_d[0]['client_id'];
							if(isset($data['vis_as_client']) && $data['vis_as_client']==1) {
								$data['vis_from_name'] = $client_d[0]['first_name']." ".$client_d[0]['last_name'];
							}
						}
                        else {										
                            if(defined('VIS_ADD_CLIENT_ACCESS') && VIS_ADD_CLIENT_ACCESS==0 && $data['vis_internal_ticket']!=1) {
                                echo '<script> $("#btn_add_ticket").removeAttr("disabled");  $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTCNTCLIENTAD'].'"); </script>';
                                return false;
                            }
                            if((isset($data['vis_internal_ticket']) && $data['vis_internal_ticket']!=1) || (isset($operation['ticket_id']) && $operation['ticket_id']!='')){ 
								$additionalChannelVariables =(isset($additionalChannelVariables))?$additionalChannelVariables:array();
								$data['vis_client']=$client_obj->add_client(array_merge(array('vis_email'=>($blankEmailCheck!=1)?$data['vis_new_ticket_list_client']:"", 'vis_domain'=>$data['vis_domain'],'vis_channel'=>$data['vis_channel']),$additionalChannelVariables), VIS_STAFF_ID, VIS_LOCATION_AREA); }
                        }
                    }
                //}
        if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4))
		{
			$char=substr(trim($data['vis_people']), -1);
			if($char==',')
			{
				$data['vis_people']=substr(trim($data['vis_people']), 0, -1);
			}
			if(strpos($data['vis_people'],','))
			{
				$email=explode(',', $data['vis_people']);
			}
			else $email[0]= $data['vis_people'];
			 foreach($email as $key=>$val)
			{
				if(isset($val) && trim($val)!='')
				 {
					list($message, $flag) = check_email_validation($val);
					if(!$flag) {
						if(VIS_LOCATION_AREA == 2 && !$data['vis_internal_ticket'] && ($data['vis_channel']==1 || ($data['vis_channel']!=1))) {
						echo '<script> $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGEMAILMISS'].'"); </script>';
						return false;
					   }
					} 
				 }	
			}
		}
        if((!isset($data['vis_ticket_post']) || trim(strip_tags($data['vis_ticket_post'],"<img>")) == '')) {
            if(VIS_LOCATION_AREA == 2 ) {
                echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGPOSTMESSAGENOTFOUND'].'"); </script>';
                return false;
            }
            elseif(VIS_LOCATION_AREA==3) {
                $operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGPOSTMESSAGENOTFOUND'].'</div>';
                return $this->new_ticket_step_one($operation);
            }
        }
            if(VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA==0 || VIS_LOCATION_AREA==3 ) {
                if(!isset($data['vis_from'])) {
					if(VIS_LOCATION_AREA==0 ) echo $vis_language['MSGSNDRMISS'];
                    else echo '<script> $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNDRMISS'].'"); </script>';
                    return false;
                }
                else if(!isset($data['vis_as_client'])) { 
                    if(preg_match("/^(.*)<(.*)@(.*)>/", $data['vis_from'], $match)) {
                        $data['vis_from_name']=trim($match[1], "\x22\x27 \t\"\\\'\;\>\<");
                        $data['vis_from_email']=trim($match[2], "\x22\x27 \t\"\\\'\;").'@'.trim($match[3], "\x22\x27 \t\"\\\'\;");
                    }
                    else {
                        $data['vis_from_name']=trim($addr, "\x22\x27 \t\"\\\'\;");
                    }
                    
                }
                else 
                {
					if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) || VIS_LOCATION_AREA==3) $data['vis_from_email']=$data['vis_new_ticket_list_client'];
                    else $data['vis_from_email']=$client[0]['email'];
				}
                if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) && (!isset($data['vis_client_email']) || $data['vis_client_email']=='') && isset($data['vis_new_ticket_list_client'])) $data['vis_client_email']=$data['vis_new_ticket_list_client'];
                elseif(VIS_LOCATION_AREA==0){ //$data['vis_client_email']=$client[0]['email'];
					if(!empty($client[0]['email']))
					{
						$data['vis_client_email']=$client[0]['email'];
					}
					else
					{
						$data['vis_client_email']=$data['vis_email'];
					}
				}
				$userid=VIS_STAFF_ID;
            }
            
            $data['vis_draft']=(isset($operation['vis_draft']) && $operation['vis_draft']==1)?1:0;
			if(($data['vis_draft']==1 && $data['vis_schedule_ticket'] ==1)) {
                include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
                $staff=new class_staff($database);
                $staff_info=$staff->get_staff('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
				if(!isset($data['vis_as_client'])) {
					$data['vis_from_name'] = trim($staff_info[0]['first_name'].' '.$staff_info[0]['last_name'], ' "-');
					$data['vis_from_email'] = $staff_info[0]['email'];
					$data['vis_from_email']; 
				}
            }		
        }
		
		## ticket schedule validation
		if(isset($data['vis_schedule_ticket']) && VIS_LOCATION_AREA == 2 && $data['vis_schedule_ticket'] ==1){
			 if($data['vis_schedule_start_date']==''){
			 	 echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTPLEASESELECTTODATE'].'"); </script>';
		    	 return false;
			 }  
			 if(trim(strtotime($data['vis_schedule_start_date'])) < trim(strtotime(date('M-jS, Y G:i')))){
			 	 /*echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSCHEDULEDATE'].'"); </script>';*/
		    	 //return false;
			 }
			 if($data['vis_set_schedule'] == 1 && ($data['vis_daily1']=='' && $data['vis_daily2']== '' && $data['vis_daily3']== '' && $data['vis_daily4']== '' && $data['vis_daily5']=='' && $data['vis_daily6']=='' && $data['vis_daily7']== '')){
			 	echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQUIREDAY'].'"); </script>';
		    	 return false;
			 }
			 if($data['vis_set_schedule']!=0){
			 	 if(trim(strtotime($data['vis_schedule_start_date'])) > trim(strtotime($data['vis_schedule_end_date']))){
					 echo '<script>  $("#btn_add_ticket").removeAttr("disabled"); $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSCHEDULEENDDATE'].'"); </script>';
					 return false;
			 	}
				 /*if($data['vis_set_schedule']==2	&& (trim(strtotime($data['vis_schedule_start_date']."+7 days")) > trim(strtotime($data['vis_schedule_end_date'])))){
				 	 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSCHEDULEWEEKLYENDDATE'].'"); </script>';
					 return false;
				 }
				 if($data['vis_set_schedule']==3	&& (trim(strtotime($data['vis_schedule_start_date']."+30 days")) > trim(strtotime($data['vis_schedule_end_date'])))){
				 	 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSCHEDULEMONTHLYENDDATE'].'"); </script>';
					 return false;
				 }*/
			 	
			 }
		}
	
        $data['received_via']=0;
		if(VIS_LOCATION_AREA == 1 || (VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4)){
			$data['received_via']=1;
			if(VIS_LOCATION_AREA == 1){ // if client portal, store dept name for 'To' field
				$dept=$ticket_object->get_department('department_id='.$data['vis_department'], $userid, VIS_LOCATION_AREA);
				$data['vis_to_email']=$dept[0]['department_name'];
				$data['vis_channel'] = $data['vis_channel'];
			}		
		} 
		if(((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) || VIS_LOCATION_AREA==0) && isset($data['vis_internal_ticket']) && $data['vis_internal_ticket']==1 && !isset($data['vis_as_client'])) {
			$data['vis_from_email']=$staff_info[0]['email'];
		}
		if(VIS_LOCATION_AREA==0) { $data['received_via']=3; }		
		#sub-contact mail setting
		if(VIS_LOCATION_AREA==1){
			$subdetails=$client_obj->get_subclient_setting($client[0]['client_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
			$sc_parent_id = $client[0]['client_id'];
			
			$sc_cc ='';
			if($client[0]['parent_id']!=0) {	
				$sc_parent_id = $client[0]['parent_id'];
				list($pclinfo, $parent_client)=$client_obj->get_client('client_id='.$client[0]['parent_id'], '', 0, '', $client[0]['client_id'], VIS_LOCATION_AREA);
				
				if($subdetails[6]==1){ 
					//Parent client should receive a copy of emails submitted by this contact
					$sc_cc =	trim($parent_client[0]['email']);						
				}				
			}
			//Receive a copy of emails submitted by parent client and other contacts
			//for seting id 7
			$sub_contatct_emaillist = $client_obj->get_subcontact_email("AND ct.parent_id =".$sc_parent_id." AND ct.client_id!=".$client[0]['client_id']);
			
			if($sub_contatct_emaillist!=-1){
				for($sc=0;$sc<count($sub_contatct_emaillist);$sc++){
					$sc_cc .= ','.trim($sub_contatct_emaillist[$sc]['email']);
				}
			}
			$data['sub_contact_cc'] = trim($sc_cc,',');			
		}
		$ret=$ticket_object->add_ticket($data, $userid, VIS_LOCATION_AREA); 
		
		if($ret){
			$ticket_id = $data['ret'] = $ret;
			$assets_id=$data['vis_assets'];
			$data['vis_parent_id']=$ticket_id;
			$data['vis_child_id']=$assets_id;
			 $data['vis_attach_type']=0;
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
				$problem_object=new class_problem($database);
			if($assets_id!='0' && !empty($assets_id))	
			{			
			$ret_assets=$problem_object->add_itil_relation($data,VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
			
		}
		##Post redmine data	
		if($ret){
			$ticket_id = $data['ret'] = $ret;
			$query	=	"SELECT `domain_url` FROM `".VIS_TABLE_PREFIX."domain` WHERE  `domain_id` = ".VIS_DOMAIN;	
			$result=$database->query_exec($query);
			$dom_result = $database->fetch_result_array($result);			
			$query	=	"SELECT  `ticket_hash` FROM `".VIS_TABLE_PREFIX."ticket` WHERE  `ticket_id` = ".$ticket_id;	
			$result=$database->query_exec($query);
			$ticket_result = $database->fetch_result_array($result);
			$helpdesk_url = $dom_result[0]['domain_url']."manage/#/ticket/ticket_details/".$ticket_result[0]['ticket_hash']."/".$ticket_id;
			$setting_object=new class_setting($database);			
			$post_data = $data['vis_ticket_post'];
			$post_data = $post_data."<br/>Helpdesk Url:<br/><a href='".$helpdesk_url."' target='_blank' >".$helpdesk_url."</a>";
			$post_data = str_replace("</p>","\n",$post_data);
			$post_data = str_replace("<br>","\n",$post_data);
			$post_data = str_replace("<br/>","\n",$post_data);
			$post_data= strip_tags($post_data);
			
			##atachment
			$query	=	"SELECT `post_id` FROM `".VIS_TABLE_PREFIX."ticket_post` WHERE  `ticket_id` =".$ticket_id;		
			$result=$database->query_exec($query);
			$post_result = $database->fetch_result_array($result);
			for($i=(count($post_result)-1);$i>=0;$i--){
				$parent_id[] =  $post_result[$i]['post_id'];
			}
			$query	=	"SELECT * FROM `avis_attachment` WHERE `parent_id` IN (".implode(',',$parent_id).")";				
			//$query	=	"SELECT * FROM `avis_attachment` WHERE `attachment_id` IN (".$data['vis_attachments']."0)";	
			$result=$database->query_exec($query);
			$att_result = $database->fetch_result_array($result);
			$attchmentFiles = array();
			$customeFields	= array();
			## uncomment following $customeFields for testing purpose on ocr-inc's redmine setup						
			/*$customeFields	= array(
									array('id' => 43, 'name' => 'Client issue/Ref #', 'value' => '' ),
									array('id' => 2, 'name' => 'Primary Mod/Ref #', 'value' => 'HelpDesk'),
									array('id' => 26, 'name' => 'Rel Notes Reqd/Ref #', 'value' => 'Yes' ),
									array('id' => 54, 'name' => 'Issue in/Ref #', 'value' => 'CLIENT' ),	
									array('id' => 32, 'name' => 'Client Name', 'value' => 'HelpDesk'),
							   ); */
			if($att_result!=-1){
				for($a=0;$a<count($att_result);$a++){
					$filecontent = file_get_contents(VIS_PATH_FILES.$att_result[$a]['content']);			
					$upload = $setting_object->get_redmine('uploadFileToIssue',$filecontent);
					$file_type	=	explode('/',$att_result[$a]['file_type']);
					$attchmentFiles[]	=	array(
												  'token' => $upload->upload->token,
												  'filename' => $att_result[$a]['file_name'],
												  'content_type' => 'application/'.$file_type[0],									  										  
												);			
				}	
			}
			$issue_data	=	array('issue'=>array(
											'project_id' => $data['vis_project'],
											'subject' => $data['vis_subject'],
											'description' => $post_data,
											'uploads' => $attchmentFiles,
											'custom_fields' => $customeFields,	
										),); //'tracker_id'=> $data['vis_tracker'],							
			if($data['vis_redmine']==1){				
				$createIssue	=	$setting_object->get_redmine('createIssue',$issue_data);
				$ins_issue_id	=	$createIssue['issue']['id']; 
				$data['vis_issue'] = $ins_issue_id;				
				## Link issue with redmine
				if(isset($data['vis_issue']) && $data['vis_issue'] !=''){ 
					$ticket_object->link_redmine_issue($data,$ins_issue_id); 
				}
			}			
		 }
		##Post redmine data	
		
		##Vtiger
			if($ret){
				if($data['vis_vtiger']==1){
					$this->vt_create_ticket($data);
				}
			}
		###Vtiger
			$operation['vis_cronschedule_flag']=(isset($operation['vis_cronschedule_flag']) && $operation['vis_cronschedule_flag']==1)?$operation['vis_cronschedule_flag']:0;
        $data=array_merge($data, $operation);
	    if($ret) {
			/*if($data['vis_channel']==7 && VIS_LOCATION_AREA!=1)
				echo '<script type="application/javascript">$(".modal").modal("toggle");</script>';*/

            $data['vis_ticket_id']=$ret;
            $data['ticket_id']=$ret;
        }
        else $data['vis_ticket_id']=0;
        if($ret && $data['vis_draft']==0 && (VIS_LOCATION_AREA==0 || VIS_LOCATION_AREA==1 || (VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4) || VIS_LOCATION_AREA==3)) {
            global $operation_hnd;
            $data['vis_is_client']=(isset($data['vis_as_client']))?1:0;
			$operation_hnd->check_automation($data, $database);
		    $data['vis_module']='ticket';
            $data['vis_operation']='open_new_ticket';
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
			$staff=new class_staff($database);								
												if($operation['vis_cronschedule_flag']!=1){
            $operation_hnd->operation_flow($data, $userid, VIS_LOCATION_AREA, $database);
            $staff->apply_roundrobin($data, $userid, VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($data, $userid, VIS_LOCATION_AREA, $database);

			 // send iOS notification 
		 $data=parse_form_array($operation['vis_action']);
		 $access = $data['vis_department'];
		 $this->send_notification($ticket_id,1,$access); 
												}
	    }
		if(VIS_LOCATION_AREA != 4){
      	 $database->database_disconnect();
		}
        if(VIS_LOCATION_AREA == 2) {
            if(!$ret) {
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].(($ticket_object->error=='NO_CREDIT')?(' ('.$vis_language['MSGBALMISS'].')'):'').'"); </script>';
                return false;
            }
            else{
				$response = '';
				$ticketData = parse_form_array($operation['vis_action']);
				$fid=($data['vis_draft']==1)?7:1;
				$fid=($data['vis_draft']==1 && $data['vis_schedule_ticket']==1)?21:$fid;
                if((isset($operation['vis_draft']) && $operation['vis_draft']=='true') || isset($ticketData['vis_draft_id'])) $draft= ",'vis_draft':'1'";
				$response = '$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTTICKETS'].'",{"vis_module":"ticket", "vis_operation":"filter_ticket" , "vis_action":"#/ticket/filter_ticket/'.$vis_language['TXTTICKETS'].'/'.$fid.'"});';
			    $response .= '$("#vis_global_msg_div").visExecution("load_operations", {"vis_module":"staff", "vis_operation":"refresh_leftpanel"'.$draft.'});';
				echo '<script>'.$response.'</script>';
			}
        }
        elseif(VIS_LOCATION_AREA==1) {
            $operation['vis_status']='';
           
            if(IS_LOGIN==1) 
            {
				if(defined('IS_WHMCS'))
				{
					echo '<script>window.location = "supporttickets.php";</script>';
				}
				else
				{
					if(!$ret)
					echo json_encode( array('vis_error_msg' => ($ticket_object->error=='NO_CREDIT')?$vis_language['TXTINSUFFICIENTCREDIT']:$vis_language['MSGERROPRT']) ); 
					else
					echo json_encode( array('vis_submitted' => 'true', 'vis_msg' => $ticket_object->ticket_hash) ); 
				}
		    }
            else {
				echo json_encode( array('vis_submitted' => 'false', 'vis_msg' => $ticket_object->ticket_hash) );
                /*include(VIS_PATH_TEMPLATE.'header.php');
                echo $operation['message'];
                include(VIS_PATH_TEMPLATE.'footer.php');*/
            } //$this->new_ticket_step_one($operation);
        }
        elseif(VIS_LOCATION_AREA==3) {
            $operation['vis_message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
            return $this->filter_ticket($operation);
        }
        elseif(VIS_LOCATION_AREA==0) {
            echo (!$ret)?'error':'success';
            return $ret;
        }elseif(VIS_LOCATION_AREA==4) {
									if($operation['vis_cronschedule_flag']==1){
										return $data;
									}else{
          return $ret;
									}
        }
	    return true;
    }

	
     function upload_file($operation) { 
        global $vis_language; 
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $is_editor_image_upload = $operation['is_editor_image_upload'] = (isset($operation['vis_static_area']) && $operation['vis_static_area']=='editor_image_upload') ? 1 : 0;
        $vis_file_extension=pathinfo($_FILES['files']['name'][0], PATHINFO_EXTENSION);
        if($is_editor_image_upload || $operation['vis_static_area']=='editor_file_upload'){
			$file_data = array();	
			if(!empty($_FILES['files'])){		
				$file_data['files']['name'][] = $_FILES['files']['name'];
				$file_data['files']['tmp_name'][] = $_FILES['files']['tmp_name'];
				$file_data['files']['size'][] = $_FILES['files']['size'];
				$file_data['files']['type'][] = $_FILES['files']['type'];
				$vis_file_extension=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
			}
			else 
		    { 
				$file_data['files']['name'][] = $_FILES['file']['name'];
				$file_data['files']['tmp_name'][] = $_FILES['file']['tmp_name'];
				$file_data['files']['size'][] = $_FILES['file']['size'];
				$file_data['files']['type'][] = $_FILES['file']['type'];
				$vis_file_extension=pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
				$is_editor_image_upload = ($operation['vis_static_area']=='editor_file_upload')?1:0;
		    }
			$_FILES = $file_data;
		}
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
		if(VIS_LOCATION_AREA == 1)
		{
			//check ext
				$find_letters=array('.php','.php3','.php4','.phtml','.pl','.py','.jsp','.asp','.htm','.shtml','.sh','.cgi','.aspx','.exe');
				$flags = false;
				foreach ($find_letters as $letter){
							if(strpos(strtolower(trim($_FILES['files']['name'][0])), $letter) !== false){
											$flags = true;
											break;
							}
				}
				if($flags!==false)
				{
								if(VIS_LOCATION_AREA == 1) echo 1;  return false; //for extension 
				}
			//ext 	
			
			/* $file_info = getimagesize($_FILES['files']['tmp_name'][0]);
			  if(empty($file_info)) // No Image?
			  {
			  echo 1;  return false;
			  } */
			$extFilter =  'module_id=2 and domain_id='.VIS_DOMAIN;
			$extensionDetails =$setting_object->get_settings($extFilter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			for($i=0;$i<count($extensionDetails);$i++) $setting[$extensionDetails[$i]['title']]=$extensionDetails[$i]['content'];
			if(trim($setting['vis_extensions']) != '')
			{
				$exts=explode(',', $setting['vis_extensions']);
				$flag=false;
				for($j=0;$j<count($exts);$j++) 
				{
				   if(strtolower(trim($vis_file_extension)) == strtolower(trim($exts[$j]))) 
				   {
						 $flag=true;
						 break;
				   }
				  
				}
				if(!$flag)
				{
					   if(VIS_LOCATION_AREA == 1) echo 1;  return false; //for extension 
				}
			}
			if($setting['vis_maxsize'] != '' || $setting['vis_maxsize'] > 0)
			{
				$fileSize = $_FILES['files']['size'][0]/1024 ;
				if($fileSize > $setting['vis_maxsize'])
				{
					 if(VIS_LOCATION_AREA == 1) echo 2;  return false; // for file size
				}
			}
		}
		if(isset($operation['vis_import_attachments'])){
            if($vis_file_extension != 'csv'){
				echo 3;
                return false; 
            }
        }	
		$ret=$ticket_object->upload_file($_FILES, $operation, VIS_DOMAIN, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(!$ret) { 
			echo 4;
			return false; 
        }
        else if($is_editor_image_upload){
            list($cnt,$domain_details)=$setting_object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.VIS_DOMAIN, '', '', '', '', '',1);
            $domain_details=$domain_details[0];
            $filename=(VIS_LOCATION_AREA==2)?$domain_details['domain_url'].str_replace('../','',$ret[0]['attachment_content']):$domain_details['domain_url'].str_replace('./','',$ret[0]['attachment_content']);
            $database->database_disconnect();
            
			if (strstr($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
				$array = array('filelink' => $filename,
								'url'=>$filename,
                             	'name'=>$_FILES['files']['name']
                              );
	        }else{
	             $array = array('url' =>$filename,
		                        'name'=>$ret[0]['attachment_name']
	                           );
            }
            echo stripslashes(json_encode($array));

		}
        else {
            $message='';
            $attach='';
            $attach_area = $remove_attachment_arg = '';
            if(isset($operation['vis_fattachments'])) $attach_area = "vis_fattachments";
            if(isset($operation['vis_attachments'])) $attach_area = 'vis_attachments';
            if(isset($operation['vis_tasks_attachments'])) $attach_area = 'vis_tasks_attachments';
            if(isset($operation['vis_selfhelp_attachments'])) $attach_area = 'vis_selfhelp_attachments';           
            $imgCnt = $fileCnt = 0;
            for($i=0;$i<count($ret);$i++) {
                $remove_attachment_arg = $ret[$i]['attachment_id'];
                if($attach_area != '') $remove_attachment_arg  .= ',\"'.$attach_area.'\"';
                if($operation['vis_ticket_id'] != '' || $operation['vis_ticket_id'] != 0) $remove_attachment_arg  .= ','.$operation['vis_ticket_id'];
                $attach.=$ret[$i]['attachment_id'].',';
                if(isset($operation['parent_type']) && $operation['parent_type'] == 3)
                {
					
					echo "<script>var attachments=parent.$('#vis_attachment_count').val();parent.$('#vis_attachment_count').val(eval(parseInt(attachments)+1))</script>";
					if(strpos($_FILES['files']['type'][$i],'image')!== false)
					{
						if($imgCnt%4 == 0)
						{
							if($imgCnt != 0)
							{
								$message2.='</div>';
							}
							$message2.='<div class=\"row row-sm\">';
						}
						$message2.='<div class=\"col-xs-6 col-sm-4 col-md-3\"><button data-dismiss=\"alert\" class=\"close m-r-sm m-t-xs\" type=\"button\" onclick=\'$(this).parent().remove(); $(this).visExecution(\"load_operations\", {\"vis_module\":\"ticket\", \"vis_operation\":\"remove_attachment\", \"vis_attachment_id\":'.$ret[$i]['attachment_id'].'}); vis_remove_attachment('.$remove_attachment_arg.');\'><i class=\"vh vh-cross\"></i></button><div class=\"thumbnail\"><img src=\"'.VIS_PATH_FILES.$ret[$i]['attachment_content'].'\" class=\"bg-white img-responsive\" /></div></div>';	
						$imgCnt++;
					}
					else
					{
						if($fileCnt%3 == 0)
						{
							if($fileCnt != 0)
							{
								$message3.='</div>';
							}
							$message3.='<div class=\"row row-sm\">';
						}
						$message3.='<div class=\"btn-group wrapper-xxs\"><span class=\"btn btn-xs alert-success\">'.$ret[$i]['attachment_name'].'</span><button class=\"btn btn-xs alert-success\" type=\"button\" data-dismiss=\"alert\" onclick=\'$(this).parent().remove(); $(this).visExecution(\"load_operations\", {\"vis_module\":\"ticket\", \"vis_operation\":\"remove_attachment\", \"vis_attachment_id\":'.$ret[$i]['attachment_id'].'}); vis_remove_attachment('.$remove_attachment_arg.');\'><i class=\"vh vh-cross\"></i></button></div>';	
						$fileCnt++;
					}
				}
				else
				{
					if(VIS_LOCATION_AREA==1) {  $field_id = ($operation['vis_field_id']!='')?",".$operation['vis_field_id']:'';
					 $message.='<div class="btn-group wrapper-xxs"><span class="btn btn-xs alert-success">'.$ret[$i]['attachment_name'].'</span><button class="btn btn-xs alert-success" type="button" data-dismiss="alert" onclick=\'vis_remove_attachment('.$remove_attachment_arg.$field_id.');\'>&times;</button></div><script> $("#vis_attachments").append("'.$remove_attachment_arg.',"); </script>';	
					}else {
						$message.='<div class=\"btn-group wrapper-xxs\"><span class=\"btn btn-xs alert-success\">'.$ret[$i]['attachment_name'].'</span><button class=\"btn btn-xs alert-success\" type=\"button\" data-dismiss=\"alert\" onclick=\'$(this).parent().remove(); $(this).visExecution(\"load_operations\", {\"vis_module\":\"ticket\", \"vis_operation\":\"remove_attachment\", \"vis_attachment_id\":'.$ret[$i]['attachment_id'].'});vis_remove_attachment('.$remove_attachment_arg.');\'><i class=\"vh vh-cross\"></i></button></div>';
					}									
				}			
            }
            if(isset($operation['parent_type']) && $operation['parent_type'] == 3)
            {
				if($fileCnt != 0 && $fileCnt%3 != 0 )
				{
					$message3.='</div>';
				}
				if($imgCnt != 0 && $imgCnt%4 != 0 )
				{
					$message2.='</div>';
				}
				$message = $message3.$message2.$message1;
			}
            $database->database_disconnect();
            if(VIS_LOCATION_AREA==1) { 
				echo $message;
			}else {
				echo '<script>parent.$("#vis_global_msg_div").visExecution("load_file_message", {"vis_message":"'.$message.'", "vis_attachments":"'.$attach.'"});</script>'; 
				return true; 
			}
				return true;
        }        
    }

    function remove_attachment($operation) {
        global $vis_language;
        if(!isset($operation['vis_attachment_id']) || !is_numeric($operation['vis_attachment_id'])) { ?>
            <script> $("#vis_global_msg_div").visInterface("load_global_message", "<? echo $vis_language['MSGERROPRT']; ?>"); </script>'; <?
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->remove_file($operation['vis_attachment_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(!$ret) {?>
            <script> $("#vis_global_msg_div").visInterface("load_global_message", "<? echo $vis_language['MSGERROPRT']; ?>"); </script>'; <?
            return false;
        }
        else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "File removed successfully");</script>';
        return true;
    }

    function ticket_search($operation) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $ticket=new class_ticket($database);
        $client=new class_client($database);
        $setting=new class_setting($database);
        include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'client.php'); 
        $object_client = new client();
        if(isset($operation['vis_action'])){
            $action=explode('/', $operation['vis_action']);
            if(isset($action[4]) && trim($action[4])==6) $operation['show_report']=6;
        }
        $filters=$ticket->get_filters_details('vscope=1 and owner='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_types=$this->get_properties('get_types', '');
        $domain_list=$object_client->get_domain_access_list();
        $user_groups=$client->get_client_group(' (domain_id in ('.$domain_list.') or domain_id=0 ) and is_enable=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $domains=$ticket->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
        $departments=$ticket->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
        $status=$this->get_properties('get_status', '');
        $priorities=$this->get_properties('get_priorities', '');
        $flags=$this->get_properties('get_flags', '');
        $owner=$this->get_properties('get_staff', '');
        list($sinfo, $sla)=$setting->get_sla(VIS_TABLE_PREFIX.'sla.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $lang_dt=$setting->get_language('is_enabled=1', '', 0, '', 0, VIS_LOCATION_AREA);
        list($info, $client_language)=$lang_dt;
        $label_details=$this->get_properties('get_labels', ''); // label list 
        $channel_details=$this->get_properties('get_channel', '');
		
		$category_details=$this->get_properties('get_category', '');
		$subcategory_details=$this->get_properties('get_subcategory', '');
		$item_details=$this->get_properties('get_item', '');
		$level_details=$this->get_properties('get_level', '');
		$location_details=$this->get_properties('get_location', '');
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'search.php');
        return true;
    }
    function ticket_search_result($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        if(VIS_LOCATION_AREA==0) $data=$operation;
        else $data=parse_form_array($operation['vis_action']);
        $object=new class_ticket($database);
        if(isset($data['vis_report']) && $data['vis_report']==1){
            $from_date = strtotime($data['vis_from_date']);
            $to_date = strtotime($data['vis_to_date']);
           
			$datetime1 = new DateTime($data['vis_from_date']);
			$datetime2 = new DateTime($data['vis_to_date']);
			
			$dateDiff = get_timespan_difference($datetime1, $datetime2);
            
            if($from_date > $to_date){
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGFROMLESSTHANTO'].'"); </script>';
                return false;
            }else if($dateDiff['y']>0){
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGDURATIONLESSTHANTHREEMONTHS'].'"); </script>';
                return false;
            }elseif($dateDiff['m']>3){
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGDURATIONLESSTHANTHREEMONTHS'].'"); </script>';
                return false;
            }
            if($dateDiff['m']==3){
                    if($dateDiff['d']>0){
                        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGDURATIONLESSTHANTHREEMONTHS'].'"); </script>';
                        return false;
                    }	
			}
            
        }
        $filterid=$object->set_filter($data, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==0) {
            if(!$filterid) echo 'error';
            else {
                $operation['vis_filter_id']=$filterid;
                return $this->get_tickets($operation);
            }
        }
        else {
            if(!$filterid)
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            else
				echo '<script> $("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTTICKET'].'", {"vis_module":"ticket", "vis_operation":"filter_ticket", "vis_search":'.$operation['vis_search'].', "vis_filter_id":'.$filterid.((isset($data['vis_report']) && $data['vis_report']==1)?', "vis_report":1':'').'}); </script>';
        }
        return true;
    }

    function ticket_search_save($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        if(!isset($operation['vis_filter_title']) || $operation['vis_filter_title']=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGFLRTTTMISS'].'"); </script>';
            return false;
        }
        $data['vis_filter_title']= $operation['vis_filter_title'];
		$data['vis_is_report']= $operation['vis_is_report'];
		$is_report=$data['vis_is_report'];
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		
		$from_date = strtotime($data['vis_from_date']);
		$to_date = strtotime($data['vis_to_date']);
		$diff = abs($to_date - $from_date);
		$years = floor($diff / (365*60*60*24));
		$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
		$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
		
		if($from_date > $to_date){
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGFROMLESSTHANTO'].'"); </script>';
			return false;
		}else if($years>0){
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGDURATIONLESSTHANTHREEMONTHS'].'"); </script>';
			return false;
		}elseif($months>3){
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGDURATIONLESSTHANTHREEMONTHS'].'"); </script>';
			return false;
		}elseif($months<=3){
			if($months==3){
				if($days>0){
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGDURATIONLESSTHANTHREEMONTHS'].'"); </script>';
					return false;
				}	
			}
		}
		
        $filterid=$object->set_filter($data, 1, VIS_STAFF_ID, VIS_LOCATION_AREA);
								include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
						 $setting_object=new class_setting($database);		
								if($filterid){
								$search_details=$object->get_search_detail('F.filter_id='.$filterid, VIS_STAFF_ID, VIS_LOCATION_AREA);
									$search_details=$search_details[0];
									 if($search_details['vscope']==1){
												if($search_details['is_report']==1){$msg='Add custom report -'.$search_details['filter_name']; $moduleid=12;}else{ $msg='Add custom filter -'.$search_details['filter_name']; $moduleid=13;}
												$setting_object->add_staff_activity_log($msg,VIS_STAFF_ID,$moduleid, VIS_LOCATION_AREA);	
												}
								}
												$database->database_disconnect();
												
        if(!$filterid)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
								else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#global_menu").visExecution("load_area", {"vis_module":"home", "vis_operation":"load_global_menu"}); $("#vis_workpanel_div").visExecution(\'load_module\',\''.$vis_language['TXTSEARCHRESULT'].'\', {\'vis_module\':\'ticket\', \'vis_operation\':\'filter_ticket\', \'vis_filter_id\':\''.$filterid.'\'});$(".modal").modal("toggle"); </script>';
        return true;
    }
	function ticket_search_update($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        if(!isset($data['vis_filter_title']) || $data['vis_filter_title']=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGFLRTTTMISS'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $filterid=$object->update_filter($data, 1, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(!$filterid)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution(\'load_module\', \''.$vis_language['TXTFILTERS'].'\', {\'vis_module\':\'ticket\', \'vis_operation\':\'view_filters\'});$(".modal").modal("toggle"); </script>';
        return true;
    }
    function global_ticket_search($operation) {
        switch($operation['vis_search_area']) {
            case 0:
                $filter='ticket_hash="'.trim($operation['vis_search_text']).'"';
            break;
            case 1:
                $filter='subject like "%'.trim($operation['vis_search_text']).'%"';
            break;
            case 2:
                $filter='(first_name like "%'.trim($operation['vis_search_text']).'%" or last_name like "%'.trim($operation['vis_search_text']).'%")';
            break;
            case 3:
                $filter='email like "%'.trim($operation['vis_search_text']).'%"';
            break;
            default:
                $filter='';
            break;
        }
        $operation['view_title']='Search result';
        return $this->ticket_display($operation, '', '', $filter);
    }

    function quick_view($operation) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:'';
        $quick_view=$object->get_quick_counts($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_activities=$object->get_recent_audit('', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==2 || VIS_LOCATION_AREA==3) include(VIS_PATH_TEMPLATE.'ticket_quickview.php');
        elseif(VIS_LOCATION_AREA==0) echo get_xml(array('count'=>$quick_view, 'recent_log'=>$ticket_activities), 'quick_count');
        return true;
    }

    function get_label_data($operation){
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTLABELS'];
        $message_info['vis_opeartion']='apply_label';
        $message_info['vis_module']='ticket';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $label_details=$object->get_labels_list('', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_label=$object->get_ticket_labels($operation['vis_ticket_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include(VIS_PATH_TEMPLATE.'ticket_labels.php');

        return true;
    }

    function apply_label($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $result=$object->set_label($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($result){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_ticket_label_form").dialog("close"); $("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_action":"details", "vis_ticket_id":'.$data['vis_ticket_id'].'}); </script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); $("#vis_client_delete_form").dialog("close"); $(this).visInterface("remove_tab", "vis_module_client_div"); </script>';
        }
        return true;
    }

    function add_label($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        if(!isset($data['vis_newlabel']) || $data['vis_newlabel']=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);



        $result=$object->add_label($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($result){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");  $("#vis_label").append("<option value='.$result.'>'.$data['vis_newlabel'].'</option>"); </script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        }
        return true;
    }

    function get_tag_data($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTTAGS'];
        $message_info['vis_opeartion']='apply_tag';
        $message_info['vis_module']='ticket';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $label_details=$object->get_tag_list('', VIS_STAFF_ID, VIS_LOCATION_AREA);// 1st argument for filter
        $ticket_label=$object->get_ticket_tag($operation['vis_ticket_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include(VIS_PATH_TEMPLATE.'ticket_tags.php');
        return true;
    }

    function apply_tag($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $result=$object->set_tag($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($result){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_tag_apply_area").dialog("close"); $("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_action":"details", "vis_ticket_id":'.$data['vis_ticket_id'].'}); </script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        }
        return true;
    }

    function add_tag($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        if(trim($data['vis_newtag'])==''){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTAGNMMISS'].'");  </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $result=$object->add_tag($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($result){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_tag").append("<option value='.$result.'>'.$data['vis_newtag'].'</option>"); </script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        }
        return true;
    }

    function get_recipient_data($operation){
        $message_info['vis_form_title']='Recipients';
        $message_info['vis_opeartion']='update_recipient';
        $message_info['vis_module']='ticket';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
        list($ticket_info, $ticket_details)=$object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_details=$ticket_details[0];
        $database->database_disconnect();
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include(VIS_PATH_TEMPLATE.'ticket_recipient.php');
        return true;
    }

    function update_recipient($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $result=$object->set_recipient($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($result){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_client_recipient_form").dialog("close"); $("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_action":"details", "vis_ticket_id":'.$data['vis_ticket_id'].'}); </script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        }
        return true;
    }

    function get_sla_plan($operation){
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTCHANGESLA'];
        $message_info['vis_opeartion']='set_mass_sla';
        $message_info['vis_module']='ticket';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $sla_details=$object->get_sla_plan(VIS_STAFF_ID, VIS_LOCATION_AREA);
        //$ticket_label=$object->get_ticket_labels($operation['vis_ticket_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);        
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
        list($schedule_info, $schedule_details)=$setting_object->get_schedule('is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'ticket_sla.php');
        return true;
    }

    function set_mass_sla($operation) {
        global $vis_language, $operation_hnd;
        $data=parse_form_array($operation['vis_action']);
        $data=array_merge($data, $operation);
        $list_chk=array();
        if(isset($data['vis_ticket_id'])) {
            $property=$data['vis_action'];
            $ticket_id=explode(",",$data['vis_ticket_id']); 
            for($i=0; $i<count($ticket_id); $i++)
            {
				$list_chk[]=$ticket_id[$i];
			}
        }
        else {
            $property=$options['action'];
            $options=parse_form_array($operation['vis_action']);
            foreach($options as $key=>$value) if(preg_match('/vis_ticket_mass_chk_[0-9]/', $key)) $list_chk[]=$value;
        }
        $sla_id=$operation['vis_sla_id'];              
        if($sla_id==0 && (isset($data['vis_response_datepicker']) && $data['vis_response_datepicker']==1)) { 
            if($data['response_from_date'] == '') {
                 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");  </script>';
                 return false;
            }
        }     
        if($sla_id==0 && (!isset($data['vis_response_datepicker']) && $data['vis_response_datepicker']!=1)) { 
            if($sla_id==0 && (!is_numeric(trim($data['vis_due_time_days'])) && !is_numeric(trim($data['vis_due_time_hrs'])) && !is_numeric(trim($data['vis_due_time_mins'])) && !is_numeric(trim($data['vis_resolution_days'])) && !is_numeric(trim($data['vis_resolution_hrs'])) && !is_numeric(trim($data['vis_resolution_mins'])))){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");  </script>';
            return false;
            }
            if($sla_id==0 && ((is_numeric(trim($data['vis_due_time_days'])) && trim($data['vis_due_time_days'])<0) || (is_numeric(trim($data['vis_due_time_hrs'])) && trim($data['vis_due_time_hrs'])<0) || (is_numeric(trim($data['vis_due_time_mins'])) && trim($data['vis_due_time_mins'])<0) || (is_numeric(trim($data['vis_resolution_days'])) && trim($data['vis_resolution_days'])<0) || (is_numeric(trim($data['vis_resolution_hrs'])) && $data['vis_resolution_hrs']<0) || (is_numeric(trim($data['vis_resolution_mins'])) && trim($data['vis_resolution_mins'])<0))){
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTTIMESHOULDNOTNEGATIVE'].'");  </script>';
                return false;
            }
        }            
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        
		$cur_date = time();//date('Y-m-d H:i:s');
       /* $newdt = strtotime(' + '.trim($data['vis_due_time_days']).' days', $cur_date);
		$newdt = strtotime(' + '.trim($data['vis_due_time_hrs']).' hours', $newdt);
		$vis_due_time = strtotime(' + '.trim($data['vis_due_time_mins']).' minutes', $newdt);
		
		$newdt = strtotime(' + '.trim($data['vis_resolution_days']).' days', $cur_date);
		$newdt = strtotime(' + '.trim($data['vis_resolution_hrs']).' hours', $newdt);
		$vis_resolve_time = strtotime(' + '.trim($data['vis_resolution_mins']).' minutes', $newdt);*/
		
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
       $staff_object=new class_staff($database);
       $staff=$staff_object->get_staff_setting('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
       $staff=$staff[0];
		$c_datetime = get_time_by_tz(strtotime(date('M-jS, Y G:i'))); 
		$current_datetime = date('M-jS, Y G:i',$c_datetime); 
		$response_date  = date("M-jS, Y G:i", ($staff['timezone_dst']==1)?(strtotime($data['response_from_date'])+3600):strtotime($data['response_from_date'])); 
		$resolution_date  = date("M-jS, Y G:i", ($staff['timezone_dst']==1)?(strtotime($data['resolution_from_date'])+3600):strtotime($data['resolution_from_date']));                    
		if($sla_id==0 && (isset($data['vis_response_datepicker']) && $data['vis_response_datepicker']==1) && ($data['response_from_date']!='') && ($data['resolution_from_date']!='')) {                                       
			$seconds = strtotime($response_date) - strtotime($current_datetime);                    
			$days    = floor($seconds / 86400);
			$hours   = floor(($seconds - ($days * 86400)) / 3600);
			$minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);                             
			$data['vis_due_time_days'] = $days;
			$data['vis_due_time_hrs'] = $hours; $data['vis_due_time_mins'] = $minutes;  
			 
			$seconds1 = strtotime($resolution_date) - strtotime($current_datetime);
			$days1    = floor($seconds1 / 86400);
			$hours1   = floor(($seconds1 - ($days1 * 86400)) / 3600);
			$minutes1 = floor(($seconds1 - ($days1 * 86400) - ($hours1 * 3600))/60);             
			$data['vis_resolution_days'] = $days1;                
			$data['vis_resolution_hrs'] = $hours1; $data['vis_resolution_mins'] = $minutes1;                       
		}                 
		$vis_due_time = trim($data['vis_due_time_days'])*1440; // days to min
		$vis_due_time += trim($data['vis_due_time_hrs'])*60;	// hr to min
		$vis_due_time += trim($data['vis_due_time_mins']);
               
		$vis_resolve_time = trim($data['vis_resolution_days'])*1440; // days to min
		$vis_resolve_time += trim($data['vis_resolution_hrs'])*60;	// hr to min
		$vis_resolve_time += trim($data['vis_resolution_mins']);
        $sla_id = ($sla_id==0) ? array('vis_update_id'=>0, 'vis_due_time'=>$vis_due_time, 'vis_resolve_time'=>$vis_resolve_time, 'vis_schedule_id'=>$data['vis_schedule']) : $sla_id;
         
        $result=$object->set_ticket_property('sla', $sla_id, $list_chk, VIS_STAFF_ID, VIS_LOCATION_AREA);    
   	    $operation['vis_operation'] = 'sla';
        $operation['vis_module'] = 'ticket';
		$operation['vis_ticket_id'] =$data['vis_ticket_id'];
		$operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
		$staff_object->apply_task_automation($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
        $database->database_disconnect();
        if($result){
			if(isset($operation['vis_inbox']) && $operation['vis_inbox']==1)
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("hide");</script>';
			else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $(".modal").modal("hide");$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_ticket_id":'.$data['vis_ticket_id'].', "vis_action":"details"});set_active_tab("ticket_details");</script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
        }
        return true;
    }

    function get_client_data($operation){
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
       // $filter=VIS_TABLE_PREFIX.'client.domain_id=(select domain_id from '.VIS_TABLE_PREFIX.'department where department_id='.$operation['vis_department_id'].' ) and ';
        list($client_info, $client_details)=$object->get_client('', '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include(VIS_PATH_TEMPLATE.'ticket_clients.php');
        return true;
    }

    function new_note($operation){
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include(VIS_PATH_TEMPLATE.'ticket_note.php');
		return true;
    }

    function add_note($operation) {
        global $vis_language, $operation_hnd;
        if(isset($operation['vis_action'])) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
        if(trim($data['vis_note'])=='') {
			if(VIS_LOCATION_AREA==0) echo $vis_language['MSGINFOMISS'];
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff=new class_staff($database);

        $data['vis_note']=nl2br($data['vis_note']);
        $result = $ticket_object->add_note($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $data=array_merge($data, $operation);
        if($result) {
			list($ticket_info, $ticket_details)=$ticket_object->get_ticket(' ticket_id='.$data['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$ticket_object->add_audit_log($ticket_details[0], 33, '', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
			$operation_hnd->operation_flow($data, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($data,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
		}
        if(VIS_LOCATION_AREA==0) {
            echo ($result)?'success':'error';
        }
        else {
            if($result){
                if(isset($operation['vis_onlyclientnote']) && $operation['vis_onlyclientnote']==1){
                     echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle"); $("#vis_details_list").visExecution("load_operations",{"vis_module":"client", "vis_operation":"get_summary", "vis_action":"details", "vis_client_id":'.$data['vis_client_id'].'});';
                }else{
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
                    $sett_obj=new class_setting($database);
                    if(VIS_GAMIFICATION_ACCESS == 1) 
                    {
                         include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
                         $staff=new class_staff($database);
                         $staff_info=$staff->get_staff('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
                         $points = $sett_obj->calculate_points($staff_info[0],7,IS_STAFF_ID,VIS_LOCATION_AREA); 
                    }
                    $module_setting=$sett_obj->get_module_setting('title="vis_show_note" and domain_id='.$data['vis_domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA); 
                    $note_details=(VIS_NOTE_ACCESS==0)?-1:$ticket_object->get_note($data['vis_ticket_id'], $data['vis_client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                    echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle");';
                    $active_tab="";
                    if($module_setting['vis_show_note']){
                        $active_tab="ticket_details";
                        echo '$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_ticket_id":'.$data['vis_ticket_id'].', "vis_action":"details", "vis_readonly":1, "vis_department_id":"'.$data['vis_department_id'].'"});';
                    }else{
                        $active_tab="notes";
                        echo '$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area", {"vis_module":"ticket", "vis_operation":"get_details", "vis_action":"notes", "vis_ticket_id":'.$data['vis_ticket_id'].',"vis_client_id":'.$data['vis_client_id'].',"vis_domain_id":'.$data['vis_domain_id'].'});';
                    }
                    echo 'set_active_tab("'.$active_tab.'");</script>';
                   /* echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle");$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_ticket_id":'.$data['vis_ticket_id'].', "vis_action":"details"});set_active_tab('.$active_tab.');</script>';*/
                }
            }
            else{
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
            }
        }
        return $result;
        $database->database_disconnect();
    }

    function confirm_delete_note($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETENOTE'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_note', 'vis_remark_id':".$operation['vis_remark_id'].", 'vis_ticket_id':".((isset($operation['vis_ticket_id']) && $operation['vis_ticket_id']!='')?$operation['vis_ticket_id']:0).((isset($operation['vis_client_id']) && $operation['vis_client_id']!='')?", 'vis_client_id':".$operation['vis_client_id']:'')."});";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_note($operation) {
        global $vis_language;
        $database = new class_database();
		$operation['vis_current_operation']='client_details'; 
        $operation['vis_current_module']='client'; 
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object = new class_ticket($database);
        $result = $object->delete_note($operation['vis_remark_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(VIS_LOCATION_AREA==0) {
            echo ($result)?'success':'error';
        }
        else {
            if($result) {
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");</script>';
                if($operation['vis_ticket_id']!=0){
					$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
					$ticket_details=$object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					$ticket_details=$ticket_details[1][0];
					$object->add_audit_log($ticket_details, 34, '', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
					$note_details=$object->get_note($ticket_details['ticket_id'],$ticket_details['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
					$note_count=($note_details!=-1)?count($note_details):0; 
                    if($note_count==0)
                    {
                        echo '<script>$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":"'.$operation['vis_ticket_id'].'"});</script>';
                    }
                    else
                    {
                        echo '<script>$("#ticket_note_'.$operation['vis_remark_id'].'").remove();';
                        echo 'if(!$("#ticket_details.active").length && $("[id^=\'ticket_note_\']:first").hasClass("m-t-sm")) $("[id^=\'ticket_note_\']:first").removeClass("m-t-sm");</script>';
                    }
                }else echo '<script>$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"client", "vis_operation":"client_details", "vis_client_id":"'.$operation['vis_client_id'].'"});</script>';
            }
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
        }
        $database->database_disconnect();
        return $result;
    }

    function get_domain($operation) {
        $database=new class_database();
        $filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:'';
        if(VIS_LOCATION_AREA==0) {
            if($filter!='') $filter.=' and ';
            $filter.=(VIS_TABLE_PREFIX.'domain.is_enabled=1 AND avis_department.is_enabled=1');
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $domain_details=$object->get_domain($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        echo get_xml($domain_details, 'domains');
        return true;
    }

    function get_department($operation) {
        $database=new class_database();
        $filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:'';
        if(VIS_LOCATION_AREA==0) {
            if($filter!='') $filter.=' and ';
            $filter.=(VIS_TABLE_PREFIX.'department.is_enabled=1');
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        if(isset($operation['vis_all_department']) && $operation['vis_all_department']==1 && defined('VIS_ANY_DEPT') && VIS_ANY_DEPT==1) $department_details=$object->get_all_department($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        else $department_details=$object->get_department($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        echo get_xml($department_details, 'departments');
        return true;
    }

    function get_status($operation) {       
	 $database=new class_database(); 
	 include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
	 $object=new class_ticket($database);        
	 $dept_access = "";        
	 if(isset($operation['vis_department_id']))           
	 $dept_access = ' and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'];        
	 $department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1'.$dept_access ,VIS_STAFF_ID, VIS_LOCATION_AREA); 
	 if($department_details!=-1){ 
          $filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:''; 
	 if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) { if($filter!='') $filter.=' and '; $filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))'; } if($filter!='') $filter.=' and '; 
	 $filter.='is_enabled=1'; 
	 $department_details=$object->get_status_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
	 $database->database_disconnect(); echo get_xml($department_details, 'status'); return true; }   
	  }

	  
	  function get_level($operation) {       
		global $vis_language;
		$database=new class_database();
      	include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff=new class_staff($database);
		
		$filter='';			
        $limit ='';
		if(isset($operation['vis_title']) && $operation['vis_title'] != ""){
			$operation['vis_filter_enable'] = 1;
			$data['vis_title'] = $operation['vis_title'];
			$filter .= " title like '%".$operation['vis_title']."%' and ";
		}
		if(isset($operation['vis_status']) && $operation['vis_status'] != ""){
			$operation['vis_filter_enable']=1;
			$data['vis_status'] = $operation['vis_status'];
			$filter .= " is_enabled =".$operation['vis_status'].' and '; 
		}
		if(isset($operation['vis_limit']) && $operation['vis_limit'] != ""){
			$limit = $operation['vis_limit']; 
		}	
		$filter=substr($filter, 0, -4);     

		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting=new class_setting($database);
		
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'subsetting.php');
        $sub_object=new class_subsetting($database);
		list($department_info, $department_details)=$sub_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1', '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$ticket_level_info = array();
		if(VIS_ADMIN_ACCESS_LEVEL==1)
         list($ticket_level_count,$ticket_level_details)=$setting->get_ticket_level_list($filter,$data,VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
        else{
			
	     list($ticket_level_count,$ticket_level_details)=$setting->get_properties('get_ticket_level', $filter,$limit,$data);
		}
		
        if(VIS_LOCATION_AREA==0){
			echo get_xml($ticket_level_details, 'ticket_level'); return true; 
		}		
	  }
	  
	  
	  
    function get_channel($operation) {
        $database=new class_database();
        $filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:'';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $channels=$object->get_channel($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        echo get_xml($channels, 'channel');
        return true;
    }

    function get_from_email($operation) {
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$object=new class_ticket($database);
		$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($department_details!=-1){
			if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id']))$filter=$operation['vis_department_id'];
			else return false;
			$email=$object->get_from_email($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$database->database_disconnect();
			echo get_xml($email, 'email');
			return true;
		}
    }

    function get_priority($operation) {
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($department_details!=-1 || (isset($operation['vis_filter']) && $operation['vis_filter']!='')){
			$filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:'';
			if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) {
				if($filter!='') $filter.=' and ';
				$filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))';
			}
			if($filter!='') $filter.=' and ';
			$filter.='is_enabled=1';
			$department_details=$object->get_priorities_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter);
			$database->database_disconnect();
			echo get_xml($department_details, 'priority');
			return true;
		}
    }

    function get_ticket_type($operation) {
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$object=new class_ticket($database);
		$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($department_details!=-1){
			$filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:'';
			if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) {
				if($filter!='') $filter.=' and ';
				$filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))';
			}
			if($filter!='') $filter.=' and ';
			$filter.='is_enabled=1';
			$department_details=$object->get_type_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter);
			$database->database_disconnect();
			echo get_xml($department_details, 'type');
			return true;
		}
    }

    function list_tags($opertion) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $tags=$object->get_tag_list('',VIS_STAFF_ID, VIS_LOCATION_AREA); // 1st argument for filter
        $database->database_disconnect();
		$operation['vis_current_module']="ticket";
		$operation['vis_current_operation']="list_tags";		
        if(VIS_LOCATION_AREA==0) echo get_xml($tags, 'tags');
        else include(VIS_PATH_TEMPLATE.'tag_list.php');
        return true;
    }

    function tag_search($operation) {
        global $vis_language;
        if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
            $action=explode("/", $operation['vis_action']);
            if(count($action)>4 && isset($action[4]) && is_numeric($action[4]))
                $operation['tag_id'] = $action[4];
        }        
        $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
        $sort_by=(isset($operation['vis_sort_by']))?$operation['vis_sort_by']:'';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $tags=$object->get_tag_data($operation['tag_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		$filter=$object->get_label_filter($operation['tag_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $operation['view_title']=$tags[0]['label_name'];
		$operation['filter_id']=$filter['filter_id'];
        $ids='';
        for($i=0;$i<count($tags);$i++) $ids.=$tags[$i]['parent_id'].',';
        return $this->ticket_display($operation, '', '', $filter['filter'], $page, $sort_by);
    }

    function confirm_delete_post($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETETICKETPOST'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_post', 'vis_post_id':".$operation['vis_post_id']."})";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_post($operation) {
        global $vis_language;
        $database = new class_database();
        global $operation_hnd;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $result=$object->delete_post($operation['vis_post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($result) {
            $operation['vis_ticket_id']=$result;
            $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
			$staff_object=new class_staff($database);
			$staff_object->apply_task_automation($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			
			$ticket['ticket_id'] = $result;
                        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$ticket['ticket_id'];
                        list($ticket_info, $ticket_details)=$object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$object->add_audit_log($ticket_details[0], 25, $operation['vis_post_id'], '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        } 
        if($result==0)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");$(".modal").modal("toggle");</script>';
        else {
			$ticket_post=$object->get_ticket_post($ticket['ticket_id'],'', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$ticket_post_count=count($ticket_post);
			if($ticket_post_count==0){
				echo '<script>$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":"'.$operation['vis_ticket_id'].'"});</script>';
			}
			else {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_ticket_post_'.$operation['vis_post_id'].'").remove(); </script>';
			}
		}
        $database->database_disconnect();
        return $result;
    }

    function post_edit($operation){
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $ticket_post=$object->get_ticket_post(0, $operation['vis_post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $ticket_post=$ticket_post[0];
        if(defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR==0) $ticket_post['content'] = get_plain_text($ticket_post['content']);
        include(VIS_PATH_TEMPLATE.'post_edit.php');
        return true;
    }

    function update_post($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        if(defined('VIS_HTML_EDITOR') && VIS_HTML_EDITOR==0) 
        $data['vis_ticket_post'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_ticket_post']);
        if((!isset($data['vis_ticket_post']) || trim(strip_tags($data['vis_ticket_post'],"<img>")) == '')) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGPOSTMESSAGENOTFOUND'].'"); </script>';
            return false;
		}
        $result=$object->update_post($data, VIS_STAFF_ID, VIS_LOCATION_AREA);     
        if(!$result)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        else{
			 list($ticket_info, $ticket_details)=$object->get_ticket(' ticket_id='.$operation['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			 $object->add_audit_log($ticket_details[0], 37, '', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_ticket_post_content_text_'.$data['vis_post_id'].'").show(); $("#vis_ticket_post_content_edit_'.$data['vis_post_id'].'").hide(); $("#vis_ticket_post_content_text_'.$data['vis_post_id'].'").html(`'.$data['vis_ticket_post'].'`); </script>';
		}
		$database->database_disconnect();
        return $result;
    }

    function get_ticket_owner($operation) {
        global $vis_language;
        $database=new class_database();
        if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
            $filter=VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$operation['vis_ticket_id'];
        }
        else {
            echo $vis_language['MSGTKTIDMISS'];
            return false;
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $owner_details=$object->get_ticket_owner($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($owner_details==-1) echo 'Nobody';
        else echo get_xml($owner_details, 'owner');
        return true;
    }

    function add_pinup($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $ret=$object->add_pinup($operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(!$ret) {
            if(VIS_LOCATION_AREA==0) echo 'error';
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        else {
			list($info, $ticket_details)=$object->get_ticket(VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'],'', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$object->add_audit_log($ticket_details[0], 30, $ticket_details[0]['ticket_hash'], '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            if(VIS_LOCATION_AREA==0) echo 'success';
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");</script>';
        }
        $database->database_disconnect();
        return true;
    }

    function add_rating($operation){
       global $vis_language;
      // $data=parse_form_array($operation['vis_action']);
	    /*$spliter=(strstr($operation['vis_action'], '/'))?'/':',';
        $action=explode($spliter, $operation['vis_action']);
		if(!isset($operation['vis_ticket_id']) || $operation['vis_ticket_id']=='') $operation['vis_ticket_id']=$action[4];
		if(!isset($operation['vis_rating']) || $operation['vis_rating']=='')$operation['vis_rating']=$action[5];*/
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        if(IS_LOGIN){
        $ret=$object->add_rating($operation['vis_ticket_id'], $operation['vis_rating'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        }
        else{
            echo '<div class="vis_message">'.$vis_language['MSGERROPRT'].'</div>';
            return false;
        }         
        if(!$ret) {
            echo '<div class="vis_message">'.$vis_language['MSGERROPRT'].'</div>';
            return false;
        }
        else $this->ticket_details($operation);
        return true;
    }

     function add_feedback($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
       /* $check_custom = true;
        if(VIS_LOCATION_AREA == 1) $check_custom=$object->check_custom_data($operation, 3, $operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		$customerrormessage=' ('.$check_custom[1].')';
		if($check_custom!=1 && $check_custom[0]==0){ $check_custom=false; }
       
        if((VIS_LOCATION_AREA == 1 || VIS_LOCATION_AREA == 3) && $check_custom == false )
		{
			$operation['message']=$vis_language['MSGINFOMISS'].''.$customerrormessage;
			$operation['success']=0;
			$this->ticket_feedback($operation);  
			return false;  
		}	*/
        if(IS_LOGIN)
        {
            $ret_delete = $object->delete_custom_data($operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,3); 
            $ret=$object->add_custom_data($operation, 3, $operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);        
            $database->database_disconnect();
        }
        else{
            echo '<div class="vis_message">'.$vis_language['MSGERROPRT'].'</div>';
            return false;
        }         
        if(!$ret) {
            echo '<div class="vis_message">'.$vis_language['MSGERROPRT'].'</div>';
            return false;
        }
        else 
        {
            $operation['message']='<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';   
            $this->ticket_details($operation);
        }        
       return true;
    }

    function update_customfields($operations, $msgflag=0){ 
		global $vis_language;
		//print_r($operations);
        if(isset($operations['vis_action'])) $operation=array_merge($operations, parse_form_array($operations['vis_action']));
        else $operation=$operations;
		$location = unserialize(base64_decode($operations['vis_location']));
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'client.php'); 
        $object_client = new client();
        if(!isset($operation['vis_department']) || $operation['vis_department']=='') $operation['vis_department']=0;
        $check_custom = array();
		$check_customret = array();
        $customerrormessage=array();
        for($i=0; $i< count($location); $i++)
        {  
			$check_custom = $object->check_custom_data($operation,$location[$i], $operation['vis_parent_id'], VIS_STAFF_ID, VIS_LOCATION_AREA); 
			$customerrormessage=' ('.$check_custom[1].')';
			if($check_custom!=1 && $check_custom[0]==0){ $check_custom=false; }
			
			
			$operation['flag']=true;
			if(VIS_LOCATION_AREA == 2 &&  $check_custom==false  ){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'"); </script>';
				return false;
			}
			if((VIS_LOCATION_AREA == 1 || VIS_LOCATION_AREA == 3 || VIS_LOCATION_AREA == 0) && $check_custom==false && $operation['vis_operation']!='update_organization_details')
			{
				$operation['message']='<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'</div>';
				// if(in_array("0",$location))
				if($location[$i]=='0')
				{
					$operation['message']='<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'</div>'; 
					$operation['flag']=false;     

					$object_client->additional_info($operation);
					return false;              
				}
				else
				{ 	
					//$operation['ticket_id']=$operations['vis_parent_id'];
					$this->ticket_edit($operation);
					return false;
				}			
			}
		}   
		
        for($i=0; $i< count($location); $i++) 
        {
			//
			if($location[$i]==12)
			{
				$operations['vis_parent_id']=$operations['vis_group_id'];
			}
			//
			$check_custom = $object->check_custom_data($operation,$location[$i], $operation['vis_parent_id'], VIS_STAFF_ID, VIS_LOCATION_AREA); 
			$customerrormessage=' ('.$check_custom[1].')';
			if($check_custom!=1 && $check_custom[0]==0){ $check_custom=false; }
			
			
			if((VIS_LOCATION_AREA == 1 || VIS_LOCATION_AREA == 3 || VIS_LOCATION_AREA == 0) && $check_custom==false && $operation['vis_operation']=='update_organization_details'){
				$operation['vis_message']='<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'</div>';
				return array('status'=>false,'vis_err_msg'=>$operation['vis_message']);
			}else{
				$ret_delete = $object->delete_custom_data($operations['vis_parent_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,$location[$i]);
				$ret = $object->add_custom_data($operation,$location[$i], $operations['vis_parent_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
        }
	    
        if(VIS_LOCATION_AREA == 2)
        {
            if($ret == false)
             {  
                    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
                    return false;
             }
             else if(!isset($operations['vis_email']) && !isset($operations['vis_username'])){
				list($info, $ticket_details)=$object->get_ticket(VIS_TABLE_PREFIX.'ticket.ticket_id='.$operations['vis_parent_id'],'', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$object->add_audit_log($ticket_details[0], 56, 'staff', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
			 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); </script>';
				
			 }
        }
		
        if(VIS_LOCATION_AREA == 1 && $msgflag==0)
        {
            if($ret == false){
                 $operation['message']='<div class="vis_message">'.$vis_language['MSGERROPRT'].'</div>';          
                $this->ticket_edit($operation);      
            }
            else 
            { 
				list($info, $ticket_details)=$object->get_ticket(VIS_TABLE_PREFIX.'ticket.ticket_id='.$operations['vis_parent_id'],'', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$object->add_audit_log($ticket_details[0], 56, 'client ( '.$ticket_details[0]['last_replier_email'].' )', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
                $operation['message']='<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>'; 
                $operation['success']=1;
                if(in_array("12",$location))
                { 
					return true;
				}
				else if(in_array("0",$location))
                {
                    $object_client->additional_info($operation)  ;
                }
				else if($operation['vis_operation']=='update_organization_details')
				{
					$object_client->update_organization_details($operation);
				}
                else
                {
                    $operation['vis_ticket_id']=$operation['vis_parent_id'];
                    $this->ticket_details($operation);     
                } 
            }
        }
        if(VIS_LOCATION_AREA == 3){
            $operation['message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
            $this->ticket_details($operation);
        }
		$database->database_disconnect();   
        return true;
    }
    function get_ticket_properties($operation){
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
        list($ticket_info, $ticket_details)=$object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_details=$ticket_details[0];
        $database->database_disconnect();
        $message_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $message_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        include(VIS_PATH_TEMPLATE.'ticket_client_properties.php');
        return true;
    }

    function update_ticket_client_properties($operation) {
        $data=parse_form_array($operation['vis_action']);
        global $vis_language;        
		if($data['vis_client_id'] > 0 && (isset($data['vis_email']) || trim($data['vis_email'])!=''))
		 {
			list($message, $flag) = check_email_validation($data['vis_email']);
			if(!$flag) {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';
				return false;
			} 
		 }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_ticket($database);
        $client_object = new class_client($database);
        list($info, $ticket_details)=$object->get_ticket(VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'],'', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticket_details==-1) return false;
        $ticket_details=$ticket_details[0];
        if(isset($data['vis_email']) && $ticket_details['email']!=$data['vis_email']) {
			$vis_domain_filter =  (VIS_SATELLITE_HELPDESK == 2 || VIS_SATELLITE_HELPDESK == 3) ? 'and '.VIS_TABLE_PREFIX.'client.optionB_domain_id='.$data['vis_domain'] :  ' and '.VIS_TABLE_PREFIX.'client.domain_id='.$data['vis_domain'];	
          $filter=VIS_TABLE_PREFIX.'client.email="'.$data['vis_email'].'" '.$vis_domain_filter;
            list($client_info, $client_details)=$client_object->get_client($filter,'', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            if($client_info['total']==0){
                $data['vis_client_id']=0;
                $clientid=$client_object->add_client($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
                $data['vis_client_id']=$clientid;
            }
            else{
                $data['vis_client_id']=$client_details[0]['client_id'];
                $ret=$object->update_client($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
            }
        }
        else {
			$data['vis_operation']='update_ticket_client_properties';
            $data['vis_client_id']=$ticket_details['client_id'];
            $client_object->update_client($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        }
       $data['vis_recipients']=$ticket_details['recipients'];
        $ret=$object->update_client($data, VIS_STAFF_ID, VIS_LOCATION_AREA); 
        if(!$ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        else {
			$object->add_audit_log($ticket_details, 32, '', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
			    echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $(".modal").modal("toggle"); $("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_action":"#/ticket/ticket_details/'.$data['vis_ticket_hash'].'/'.$data['vis_ticket_id'].'"});set_active_tab("ticket_details");</script>';
		}
		$database->database_disconnect();
        return true;
    }

    function confirm_delete_tag($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETETAGS'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_tag', 'vis_tag_id':".$operation['vis_tag_id'].",'vis_current_operation':'".$operation['vis_current_operation']."','vis_current_module':'".$operation['vis_current_module']."'})";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function confirm_delete_label($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETELABEL'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
		$vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';	
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
        $ticket_label=$ticket_object->get_ticket_tag('',VIS_STAFF_ID, VIS_LOCATION_AREA,VIS_TABLE_PREFIX.'label_data.label_id='.$operation['vis_tag_id']);  
        if($ticket_label!=-1) {
            $message_info['vis_message']=count($ticket_label).' '.$vis_language['MSGLABELCNDEL'];
            $message_info['vis_event']='';
        }else {
            $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_tag', 'vis_tag_id':".$operation['vis_tag_id'].",'count':'".$operation['count']."','vis_page':'".$vis_page."', 'vis_current_operation':'".$operation['vis_current_operation']."','vis_current_module':'".$operation['vis_current_module']."'})";
        }
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_tag($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
        $label_list=$object->get_labels_list('label_id='.$operation['vis_tag_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $result=$object->delete_label($operation['vis_tag_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';					
        if(!$result)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); $("#vis_tag_delete_form").dialog("close"); </script>';
        else {
			$activity_log=$setting_object->add_staff_activity_log("Removed ".$label_list[0]['label_name']." label", VIS_STAFF_ID,'', VIS_LOCATION_AREA);
			if($operation['count'] > 1)
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_area",{"vis_module":"'.$operation['vis_current_module'].'", "vis_operation":"'.$operation['vis_current_operation'].'","vis_page":"'.$vis_page.'"}); </script>'; 
			else
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_area",{"vis_module":"'.$operation['vis_current_module'].'", "vis_operation":"'.$operation['vis_current_operation'].'","vis_page":0}); </script>';
        }
        $database->database_disconnect();
		return $result;
    }

    function get_filter_delete($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETEFILTER'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_filter', 'vis_filter_id':".$operation['vis_filter_id']."})";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_filter($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
									include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
						 $setting_object=new class_setting($database);		
							
        $result=$object->delete_filter($operation['vis_filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
								if($result){
								$search_details=$object->get_search_detail('F.filter_id='.$operation['vis_filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
									$search_details=$search_details[0];
									 if($search_details['vscope']==1){
												if($search_details['is_report']==1){$msg='Delete custom report -'.$search_details['filter_name']; $moduleid=12;}else{ $msg='Delete custom filter -'.$search_details['filter_name']; $moduleid=13;}
												$setting_object->add_staff_activity_log($msg,VIS_STAFF_ID,$moduleid, VIS_LOCATION_AREA);	
												}
								}
        $database->database_disconnect();
        if(!$result)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); $("#vis_filter_delete_area").dialog("close"); </script>';
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#global_menu").visExecution("load_area", {"vis_module":"home", "vis_operation":"load_global_menu"}); $("#vis_workpanel_div").visExecution("load_module", "'.$vis_language['TXTFILTERS'].'", {"vis_module":"ticket", "vis_operation":"view_filters"});</script>';
        return $result;
    }

function get_custom_delete($operation) {
        global $vis_language;
		 
        $message_info['vis_form_title']=$vis_language['TXTDELETE'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'custom_report', 'vis_filter_id':".$operation['vis_filter_id'].", 'vis_is_report':".$operation['vis_is_report']."})";
		 
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }
	

 function custom_report($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
								include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
						 $setting_object=new class_setting($database);	
							
        $result=$object->delete_filter($operation['vis_filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($result){
								$search_details=$object->get_search_detail('F.filter_id='.$operation['vis_filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
									$search_details=$search_details[0];
									 if($search_details['vscope']==1){
												if($search_details['is_report']==1){$msg='Delete custom report -'.$search_details['filter_name']; $moduleid=12; }else{ $msg='Delete custom filter -'.$search_details['filter_name']; $moduleid=13;}
												$setting_object->add_staff_activity_log($msg,VIS_STAFF_ID,$moduleid, VIS_LOCATION_AREA);	
												}
								}
        $database->database_disconnect();
		 
         if(!$result){
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); $("#vis_filter_delete_area").dialog("close"); </script>';
      }  else{
			

			  echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#global_menu").visExecution("load_area", {"vis_module":"home", "vis_operation":"load_global_menu"}); $("#vis_workpanel_div").visExecution("load_module", "'.$vis_language['TXTCUSTOM'].'", {"vis_module":"ticket", "vis_operation":"view_filters","custom_show_report":"7", "vis_action":"#/ticket/view_filters/'.$vis_language['TXTCUSTOM'].'/7"});</script>'; 
			} 
        return $result;
    }
    function get_merge_tickets($operation) {
        include(VIS_PATH_TEMPLATE.'ticket_merge.php');
        return true;
    }

    function merge_ticket_hash($operation) {
        global $vis_language, $operation_hnd;
        $data=parse_form_array($operation['vis_action']);
        if(!(isset($data['vis_ticket_id']) && is_numeric($data['vis_ticket_id']) && isset($data['vis_ticket_hash']) && $data['vis_ticket_hash']!='')) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTICKHASHTOMRG'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);        
        $list_chk[0]=$data['vis_ticket_id'];
        $temp=$ticket_object->get_ticket('ticket_hash="'.$data['vis_ticket_hash'].'"', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        list($info, $ticket)=$temp;
        $list_chk[1]=$ticket[0]['ticket_id']; 
        list($total, $ticket_details) = $ticket_object->get_ticket('ticket_id="'.$data['vis_ticket_id'].'"', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $domain_id = $ticket_details[0]['domain_id'];
        $valid_hash = $ticket_object->check_hash_exists($data['vis_ticket_hash'], $domain_id); // validate_hash
        if(!$temp || !$valid_hash || $data['vis_ticket_id']==$ticket[0]['ticket_id']){
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTICKHASHTOMRG'].'"); </script>';
            return false;
		}
		$mergeoptions=array('vis_merge_timetrack'=>'','vis_merge_invoice'=>'','vis_merge_notes'=>'','vis_merge_comments'=>'','vis_merge_post'=>'');


		$mergeoptions['vis_merge_timetrack']=(isset($data['vis_merge_timetrack']) && $data['vis_merge_timetrack']=='1')?'1':'';

		$mergeoptions['vis_merge_invoice']=(isset($data['vis_merge_invoice']) && $data['vis_merge_invoice']=='1')?'1':'';

		$mergeoptions['vis_merge_notes']=(isset($data['vis_merge_notes']) && $data['vis_merge_notes']=='1')?'1':'';

		$mergeoptions['vis_merge_comments']=(isset($data['vis_merge_comments']) && $data['vis_merge_comments']=='1')?'1':'';
		$mergeoptions['vis_merge_post']=(isset($data['vis_merge_post']) && $data['vis_merge_post']=='1')?'1':'';
		$mergeoptions['vis_client_id']=(isset($data['vis_client_id']) && $data['vis_client_id']!='')?$data['vis_client_id']:'0';
		

if(!isset($data['vis_merge_timetrack']) && !isset($data['vis_merge_invoice']) && !isset($data['vis_merge_notes'])&& !isset($data['vis_merge_comments'])&& !isset($data['vis_merge_post']))
{
	
echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTMERGEOPTIONS'].'"); </script>';
			return false;
}
		if($ticket_details[0]['domain_id']==$temp[1][0]['domain_id'])
        $ret=$ticket_object->merge_tickets($list_chk, VIS_STAFF_ID, VIS_LOCATION_AREA,$mergeoptions);
        else
        {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTICKFRMDIFFDOMNOTMERGE'].' "); </script>';
			return false;
		}
        if($ret) {
            $operation['vis_operation']='merge_tickets';
            $operation['vis_ticket_id']=$list_chk[0];
            $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
			$staff_object=new class_staff($database);
			$staff_object->apply_task_automation($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			
            echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("hide");';
echo "$('#vis_workpanel_div').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'ticket_details', 'vis_action':'details', 'vis_ticket_id':".$operation['vis_ticket_id'].", 'vis_department_id':".$ticket_details[0]['department_id']."});";
echo "set_active_tab('ticket_details');</script>";
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        $database->database_disconnect();
        return true;
    }

    function merge_tickets($operation) {
        global $vis_language, $operation_hnd;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);  
        $options=explode('&',$operation['vis_action']);
        $dataa=parse_form_array($operation['vis_action']);
        $list_chk=array();
        foreach($options as $data) {
            $action=explode('=', $data);
            if($action[0]=='action') {
                $property=$action[1];
            }
            elseif(preg_match('/vis_ticket_mass_chk_[0-9]/', $action[0])) {
                $list_chk[]=$action[1];
            }
        }
        $flag=0;
        foreach($options as $data) {
            $action=explode('=', $data);
            if(preg_match('/vis_ticket_merge_id/', $action[0])) {
                $flag=$action[1];
                break;
            }
        }
        if($flag!=0){
            $temp= array();
            $temp[0]=$flag;
            for($i=0;$i<count($list_chk);$i++) if($list_chk[$i]!=$flag) $temp[]=$list_chk[$i];
            $list_chk=$temp;
			
        }
		if(!isset($dataa['vis_merge_timetrack']) && !isset($dataa['vis_merge_invoice']) && !isset($dataa['vis_merge_notes'])&& !isset($dataa['vis_merge_comments'])&& !isset($dataa['vis_merge_post']))
{
	
echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTMERGEOPTIONS'].'"); </script>';
			return false;
}
        $temp=$ticket_object->get_ticket('ticket_id="'.$list_chk[0].'"', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $temp1=$ticket_object->get_ticket('ticket_id="'.$list_chk[1].'"', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(!(isset($list_chk[0]) && is_numeric($list_chk[0]) && isset($list_chk[1]) && is_numeric($list_chk[1]))) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNGLTKT'].'"); </script>';
            return false;
        }
        if($temp[1][0]['domain_id']!=$temp1[1][0]['domain_id'] && VIS_DOMAIN_COUNT>1){
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
            $settingobject=new class_setting($database);
            $vis_satellite_helpdesk = $settingobject->get_settings('title="vis_satellite_helpdesk" and domain_id='.$temp[1][0]['domain_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
            if($vis_satellite_helpdesk != -1) { 
                define('VIS_SATELLITE_HELPDESK', $vis_satellite_helpdesk[0]['content']);
            } else { // satellite case 3
                $vis_satellite_helpdesk = $settingobject->get_settings('title="vis_satellite_helpdesk"', VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($vis_satellite_helpdesk != -1) 
                    define('VIS_SATELLITE_HELPDESK', $vis_satellite_helpdesk[0]['content']);
                else // default if not set
                    define('VIS_SATELLITE_HELPDESK', 1);
            }
        }
		$mergeoptions=array('vis_merge_timetrack'=>'','vis_merge_invoice'=>'','vis_merge_notes'=>'','vis_merge_comments'=>'','vis_merge_post'=>'');


		$mergeoptions['vis_merge_timetrack']=(isset($dataa['vis_merge_timetrack']) && $dataa['vis_merge_timetrack']=='1')?'1':'';

		$mergeoptions['vis_merge_invoice']=(isset($dataa['vis_merge_invoice']) && $dataa['vis_merge_invoice']=='1')?'1':'';

		$mergeoptions['vis_merge_notes']=(isset($dataa['vis_merge_notes']) && $dataa['vis_merge_notes']=='1')?'1':'';
		$mergeoptions['vis_merge_post']=(isset($dataa['vis_merge_post']) && $dataa['vis_merge_post']=='1')?'1':'';

		$mergeoptions['vis_merge_comments']=(isset($dataa['vis_merge_comments']) && $dataa['vis_merge_comments']=='1')?'1':'';
		$mergeoptions['vis_client_id']='0';
        if($temp[1][0]['domain_id']==$temp1[1][0]['domain_id'] || VIS_SATELLITE_HELPDESK == 2 || VIS_SATELLITE_HELPDESK == 3)
            $ret=$ticket_object->merge_tickets($list_chk, VIS_STAFF_ID, VIS_LOCATION_AREA,$mergeoptions);
        else
        {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTICKFRMDIFFDOMNOTMERGE'].' "); </script>';
			return false;
		}
        if($ret) {
            $operation['vis_ticket_id']=$list_chk[0];
            $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			$staff_object=new class_staff($database);
			$staff_object->apply_task_automation($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_workpanel_div").visExecution("load_area", {"vis_module":"ticket", "vis_operation":"filter_ticket", "vis_filter_id": 1}); $("#vis_global_msg_div").visExecution("load_operations",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"}); $(".modal").modal("toggle");</script>';
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        $database->database_disconnect();
        return true;
    }
	
    function whmcs_products($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=1 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $login_integrate = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $login_integrate =   $login_integrate[1];
		if(count($login_integrate)>0 && $login_integrate!=-1)
		{
			  for($i=0;$i<count($login_integrate);$i++)
			  {
				$url =  $login_integrate[$i]['billing_url']."includes/api.php"; 
				$file_headers = @get_headers($url);
				if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
				}
				else {
				   $postfields["username"] = $login_integrate[$i]['admin_user']; # Admin username goes here
				   $postfields["password"] = md5($login_integrate[$i]['admin_password']);  # Admin password goes here
				   $postfields["action"] = "validatelogin";
				  
				   $postfields["action"] = "getclientsdetails"; // get client details
				   $postfields["email"] = $vis_email;
				   $ch = curl_init();
				   curl_setopt($ch, CURLOPT_URL, $url);
				   curl_setopt($ch, CURLOPT_POST, 1);
				   curl_setopt($ch, CURLOPT_TIMEOUT, 100);
				   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				   curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
				   $out_data = curl_exec($ch);
				   curl_close($ch);
				   $out_data = explode(";",$out_data);
				   foreach ($out_data AS $temp) {
					   $temp = explode("=",$temp);
					   $results[$temp[0]] = $temp[1];
					   $results[$temp[2]] = $temp[3];
				   }
				
				   if($results["result"]=="success")
				   {
						 $postfields["action"] = "getclientsproducts"; // get product details
						 $postfields["clientid"] = $results["userid"];
						 $postfields["responsetype"] = "json";
						 $ch = curl_init();
						 curl_setopt($ch, CURLOPT_URL, $url);
						 curl_setopt($ch, CURLOPT_POST, 1);
						 curl_setopt($ch, CURLOPT_TIMEOUT, 100);
						 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
						 curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
						 $out_detail = curl_exec($ch);
						 $out_detail = get_object_vars(json_decode($out_detail));
						
						 if($out_detail['totalresults']!= 0)
						 {
							 $productArray =  get_object_vars($out_detail['products']);
							 if(!empty($productArray['product']) && $productArray['product'] != '') 
							 {
								 $product = array();
								 foreach($productArray['product'] as $row){
									 $product[] = get_object_vars($row);
								 }
							 }
							 $productDetails[$login_integrate[$i]['billing_url']] = $product ;
						 }
						 else  $productDetails[$login_integrate[$i]['billing_url']] = '' ;
				    }
				 }
		     }
        }
      
        $whmcs_tab = 1;
        include(VIS_PATH_TEMPLATE.'whmcs_details.php');
    }

    function whmcs_clients($operation)
    {
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=1 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $login_integrate = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $login_integrate =   $login_integrate[1];
		  if(count($login_integrate)>0 && $login_integrate!=-1)
		  {
			  for($i=0;$i<count($login_integrate);$i++)
			  {
				$clientDetails[$login_integrate[$i]['billing_url']];
				$url =  $login_integrate[$i]['billing_url']."includes/api.php"; 
				$file_headers = @get_headers($url);
				if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
				}
				else {
					   $postfields["username"] = $login_integrate[$i]['admin_user']; # Admin username goes here
					   $postfields["password"] = md5($login_integrate[$i]['admin_password']);  # Admin password goes here
					   $postfields["action"] = "validatelogin";
		
					   $postfields["action"] = "getclientsdetails";
					   $postfields["email"] = $operation['vis_email'];
					   $postfields["responsetype"] = "json";
					   $ch = curl_init();
					   curl_setopt($ch, CURLOPT_URL, $url);
					   curl_setopt($ch, CURLOPT_POST, 1);
					   curl_setopt($ch, CURLOPT_TIMEOUT, 100);
					   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					   curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
					   $out_data = curl_exec($ch);
					   curl_close($ch);
					 
					   $out_detail = json_decode($out_data);
					   $client_details = get_object_vars($out_detail);
					   if($client_details['result'] != 'error' ) {
					   $clientDetails[$login_integrate[$i]['billing_url']] = $client_details;
					   }

				   }
				}
			  }
				
        $whmcs_tab = 2;
        include(VIS_PATH_TEMPLATE.'whmcs_details.php');
    }

    function delete_ticket($operation) {
        global $vis_language;
        $options=explode('&',$operation['vis_action']);
        $list_chk=array();
        foreach($options as $data) {
            $action=explode('=', $data);
            if($action[0]=='action') {
                $property=$action[1];
            }
            elseif(preg_match('/vis_ticket_mass_chk_[0-9]/', $action[0])) {
                $list_chk[]=$action[1];
            }
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        if(count($list_chk)==0) $ret=false;
        else $ret=$ticket_object->delete_ticket('ticket_id in ('.implode(',',$list_chk).')', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ret) {  
           echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
           
		    if($operation['vis_filter_id']==7){
				echo '$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTDRAFT'].'",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":7, "vis_draft":1});';
			}else if($operation['vis_filter_id']==21){
				echo '$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTDRAFT'].'",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":21, "vis_draft":1});';
			}else if($operation['vis_filter_id']==5){
				 echo '$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTTRASH'].'",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":5});';
			}else{
				echo '$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTDRAFT'].'",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":1});';
			}
		   
		    /*if($operation['vis_filter_id']!=5) echo '$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTDRAFT'].'",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":1, "vis_draft":1});';
           else echo '$("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTTRASH'].'",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":5});';
		   */
           echo '$("#vis_global_msg_div").visExecution("load_operations",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"}); </script>';
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        $database->database_disconnect();
        return true;
    }

    function twitter_search($operation) {
        include(VIS_PATH_TEMPLATE.'twitter_search.php');
        return true;
    }

    function search_media($operation) {
        $data=parse_form_array($operation['vis_action']);
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        if(isset($operation['vis_media_id'])) {
            $search_list=$object->get_media_list('search_id='.$operation['vis_media_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $search_list=$search_list[0];
            $content=$search_list['content'];
            $title=$search_list['title'];
        }
        elseif(isset($data['vis_query']) && $data['vis_query']!='') {
            $content=$data['vis_query'];
            $title=ucfirst($data['vis_query']);
        }
        else {
            echo $vis_language['MSGINFOMISS'];
            return false;
        }
        $tweets=$object->search_twitter($content, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(isset($tweets->errors) && $tweets->errors!='') print_r($tweets->errors);
        else {
            include(VIS_PATH_TEMPLATE.'twitter_result.php');
        }
        return true;
    }

    function media_search_list($operation){
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $search_list=$object->get_media_list('', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'media_search_list.php');
        return true;
    }

    function new_twetter_search($operation){
        include(VIS_PATH_TEMPLATE.'twitter_search.php');
        return true;
    }

    function save_search_media($operation) {
        global $vis_language, $operation_hnd;
        $data=parse_form_array($operation['vis_action']);
        if($data['vis_title']=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQFLDTIT'].' "); </script>';
            return false;
        }
        if(trim($data['vis_query'])=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].' "); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->save_search_media($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $(this).visInterface("remove_tab", "vis_module_ticket_div"); </script>';
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        return true;
    }

    function delete_search_media($operation) {
        global $vis_language;
        if(!(isset($operation['vis_media_id']) && is_numeric($operation['vis_media_id']))) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->delete_search_media($operation['vis_media_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($ret) {
            $operation['vis_operation']='merge_tickets';
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_module_ticket_div").tabs("load", $("#vis_module_ticket_div").tabs("option","selected")); </script>';
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        return true;
    }

    function confirm_delete_trash($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTEMPTYTRASH'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'empty_trash'})";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function empty_trash($operation) {
        global $vis_language, $operation_hnd;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->delete_ticket('is_deleted=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_module","Trash",{"vis_module":"ticket","vis_operation":"filter_ticket", "vis_filter_id":5}); $("#vis_global_msg_div").visExecution("load_operations",{"vis_module":"staff", "vis_operation":"refresh_leftpanel","vis_action":"delete"}); </script>';
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); $("#vis_trash_conf").dialog("close") </script>';
        return true;
    }

    function last_post($operation) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->get_last_post($operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $last_post = strip_tags($ret['content'], '<br><span>');
        echo substr($last_post, 0, 400);
    }
	function load_link_data($operation) {
		global $vis_language;
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		$link_data=array('vis_ticket_id'=>$operation['vis_ticket_id'], 'case'=>1);
		$link_arr = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
		
		
		if($link_arr!=-1){
			foreach($link_arr as $link){ 
				$ticket_id_arr=explode(",", $link['ticket_ids']);
				if(!empty($ticket_id_arr)){
					if(in_array($operation['vis_ticket_id'], $ticket_id_arr)){
							$ticket_id = $link['parent_ticket_id'];
							$del_type ='child';
							$link_data=array('vis_ticket_id'=>$ticket_id, 'case'=>2, 'filter'=>'link_id='.$link['link_id']);
							$temp = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
							$temp[0]['del_type']=$del_type;
							$link_details[]=$temp[0];
					}else{		
						foreach($ticket_id_arr as $ticket_id){ 
							$del_type ='parent';
							$link_data=array('vis_ticket_id'=>$ticket_id, 'case'=>2, 'filter'=>'link_id='.$link['link_id']);
							$temp = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
							$temp[0]['del_type']=$del_type;
							$link_details[]=$temp[0];
						}    
					}
				}
			}
		}
		$link_data=array('vis_ticket_id'=>$operation['vis_ticket_id'], 'case'=>2, 'filter'=>'1=1');
		$temp = $ticket_object->get_ticket_link($link_data, VIS_STAFF_ID, VIS_LOCATION_AREA);
		//print_r($temp[0]);
		$title=$vis_language['TXTTLINKSFORTICKET'].' '.$temp[0]['ticket_hash'];
		/*$link_type_arr = array( 1 => $vis_language['TXTRELATESTO'], 2 => $vis_language['TXTISRELATEDTO'], 3 => $vis_language['TXTISAPARENTOF'], 4 => $vis_language['TXTISACHILDOF'], 5 => $vis_language['TXTDEPENDSON'], 6 => $vis_language['TXTISDEPENDEDON'], 7 => $vis_language['TXTDUPLICATES'], 8 => $vis_language['TXTISADUPLICATEDBY']);
		$link_type_oppose_arr = array( 1 => $vis_language['TXTISRELATEDTO'], 2 => $vis_language['TXTRELATESTO'], 3 => $vis_language['TXTISACHILDOF'], 4 => $vis_language['TXTISAPARENTOF'], 5 => $vis_language['TXTISDEPENDEDON'], 6 => $vis_language['TXTDEPENDSON'], 7 => $vis_language['TXTISADUPLICATEDBY'], 8 => $vis_language['TXTDUPLICATES']);
		
		$html='<table class="table table-hover b-t b-light m-b-none" data-ride="datatables"><thead class="table_head"><tr><th>'.$vis_language['TXTLINK'].'</th><th>'.$vis_language['TXTTICKETHASH'].'</th></tr></thead><tbody>';
		
		for($i=0; $i<count($link_details); $i++) {
			$link_type= ($operation['vis_ticket_id']==$link_details[$i]['parent_ticket_id']) ? $link_type_arr[$link_details[$i]['link_type']] : $link_type_oppose_arr[$link_details[$i]['link_type']]; 	
		
			$html.='<tr><td>'.$link_type.'</td><td><a href="#/ticket/ticket_details/'.$link_details[$i]['ticket_hash'].'/'.$link_details[$i]['ticket_id'].'" class="link">'.$link_details[$i]['ticket_hash'].'</a></td></tr>';
		}
		$html.='</tbody></table>';*/
		include(VIS_PATH_TEMPLATE."ticket_link_details.php");
        return true; 
		//echo $html;
    }

    function add_live_tag($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $data=array_merge($data, $operation);
        $data['vis_action']='details';
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
        if(!isset($data['vis_newtag']) || trim($data['vis_newtag'])=='') {
			if(VIS_LOCATION_AREA==0) echo $vis_language['MSGINFOMISS'];
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'"); </script>';
            return false;
        }
        else {
            $ret=$ticket_object->add_live_tag($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if(VIS_LOCATION_AREA!=0) echo '<script>if($("#show_vis_ticket_tags").is(":visible")) $("#show_vis_ticket_tags").hide();</script>';
		}
		if($ret==-1){
		 if(VIS_LOCATION_AREA==0) echo $vis_language['MSGTAGALREDEYUSED'];
		 else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTAGALREDEYUSED'].'"); </script>';
		 $vis_ticket_id=$operation['vis_ticket_id'];
		 $tag_details = $ticket_object->get_ticket_tag($vis_ticket_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
		 include(VIS_PATH_TEMPLATE."ticket_tags_list.php");
		 return false;
		}
		$vis_ticket_id=$operation['vis_ticket_id'];
		$tag_details = $ticket_object->get_ticket_tag($vis_ticket_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(VIS_LOCATION_AREA==0) {
            echo ($ret)?'success':'error';
        }
        else{
			if($ret){
				 list($ticket_info, $ticket_details)=$ticket_object->get_ticket(' ticket_id='.$vis_ticket_id, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				 $ticket_object->add_audit_log($ticket_details[0], 42, '', $data['vis_newtag'] , VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
		}
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE."ticket_tags_list.php");
        return true;        
    }

    function add_live_label($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $data=array_merge($data, $operation);
        if(!isset($data['vis_label_id']) || trim($data['vis_label_id'])=='') {
			if(VIS_LOCATION_AREA==0) echo $vis_language['MSGINFOMISS'];
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].' "); </script>';
            return false;
        }
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		$ret=$ticket_object->add_live_label($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$label_list=$ticket_object->get_labels_list(' (department_access=0 or find_in_set('.$data['department_id'].', department_access)) and is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$vis_ticket_id=$data['vis_ticket_id'];
        $vis_dept_id=$data['department_id'];
		$label_details = $ticket_object->get_ticket_labels($vis_ticket_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$new_label_details=$ticket_object->get_labels_list('label_id="'.$data['vis_label_id'].'"', VIS_STAFF_ID, VIS_LOCATION_AREA); 
		$new_label_details=$new_label_details[0];
		if(VIS_LOCATION_AREA==0) {
            echo ($ret)?'success':'error';
        }
        else {
			if($ret){
				 list($ticket_info, $ticket_details)=$ticket_object->get_ticket(' ticket_id='.$data['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				 $ticket_object->add_audit_log($ticket_details[0], 29, '', $new_label_details['label_name'] , VIS_STAFF_ID, VIS_LOCATION_AREA);
			 }
		}
		$database->database_disconnect();  
		if(VIS_LOCATION_AREA!=0){     
			include(VIS_PATH_TEMPLATE."ticket_label_list.php");
			$labels = "";
			if($new_label_details!=-1){
				$labels='<span id="vis_ticket_label_'.$new_label_details['label_id'].'">';
				$labels.='<div class="btn-group m-l-xs"><span class="btn btn-xs l-h-1x text-xs" style="background-color: '.$new_label_details['label_color'].'; color: #fff; font-weight: normal">'.$new_label_details['label_name'].'</span>';
				$labels.='<button style="background-color: '.$new_label_details['label_color'].'; color: #fff;" type="button" class="btn btn-xs l-h-1x text-xs p-l-none" onclick="remove_label('.$new_label_details['label_id'].','.$data['vis_ticket_id'].');"><span aria-hidden="true"><i class="vh vh-cross"></i></span><span class="sr-only">Close</span></button>';
				$labels.='</div></span>';
				echo '<script>$("#vis_ticket_labels").append(\''.$labels.'\');</script>';
			}	
		}	
        return true;
    }

    function remove_ticket_label($operation) {
		global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->remove_ticket_label($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $vis_ticket_id=$operation['vis_ticket_id'];
        if($ret===-1) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQRECPT'].'"); </script>';
        else echo '<script>$("#vis_ticket_label_'.$operation["vis_label_id"].'").remove();</script>';
		if(isset($operation['vis_action']) && $operation['vis_action']=="remove_tags"){
			$tag_details = $ticket_object->get_ticket_tag($vis_ticket_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($ret){
			 $tag_info=$ticket_object->get_tag_list('label_id="'.$operation['vis_label_id'].'"', VIS_STAFF_ID, VIS_LOCATION_AREA); 
			 $tag_info=$tag_info[0];
			 list($ticket_info, $ticket_details)=$ticket_object->get_ticket(' ticket_id='.$vis_ticket_id, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			 $ticket_object->add_audit_log($ticket_details[0], 43, '', $tag_info['label_name'] , VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
			if($tag_details==-1) echo '<script>$("#show_vis_ticket_tags").show();$("#vis_ticket_tags").hide();</script>';
			include(VIS_PATH_TEMPLATE."ticket_tags_list.php");
		}
		else{
            if(isset($operation['department_id'])) $vis_dept_id=$operation['department_id'];
			$label_list=$ticket_object->get_labels_list(' (department_access=0 or find_in_set('.$vis_dept_id.', department_access)) and is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$label_details = $ticket_object->get_ticket_labels($vis_ticket_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$new_label_details=$ticket_object->get_labels_list('label_id="'.$operation['vis_label_id'].'"', VIS_STAFF_ID, VIS_LOCATION_AREA); 
			$new_label_details=$new_label_details[0];
			if($ret){
			 list($ticket_info, $ticket_details)=$ticket_object->get_ticket(' ticket_id='.$vis_ticket_id, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			 $ticket_object->add_audit_log($ticket_details[0], 31, '', $new_label_details['label_name'] , VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
			include(VIS_PATH_TEMPLATE."ticket_label_list.php");
		}
		$database->database_disconnect();
		return true;		
    }

    function add_live_recipient($operation) { 
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $data=array_merge($data, $operation);  
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		$data['field']=($data['action']=="add_people") ? $data["vis_people"] : $data["vis_newrcpt"];       
		if(isset($data['field']) || trim($data['field'])!='')
		 {
			list($message, $flag) = check_email_validation($data['field']);
			if(!$flag) {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$message.'"); </script>';		
			} else {
           	 $ret=$ticket_object->udpate_live_recipient($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
		}
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$ticket_details=$ticket_details[0];
		if($ret) {
			if(isset($data["vis_newrcpt"]) && $data["vis_newrcpt"]!='')
			$ticket_object->add_audit_log($ticket_details, 38, '', $data["vis_newrcpt"] , VIS_STAFF_ID, VIS_LOCATION_AREA);
			else if(isset($data["vis_people"]) && $data["vis_people"]!='')
			$ticket_object->add_audit_log($ticket_details, 39, '', $data["vis_people"] , VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
		$database->database_disconnect();
		if($data['action']=="add_people") include(VIS_PATH_TEMPLATE."peoples_list.php");
		else include(VIS_PATH_TEMPLATE."recipients_list.php");
        return true;
    }

    function remove_ticket_recp($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->remove_ticket_recp($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ret===-1) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQRECPT'].'"); </script>';
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$ticket_details=$ticket_details[0];
		if($ret) {
			if(isset($operation["vis_action"]) && $operation["vis_action"]=='remove_recipient')
			$ticket_object->add_audit_log($ticket_details, 40, '', $operation['vis_email'] , VIS_STAFF_ID, VIS_LOCATION_AREA);
			else if(isset($operation["vis_action"]) && $operation["vis_action"]=='remove_people')
			$ticket_object->add_audit_log($ticket_details, 41, '', $operation['vis_email'] , VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
		$database->database_disconnect();
		if($operation['vis_action']=="remove_people") include(VIS_PATH_TEMPLATE."peoples_list.php");
		else include(VIS_PATH_TEMPLATE."recipients_list.php");
		return true;
    }

    function get_label($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $labels=$ticket_object->get_labels_list('label_name like "%'.$operation['vis_data'].'%"', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($labels===-1) return false;
        $return='[';
        for($i=0;$i<count($labels);$i++) $return.='{"label_id": "'.$labels[$i]['label_id'].'", "label_name": "'.$labels[$i]['label_name'].'"},';
        $return=substr($return,0,-1);
        $return.=']';
        echo $return;
        return true;
    }

    function get_tag($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $labels=$ticket_object->get_tag_list('label_name like "%'.$operation['vis_data'].'%"', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($labels===-1) return false;
        $return='[';
        for($i=0;$i<count($labels);$i++) $return.='{"label_id": "'.$labels[$i]['label_id'].'", "label_name": "'.$labels[$i]['label_name'].'"},';
        $return=substr($return,0,-1);
        $return.=']';
        echo $return;
        return true;
    }

    function rate_ticket($operation) {
		
        global $vis_language;
        if(VIS_LOCATION_AREA==1 && IS_LOGIN==0){
             include(VIS_PATH_TEMPLATE.'header.php');
             include(VIS_PATH_TEMPLATE.'login.php');
             include(VIS_PATH_TEMPLATE.'footer.php');
             break;
        }
        if(isset($operation['vis_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			$operation['ticket_id'] = $data[4];
			$operation['rate'] = $data[6];
			$operation['rate_flag'] = $data[7];
		}
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ticket_details=$ticket_object->get_ticket(VIS_TABLE_PREFIX.'ticket.client_id='.VIS_CLIENT_ID.' and ticket_id='.$operation['ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticket_details[1]!=-1){
            $ret=$ticket_object->rate_ticket($operation, VIS_CLIENT_ID, VIS_LOCATION_AREA);
            $operation['success']=1;
            $operation['message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
        }elseif(VIS_REPLY_TICKET==1){
            $ticket_details=$ticket_object->get_ticket(' ticket_id='.$operation['ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client=new class_client($database);
            $filter=VIS_TABLE_PREFIX.'client.client_id='.$ticket_details[1][0]['client_id'];
            list($client_info, $client_details)=$client->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $client_details=$client_details[0];
            if($client_details['parent_id']==VIS_CLIENT_ID){
                $ret=$ticket_object->rate_ticket($operation, $ticket_details[1][0]['client_id'], VIS_LOCATION_AREA);
                $operation['success']=1;
                $operation['message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
            }else{
                $filter=VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
                list($client_info, $client_details)=$client->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
                $client_details=$client_details[0];
                if($client_details['parent_id']==$ticket_details[1][0]['client_id']){
                    $ret=$ticket_object->rate_ticket($operation, $client_details['parent_id'], VIS_LOCATION_AREA);
                    $operation['success']=1;
                    $operation['message']=(!$ret)?'<div class="vis_error_message">'.$vis_language['MSGERROPRT'].'</div>':'<div class="vis_message">'.$vis_language['MSGSUCCOPRT'].'</div>';
                }
            }
        }else{
            $operation['success']=0;
            $operation['message']='<div class="vis_error_message">'.$vis_language['MSGACCSSDND'].'</div>';
        }
       
        $database->database_disconnect();
        if(isset($operation['rate_flag']) && $operation['rate_flag'] == 1)
        {
         echo (!$ret)?0:1;
        }
        else $this->ticket_details($operation);
        return true;
    }

    function get_department_status_list($operation) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ret=$ticket_object->get_department_status_list($operation['vis_department'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        echo get_xml($ret, 'stuaus');
        return true;
    }
    
    function new_time_track($operation){
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_object=new class_setting($database);
        $department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		$domain_details=$object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$department_details[0]['domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		$currency=$domain_details[0]['currency'];
		$amount=$client_object->get_bill_setting($operation['vis_ticket_id'], $operation['vis_ticket_time_'][$operation['vis_ticket_id']], VIS_STAFF_ID, VIS_LOCATION_AREA);
		$module_setting=$sett_object->get_settings(' module_id=2 and title="vis_show_time_track_amount" and domain_id='.$operation['vis_domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(empty($module_setting) || $module_setting==-1){
			$module_setting=$sett_object->get_settings(' module_id=2 and title="vis_show_time_track_amount" and domain_id=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
        $message_info['ticket_id'] = (isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) ? $operation['vis_ticket_id'] : 0;
        $message_info['client_id'] = (isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id'])) ? $operation['vis_client_id'] : 0;
        $message_info['timer_value'] = (isset($operation['vis_ticket_time_'][$message_info['ticket_id']]) && is_numeric($operation['vis_ticket_time_'][$message_info['ticket_id']])) ? $operation['vis_ticket_time_'][$message_info['ticket_id']] : 0;
								$hr = floor(($message_info['timer_value']/60)/60);
        $message_info['timer_value'] = ($message_info['timer_value'] / 60) % 60;
        
        $min = $message_info['timer_value']%60;
		$database->database_disconnect();
        $message_info['vis_department_id'] = $operation['vis_department_id'];
        include(VIS_PATH_TEMPLATE.'time_track.php');
        return true;
    }
    
    function add_time_track($operation) {
        global $vis_language, $operation_hnd;
        if(isset($operation['vis_action'])) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
       if( ($data['vis_billtime_hr'] == '' && $data['vis_billtime_min'] == '') || ($data['vis_worktime_hr'] == '' && $data['vis_worktime_min'] == '')) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
        if(!is_numeric($data['vis_billtime_hr']) || !is_numeric($data['vis_billtime_min']) )  
        {
			  echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGBILLINVTIME'].'");</script>';
            return false;
		}
		 if(!is_numeric($data['vis_worktime_hr']) || !is_numeric($data['vis_worktime_min']) )  
        {
			  echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGWORKINVTIME'].'");</script>';
            return false;
		}
        if(isset($data['vis_amount']) && $data['vis_amount'] == '') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
         if(isset($data['vis_amount']) && $data['vis_amount'] !='' && !is_numeric($data['vis_amount'])) {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
			return false;			
		}
		 if( trim($data['vis_time_track']) == '' ) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $data['vis_time_track']=nl2br($data['vis_time_track']);
        $result = $object->add_time_track($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $data=array_merge($data, $operation);
        if($result) $operation_hnd->operation_flow($data, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
        if(VIS_LOCATION_AREA==0) {
            echo ($result)?'success':'error';
        }
        else {
            if($result){
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $(".modal").modal("toggle");$(".modal-backdrop").remove();document.cookie="vis_ticket_time_['.$data['vis_ticket_id'].']=0";$("#time_track").show(); $("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"time_track_details", "vis_ticket_id":'.$data['vis_ticket_id'].', "vis_department_id":'.$data['vis_department_id'].'});set_active_tab("time_track");</script>';
            }
            else{
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
            }
        }
        return $result;
        $database->database_disconnect();
    }
    
    function time_track_details($operation) {
		if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) {
			$database = new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
			$ticket_object = new class_ticket($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
            $sett_object=new class_setting($database);
			$filter = 'ticket_id='.$operation['vis_ticket_id'];
			$time_track_details = $ticket_object->get_time_track_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$department_details=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
			$domain_details=$ticket_object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$department_details[0]['domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
			$currency=$domain_details[0]['currency'];
			$module_setting=$sett_object->get_settings(' module_id=2 and title="vis_show_time_track_amount" and domain_id='.$domain_details[0]['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			if(empty($module_setting) || $module_setting==-1){
				$module_setting=$sett_object->get_settings(' module_id=2 and title="vis_show_time_track_amount" and domain_id=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
			$time_track_count = ($time_track_details!=-1) ? count($time_track_details) : 0;
			$database->database_disconnect();
			if(VIS_LOCATION_AREA==0)
			echo get_xml($time_track_details, 'time_track');
			include_once(VIS_PATH_TEMPLATE.'time_track_list.php');
			return true;
		}
		else {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTKTIDMISS'].'"); </script>';
			return false;
		}
	}
	
	function edit_time_track($operation) {
        global $vis_language;
        if(VIS_LOCATION_AREA == 1 && !IS_LOGIN)
        {
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            include(VIS_PATH_TEMPLATE.'login.php');
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
        }
        if(isset($operation['vis_time_tracker_id']) && is_numeric($operation['vis_time_tracker_id'])) $time_tracker_id = $operation['vis_time_tracker_id'];
        else {            
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVMISS'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_object=new class_setting($database);
        $filter = 'time_tracker_id='.$time_tracker_id;
        $time_track_details=$object->get_time_track_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $time_track_details=$time_track_details[0];
        $department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		$domain_details=$object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$department_details[0]['domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		$currency=$domain_details[0]['currency'];
		$module_setting=$sett_object->get_settings(' module_id=2 and title="vis_show_time_track_amount" and domain_id='.$domain_details[0]['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(empty($module_setting) || $module_setting==-1){
			$module_setting=$sett_object->get_settings(' module_id=2 and title="vis_show_time_track_amount" and domain_id=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
        $database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'time_track_edit.php');
        return true;
    }
    
    function update_time_track($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        if(!is_numeric($data['vis_time_tracker_id']) || $data['vis_time_tracker_id']==0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVMISS'].'"); </script>';
            return false;

        }
       if( ($data['vis_billtime_hr'] == '' && $data['vis_billtime_min'] == '') || ($data['vis_worktime_hr'] == '' && $data['vis_worktime_min'] == '')) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
        if(isset($data['vis_amount']) && $data['vis_amount'] == '') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
         if(isset($data['vis_amount']) && $data['vis_amount'] !='' && !is_numeric($data['vis_amount'])) {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
			return false;			
		}
		 if( trim($data['vis_time_track']) == '' ) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $ret=$object->update_time_track($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(!$ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_details_list_'.$data["vis_ticket_id"].'").visExecution("load_operations",{"vis_module":"ticket", "vis_operation":"time_track_details", "vis_ticket_id":"'.$data["vis_ticket_id"].'", "vis_department_id":"'.$data['vis_department_id'].'"});$(".modal").modal("toggle");$(".modal-backdrop").remove();</script>';
        return true;
    }
    
    function confirm_delete_time_track($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETETIMETRACK'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_time_track', 'vis_time_tracker_id':".$operation['vis_time_tracker_id'].", 'vis_ticket_id':".$operation['vis_ticket_id'].", 'vis_department_id':".$operation['vis_department_id']."});";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_time_track($operation) {
        global $vis_language;
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object = new class_ticket($database);
        $result = $object->delete_time_track($operation['vis_time_tracker_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(VIS_LOCATION_AREA==0) {
            echo ($result)?'success':'error';
        }
        else {
            if($result) {
				$time_track_details=$object->get_time_track_details('ticket_id='.$operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA); 
				$time_track_count=($time_track_details!=-1)?count($time_track_details):0;
				if($time_track_count==0)
				{
					echo '<script>$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":"'.$operation['vis_ticket_id'].'"});</script>';
				}
				else {
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_details_list_'.$operation['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"time_track_details", "vis_ticket_id":'.$operation['vis_ticket_id'].', "vis_department_id":'.$operation['vis_department_id'].'});set_active_tab("time_track");';
					echo ' </script>';
				}
            }
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
        }
        $database->database_disconnect();
        return $result;
    }
    
    function load_inline_images($operation) {
		global $vis_language;
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object = new class_ticket($database);
        $post_details=$object->get_ticket_post(0, $operation['vis_post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($operation['vis_display'])  echo json_encode( array('vis_post_content_html' => stripslashes($post_details[0]['content'])) );
        else  echo json_encode( array('vis_post_content_html' => preg_replace("/<img[^>]+\>/i", " ", $post_details[0]['content'])) );
        $database->database_disconnect();
	}

	function apply_filter($operation){
        global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);         
		if(isset($operation['vis_filter_enable']) && $operation['vis_filter_enable']==1){			
			$data['vis_filter_title'] = $vis_language['TXTFILTERRESULT'];
			$data['vis_concate_option'] = "and";			
			$i=1;
			if(isset($operation['search_domain']) && $operation['search_domain']!=''){
				$data['vis_main_search'.$i] = 18;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_domain'];
			}
			if(isset($operation['search_dept']) && $operation['search_dept']!=''){
				$data['vis_main_search'.$i] = 7;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_dept'];
			}
			if(isset($operation['search_status']) && $operation['search_status']!=''){
				$data['vis_main_search'.$i] = 8;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_status'];
			}
			if(isset($operation['search_priority']) && $operation['search_priority']!=''){
				$data['vis_main_search'.$i] = 9;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_priority'];
			}
			if(isset($operation['search_type']) && $operation['search_type']!=''){
				$data['vis_main_search'.$i] = 21;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_type'];
			}
			if(isset($operation['search_flag']) && $operation['search_flag']!=''){
				$data['vis_main_search'.$i] = 11;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_flag'];
			}
			if(isset($operation['search_owner']) && $operation['search_owner']!=''){
				$data['vis_main_search'.$i] = 10;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_owner'];
			}
			if(isset($operation['search_internal_ticket']) && $operation['search_internal_ticket']=='1'){
				$data['vis_main_search'.$i] = 30;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_internal_ticket'];
			}
			if(isset($operation['search_category']) && $operation['search_category']!=''){
				$data['vis_main_search'.$i] = 31;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_category'];
			}
			if(isset($operation['search_subcategory']) && $operation['search_subcategory']!=''){
				$data['vis_main_search'.$i] = 32;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_subcategory'];
			}
			if(isset($operation['search_item']) && $operation['search_item']!=''){
				$data['vis_main_search'.$i] = 33;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_item'];
			}
			if(isset($operation['search_level']) && $operation['search_level']!=''){
				$data['vis_main_search'.$i] = 34;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_level'];
			}
			if(isset($operation['search_location']) && $operation['search_location']!=''){
				$data['vis_main_search'.$i] = 35;
				$data['vis_sub_search'.$i] = 0;
				$data['vis_search_text'.$i++] = $operation['search_location'];
			}
			$data['total_critaria'] = --$i;			
			$filter_id = $ticket_object->set_filter($data, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$operation['vis_filter_id'] = $filter_id;            
		}
        if(isset($operation['vis_filter_enable']) && $operation['vis_filter_enable']==1){					
            echo json_encode( array('fid'=>$filter_id) );
        } else {
        //if(isset($operation['vis_filter_id']) && $operation['vis_filter_id'] != '')
            return $this->$operation['ticket_operation']($operation);
        }        
	}
	function save_filter($operation) {
        include(VIS_PATH_TEMPLATE.'save_filter.php');
        return true;
    }
    function search_detail($operation) {
        global $vis_language;
        $spliter=(strstr($operation['vis_action'], '/'))?'/':',';
        $action=explode($spliter, $operation['vis_action']);
        if(!isset($action[4]) || trim($action[4])=='') {
            $message=$vis_language['MSGFILTIDNTFND'];
            return false;
        }
        if(isset($action[4]) && $action[4]!='' && is_numeric($action[4])) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $ticket=new class_ticket($database);
        $client=new class_client($database);
        $setting=new class_setting($database);
        include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'client.php'); 
        $object_client = new client();
        $ticket_types=$this->get_properties('get_types', '');
        $domain_list=$object_client->get_domain_access_list();
        $user_groups=$client->get_client_group(' (domain_id in ('.$domain_list.') or domain_id=0 ) and is_enable=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $domains=$ticket->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1','','','', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $departments=$ticket->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
        $status=$this->get_properties('get_status', '');
        $priorities=$this->get_properties('get_priorities', '');
        $flags=$this->get_properties('get_flags', '');
        $owner=$this->get_properties('get_staff', '');
        list($sinfo, $sla)=$setting->get_sla(VIS_TABLE_PREFIX.'sla.is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $search_details=$ticket->get_search_detail('F.filter_id='.$action[4], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $search_details=$search_details[0];
        $criteria_detail=$ticket->get_search_criteria('FC.filter_id='.$action[4], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $lang_dt=$setting->get_language('is_enabled=1', '', 0, '', 0, VIS_LOCATION_AREA);
        list($info, $client_language)=$lang_dt;
		 $label_details=$this->get_properties('get_labels', ''); // label list 
		 $channel_details=$this->get_properties('get_channel', '');
		 $category_details=$this->get_properties('get_category', '');		
		 $subcategory_details=$this->get_properties('get_subcategory', '');
		 $item_details=$this->get_properties('get_item', '');
		 $level_details=$this->get_properties('get_level', '');
		 $location_details=$this->get_properties('get_location', '');
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'filter_update.php');
        return true;
	}
    }
    function update_filter($operation) {
        global $vis_language;
        $data=parse_form_array($operation['vis_action']); 
        if(!isset($data['vis_filter_title']) || $data['vis_filter_title']=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQFLDTIT'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database); 
								include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);
        $ret=$object->update_filter($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
								if($ret){
									$search_details=$object->get_search_detail('F.filter_id='.$data['vis_filter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
									$search_details=$search_details[0];
									 if($search_details['vscope']==1){
												if($search_details['is_report']==1){$msg='Update custom report -'.$search_details['filter_name']; $moduleid=12;}else{ $msg='Update custom filter -'.$search_details['filter_name']; $moduleid=13;}
												$setting_object->add_staff_activity_log($msg,VIS_STAFF_ID,$moduleid, VIS_LOCATION_AREA);	
												}
									}
        $database->database_disconnect();
		$operation['vis_current_operation']='view_filters';
		$operation['vis_current_module']='ticket';			
$operation['vis_is_report']=(isset($operation['vis_is_report']))?$operation['vis_is_report']:0;		 
        if(!$ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
elseif($operation['vis_is_report']==1){
		 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#global_menu").visExecution("load_area", {"vis_module":"home", "vis_operation":"load_global_menu"}); $("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTCUSTOM'].'",{"vis_module":"'.$operation['vis_current_module'].'", "vis_operation":"'.$operation['vis_current_operation'].'","custom_show_report":"7", "vis_action":"#/ticket/view_filters/'.$vis_language['TXTCUSTOM'].'/7"}); </script>';
		
     }  else {
		
		  echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#global_menu").visExecution("load_area", {"vis_module":"home", "vis_operation":"load_global_menu"}); $("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTFILTERS'].'",{"vis_module":"'.$operation['vis_current_module'].'", "vis_operation":"'.$operation['vis_current_operation'].'"}); </script>';}
        return true;
    }
    function new_comment($operation){
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		$vis_ticket_id=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
		$filter = 'ticket_id='.$vis_ticket_id.' order by receive_date desc limit 1';
		$recent_post=$ticket_object->get_tickets_posts($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$recent_post_id=$recent_post[0]['post_id'];
        include(VIS_PATH_TEMPLATE.'ticket_comment.php');
        return true;
	}
	function add_comment($operation){
		global $vis_language, $operation_hnd;
        if(isset($operation['vis_action'])) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
        if(trim($data['vis_comment'])=='') {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'");</script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $data['vis_comment']=nl2br($data['vis_comment']);
        $result = $ticket_object->add_comment($data, $operation['vis_post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);

		if($result){
			list($ticket_info, $ticket_details)=$ticket_object->get_ticket(' ticket_id='.$operation['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$ticket_object->add_audit_log($ticket_details[0], 35, '', '' , VIS_STAFF_ID,  VIS_LOCATION_AREA);
			if(VIS_GAMIFICATION_ACCESS == 1) 
            {
                     include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
                     $staff=new class_staff($database);
                     include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
                     $sett_obj=new class_setting($database);
                     $staff_info=$staff->get_staff('staff_id='.VIS_STAFF_ID, VIS_STAFF_ID, VIS_LOCATION_AREA);
                     $points = $sett_obj->calculate_points($staff_info[0],8,IS_STAFF_ID,VIS_LOCATION_AREA);  
            }
            if($result) $operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("hide");$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":"'.$operation['vis_ticket_id'].'"});</script>';
		}
		else{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
		}     
        $database->database_disconnect();   
        return $result;
	}
	function show_user_details($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        if(isset($operation['vis_post_id']) && $operation['vis_post_id']!=""){
            $user_details=$ticket_object->get_user_details($operation['vis_post_id'], $operation['vis_submitter'], $operation['vis_submitter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        } else if($operation['vis_submitter']==1){
             include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client_object=new class_client($database);
            $user_details=$client_object->get_client(VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_submitter_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $user_details=$user_details[1][0];
        } else {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
            $staff_object=new class_staff($database);
            $user_details=$staff_object->get_staff('staff_id='.$operation['vis_submitter_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $user_details=$user_details[0];
			$staff_gr_details = $staff_object->get_staff_group('group_id ='.$user_details['group_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			$user_details['group_name'] = $staff_gr_details[0]['group_name'];
        }
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);		       
		$module_setting=$sett_obj->get_module_setting('domain_id='.$user_details['domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(isset($operation['vis_task_id']) && $operation['vis_task_id']!=""){
			$details_txt='<div class="form-group"><div class="col-sm-12"><label>'.$vis_language['TXTNAME'].'</label><span class="link m-l-sm">'.$user_details['first_name'].' '.$user_details['last_name'].'</span></div></div>';
			$details_txt.='<div class="form-group"><div class="col-sm-12"><label>'.$vis_language['TXTEMAIL'].'</label><span class="link m-l-sm">'.$user_details['email'].'</span></div></div>';
			$details_txt.='<div class="form-group"><div class="col-sm-12"><label>'.$vis_language['TXTCONTACTNUMBER'].'</label><span class="link m-l-sm">'.$user_details['contact_number'].'</span></div></div>';
		}
		else
		{
			$details_txt='<div class="form-group"><div class="col-sm-12"><label>'.$vis_language['TXTEMAIL'].'</label><span class="link m-l-sm">'.$user_details['email'].'</span></div></div>';
			if ((isset($module_setting['vis_show_ip_addr']) && $module_setting['vis_show_ip_addr'] == 1 && isset($operation['vis_post_id']) && $operation['vis_post_id']!=" ") || !isset($module_setting['vis_show_ip_addr'])) {
				$details_txt.='<div class="form-group"><div class="col-sm-12 m-t-xs"><label>' . $vis_language['TXTIPADDRESS'] . '</label><span class="link m-l-sm">' . $user_details['ipaddress'] . '</span></div></div>';
			}
			 if ($user_details['parent_name'] == "") {
				$details_txt.='<div class="form-group"><div class="col-sm-12 m-t-xs"><label>'.(($operation['vis_submitter']!=1) ? $vis_language['TXTTEAM'] : $vis_language['TXTORGANIZATION']).'</label><span class="link m-l-sm">'.$user_details['group_name'].'</span></div></div>';
			}
			$details_txt.='<div class="form-group"><div class="col-sm-12 m-t-xs"><label>'.$vis_language['TXTCONTACTNUMBER'].'</label><span class="link m-l-sm">'.$user_details['contact_number'].'</span></div></div>';
			if ($user_details['parent_name'] != "") {
				$details_txt.='<div class="form-group"><div class="col-sm-12 m-t-xs"><label>'.$vis_language['TXTPARENT'].'</label><span class="link m-l-sm">'.$user_details['parent_name'].'</span><span class="link m-l-xs">< '.$user_details['parent_email'].' ></span></div></div>';
				$details_txt.='<div class="form-group"><div class="col-sm-12 m-t-xs"><label>'.(($operation['vis_submitter']!=1) ? $vis_language['TXTTEAM'] : $vis_language['TXTORGANIZATION']).'</label><span class="link m-l-sm">'.$user_details['group_name'].'</span></div></div>';
			}
		}
        echo $details_txt;
    }
    function show_split_ticket_post_form($operation) { // show split ticket post form/modal
						global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticket_details != -1){
									$operation['domain_id']=$ticket_details[0]['domain_id'];
									$operation['vis_client_id']=$ticket_details[0]['client_id'];
									$operation['vis_email_id']=$ticket_details[0]['email'];
									$operation['vis_channel']=$ticket_details[0]['channel_id'];
								}
								
        include(VIS_PATH_TEMPLATE.'split_ticket_post.php');
        return true;
    }
    function split_ticket_post($operation) { // process split ticket post
        global $vis_language;
								 $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_obj=new class_client($database);
								
        if(isset($operation['vis_action']) && isset($operation['vis_form']) && $operation['vis_form'] == "vis_split_ticket_post_form"){
            $data = parse_form_array($operation['vis_action']);
            if($data['vis_split_ticket_post'] == 2 && $data['vis_ticket_hash'] == ""){
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTENTERTICKETHASH'].'");</script>';
                return false;
            }
												
							if(isset($operation['vis_channel']) && $operation['vis_channel']!=0){$data['vis_channel']=$operation['vis_channel'];}
							if(isset($operation['domain_id'])){$data['domain_id']=$operation['domain_id'];}
						
												if(VIS_LOCATION_AREA == 2){
   $char=substr(trim($data['vis_new_ticket_list_client']), -1);
			if($char==','){
				$data['vis_new_ticket_list_client']=substr(trim($data['vis_new_ticket_list_client']), 0, -1);
			}
			if(strpos($data['vis_new_ticket_list_client'],',')){
				$email=explode(',', $data['vis_new_ticket_list_client']);
			}
			else $email[0]= $data['vis_new_ticket_list_client'];
	if(VIS_LOCATION_AREA == 2 && (($data['vis_channel']==1 || $data['vis_channel']==5 || $data['vis_channel']==7) ||($data['vis_channel']!=1 && $data['vis_new_ticket_list_client']==''))) {
				 foreach($email as $key=>$val){
							if(isset($val) || trim($val)!=''){
								list($message, $flag) = check_email_validation($val);
										if(!$flag){
												if(VIS_LOCATION_AREA == 2 && ($data['vis_channel']!=2 || $data['vis_channel']!=19 )) {
													echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGEMAILMISS'].'"); </script>';
													return false;
												} 
										}
								}				
    }
 }	
else if($data['vis_channel']==2 || $data['vis_channel']==19){ 
				 foreach($email as $key=>$val){
						if(isset($val) || trim($val)!=''){ 
							list($message, $flag) = check_email_validation($val);
								if($flag == 1) {
									echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCONTACTNOINVALIDEORMISSING'].'"); </script>';
									return false;
								}
						}
				}
}
else if(VIS_LOCATION_AREA == 2 && ($data['vis_channel']!=1 && $data['vis_channel']!=5 && $data['vis_channel']!=7 && $data['vis_channel']!=2 && $data['vis_channel']!=19 ) && $data['vis_new_ticket_list_client']!=''){ 
 foreach($email as $key=>$val){ 
					if(isset($val) || trim($val)!=''){
						list($message, $flag) =  check_email_validation($val);
							if($flag==1){
									$client_detail['vis_email']=$data['vis_new_ticket_list_client'];
								}
       }
					}
}

	if($data['vis_new_ticket_list_client']!='') 
								$emilclient_res=$client_obj->get_check_additionalemailclient('additional_email="'.$data['vis_new_ticket_list_client'].'"  and '.VIS_TABLE_PREFIX.'client.domain_id='.$data['domain_id'],' limit 0,1',VIS_CLIENT_ID, VIS_LOCATION_AREA);
				if($emilclient_res!=-1){
								$client_d=$emilclient_res;
				}else{
								$filterCon = (($data['vis_channel'] == 2 || $data['vis_channel'] == 19) && $isCallClientEmailvalid != 1 )?'contact_number="'.$data['vis_new_ticket_list_client'].'"':'email="'.$data['vis_new_ticket_list_client'].'" or user_name="'.$data['vis_new_ticket_list_client'].'"  or twitter_id="'.$data['vis_new_ticket_list_client'].'"';
								list($client_i, $client_d)=$client_obj->get_client($filterCon.' and '.VIS_TABLE_PREFIX.'client.domain_id='.$data['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				}
	
				if($client_d!=-1 && is_array($client_d)) {
								$data['vis_client'] = $client_d[0]['client_id'];
				}else {										
											if(defined('VIS_ADD_CLIENT_ACCESS') && VIS_ADD_CLIENT_ACCESS==0 && $data['vis_internal_ticket']!=1) {
											echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTCNTCLIENTAD'].'"); </script>';
											return false;
												}
											
						$c_arr=explode('@',$data['vis_new_ticket_list_client']);
						$insertclient=array();
						$insertclient['vis_email']=$data['vis_new_ticket_list_client'];
						$insertclient['vis_username']=$data['vis_new_ticket_list_client'];
						$insertclient['vis_firstname']=$c_arr[0];
						$insertclient['vis_domain']=$data['domain_id'];
						$insertclient['vis_channel']=$data['vis_channel'];
						$data['vis_client']=$client_obj->add_client($insertclient, VIS_STAFF_ID, VIS_LOCATION_AREA); 
						$data['vis_email']=$data['vis_new_ticket_list_client'];
			}

}
												
												
            $database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
			$ticket_object=new class_ticket($database);
			$total_post_count=$ticket_object->get_total_post_count($operation['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($total_post_count == 1){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGMORETHANONEREQFORSPLIT'].'");</script>';
				$database->database_disconnect();
                return false;
			}
            $new_data=array_merge($data, $operation);
            if($data['vis_split_ticket_post'] == 2){
                $ticket=$this->split_ticket_post_into_existing($new_data);				
            }else if($data['vis_split_ticket_post'] == 1){
				$this->split_ticket_post_into_new($new_data);
            }
        }        
    }
    function split_ticket_post_into_existing($data){
		global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		list($info, $ticket)=$ticket_object->get_ticket('ticket_hash="'.$data['vis_ticket_hash'].'"', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);		
		list($info, $oldticket)=$ticket_object->get_ticket('ticket_id="'.$data['vis_ticket_id'].'"', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticket != -1){
            $data['vis_ticket_id']=$data['old_ticket_id']=$ticket[0]['ticket_id'];
            $res=$ticket_object->update_postid_into_ticket($data, VIS_STAFF_ID, VIS_LOCATION_AREA);		
			$ticket_object->add_audit_log($oldticket[0], 26, '', $data['vis_ticket_hash'] , VIS_STAFF_ID, VIS_LOCATION_AREA);	
            $msg=($res) ? $vis_language['MSGSUCCOPRT'] : $vis_language['MSGERROPRT'];
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$msg.'"); $(".modal").modal("hide"); $("#vis_ticket_post_'.$data['vis_post_id'].'").remove();</script>';
        }
        else{
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['TXTENTERTICKETHASH'].'");</script>';
        }
		$database->database_disconnect();
		return true;
	}
    function split_ticket_post_into_new($data){
		global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'];
        list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticket_details != -1){
			$data['vis_domain']=$ticket_details[0]['domain_id'];
            $data['vis_channel']=$ticket_details[0]['channel_id'];
            $data['vis_spam']=$ticket_details[0]['is_ticket_spam'];
            $data['last_replier_id']=$ticket_details[0]['last_replier_id'];
            $data['vis_people']=$ticket_details[0]['people'];
            $data['vis_department']=$ticket_details[0]['department_id'];
            $data['vis_status']=$ticket_details[0]['status_id'];
            $data['vis_priority']=$ticket_details[0]['priority_id'];
            $data['vis_type']=$ticket_details[0]['type_id'];
            $data['vis_client']=(isset($data['vis_client']))?$data['vis_client']:$ticket_details[0]['client_id'];
            $data['vis_ticket_id']=$data['old_ticket_id']=$ticket_details[0]['ticket_id'];
            $data['owner']=$ticket_details[0]['owner'];
            $data['attachment_count']=$ticket_details[0]['attachment_count'];
           //$data['vis_from_email']=(isset($data['vis_email']) && $data['vis_email']!='')?$data['vis_email']:$ticket_details[0]['recipients'];
											$data['vis_from_email']=$data['vis_email'];
												//$data['vis_sla_id']=$ticket_details[0]['slaplan_id'];
											
												
            $res=$ticket_object->add_ticket($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
			list($info, $newticket)=$ticket_object->get_ticket('ticket_id="'.$res.'"', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$ticket_object->add_audit_log($ticket_details[0], 26, '', $newticket[0]['ticket_hash'] , VIS_STAFF_ID, VIS_LOCATION_AREA);	
			/*if($res){
				$result=$ticket_object->set_ticket_property('sla', $data['vis_sla_id'], $res, VIS_STAFF_ID, VIS_LOCATION_AREA);
			}*/
            $msg=($res) ? $vis_language['MSGSUCCOPRT'] : $vis_language['MSGERROPRT'];
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$msg.'"); $(".modal").modal("hide"); $("#vis_ticket_post_'.$data['vis_post_id'].'").remove();</script>';
        }
		$database->database_disconnect();
		return true;
    }

    function confirm_delete_link($operation){
		global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETELINK'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
		$message_info['vis_event'] = "$(this).visExecution('submit_form', {'vis_module':'ticket', 'vis_operation':'delete_ticket_link', 'vis_ticket_id':".$operation['vis_ticket_id'].", 'vis_del_id':".$operation['vis_del_id'].", 'vis_link_id':".$operation['vis_link_id'].", 'vis_del_type':'".$operation['vis_del_type']."' });";
		include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
	}
	function delete_ticket_link($operation){
		global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $result = $ticket_object->delete_ticket_link($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($result) {
            $link_data=array('vis_ticket_id'=>$operation['vis_ticket_id'], 'case'=>1);	
            $link_details=$ticket_object->get_ticket_link($link_data,VIS_STAFF_ID, VIS_LOCATION_AREA);
            $link_count=($link_details!=-1)?count($link_details):0;
            list($info, $ticket_from)=$ticket_object->get_ticket('ticket_id="'.$operation['vis_ticket_id'].'"', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
            list($info, $ticket_to)=$ticket_object->get_ticket('ticket_id="'.$operation['vis_del_id'].'"', 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
            $ticket_object->add_audit_log($ticket_from[0], 28, $ticket_to[0]['ticket_hash'], $ticket_from[0]['ticket_hash'] , VIS_STAFF_ID, VIS_LOCATION_AREA);	
			if($link_count==0)
			{
				echo '<script>$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"ticket_details", "vis_ticket_id":"'.$operation['vis_ticket_id'].'"});</script>';
			}
			else {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';			
				echo '$("#vis_details_list_'.$operation['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_ticket_id":'.$operation['vis_ticket_id'].', "vis_action":"link"});set_active_tab("link");';
				echo ' </script>';
			}
		}
		else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';		
        $database->database_disconnect();
        return $result;
	}
	function get_link_tickets($operation) {
        include(VIS_PATH_TEMPLATE.'ticket_link.php');
        return true;
    }
    function link_ticket_hash($operation){
		global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        if(!(isset($data['vis_ticket_id']) && is_numeric($data['vis_ticket_id']) && isset($data['vis_ticket_hash']) && $data['vis_ticket_hash']!='')) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTICKHASHLINK'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);        
        $list_chk[0]=$data['vis_ticket_id'];
		list($info, $oticket)=$ticket_object->get_ticket('ticket_id="'.$data['vis_ticket_id'].'"', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        list($info, $ticket)=$ticket_object->get_ticket('ticket_hash="'.$data['vis_ticket_hash'].'"', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ticket == -1 || $data['vis_ticket_id']==$ticket[0]['ticket_id']){
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGTICKHASHLINKERROR'].'"); </script>';
            return false;
		}   
		$data['vis_parent_ticket_id']=$data['vis_ticket_id'];
		//$ticket_ids=array($data['vis_ticket_id'],$ticket[0]['ticket_id']);
		$ticket_ids=$ticket[0]['ticket_id'];
		$ret=$ticket_object->set_ticket_property('link', $data, $ticket_ids, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$ticket_object->add_audit_log($ticket[0], 24, $oticket[0]['ticket_hash'], $ticket[0]['ticket_hash'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_object->add_audit_log($oticket[0], 24, $ticket[0]['ticket_hash'], $oticket[0]['ticket_hash'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		
        if($ret) {
            echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("hide");$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_area",{"vis_module":"ticket", "vis_operation":"get_details", "vis_ticket_id":'.$data['vis_ticket_id'].', "vis_action":"link"});set_active_tab("link");</script>';
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        
		if(VIS_LOCATION_AREA !=4){
		 	$database->database_disconnect();
		 }
        return true;
	}
		
	function link_tickets($operation) {
        global $vis_language, $operation_hnd;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);  
        $options=explode('&',$operation['vis_action']);
        $list_chk=array();
		$flag=0;
        foreach($options as $postdata) {
            $action=explode('=', $postdata);
			if(preg_match('/vis_ticket_mass_chk_[0-9]/', $action[0]))
                $list_chk[]=$action[1];
			
			if(preg_match('/vis_parent_ticket_id/', $action[0]))
                $data['vis_parent_ticket_id']=$flag=$action[1];
            
			if(preg_match('/vis_link_type/', $action[0]))
                $data['vis_link_type']=$action[1];
			
			if(preg_match('/vis_filter_id/', $action[0]))
				$filter_id=$action[1];
        }
        if($flag!=0){
            $temp= array();
            for($i=0;$i<count($list_chk);$i++)	if($list_chk[$i]!=$flag) $temp[]=$list_chk[$i];
            $list_chk=$temp;
        }
        $ret=$ticket_object->set_ticket_property('link', $data, $list_chk, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($ret) {
            echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("hide");$("[id^=\'vis_ticket_mass_chk_\']").attr("checked",false);';
			echo "$('#vis_workpanel_div').visExecution('load_area', {'vis_module':'ticket', 'vis_operation':'filter_ticket','vis_filter_id':'".$filter_id."'});</script>";
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        $database->database_disconnect();
        return true;
    }
	
	function get_tickets_link($operation){
        global $vis_language;
        $database=new class_database();
        $list_chk=explode(",",$operation['vis_ticket_id']);
        $chk_count=count($list_chk);
		if($chk_count<2)
        {
			  echo '<script>$(".modal").modal("hide");$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNGLTKTLINK'].'"); </script>';
			  return false;
		}
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $ticket_list=$object->get_ticket('ticket_id in ('.$operation['vis_ticket_id'].')', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_list=$ticket_list[1];
        $title=$vis_language['TXTLINKTICKET'];
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'link_tickets.php');
        return true;
    }
	
	function get_remaining_tickets_link($operation){
        global $vis_language;
        $database=new class_database();
        $list_chk=explode(",",$operation['vis_ticket_list']);
        for($j=0;$j<count($list_chk);$j++){
			if($list_chk[$j]==$operation['vis_ticket_id'])
				unset($list_chk[$j]);
		}
		$operation['vis_ticket_list']=implode(",",$list_chk);

        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $ticket_list=$object->get_ticket('ticket_id in ('.$operation['vis_ticket_list'].')', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_list=$ticket_list[1];
       
	   $html='<table class="table table-hover b-t b-light m-b-none"><thead class="table_head"><tr><th>'.$vis_language['TXTTICKETHASH'].'</th><th>'.$vis_language['TXTSUBJECT'].'</th></tr></thead><tbody>';
		
		for($i=0;$i<count($ticket_list);$i++) {
			$html.='<tr><td><a href="#/ticket/ticket_details/'.$ticket_list[$i]['ticket_hash'].'/'.$ticket_list[$i]['ticket_id'].'" class="link">'.$ticket_list[$i]['ticket_hash'].'</a></td><td>'.$ticket_list[$i]['subject'].'</td></tr>';
		}
		$html.='</tbody></table>';
		echo $html;
    }
	
    function lock_ticket($operation){ 
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $ticket_lock = $ticket_object->lock_ticket($operation['vis_ticket_id'], $operation['vis_action'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($ticket_lock){
            $lock_icon_class = $title = $lock_status = "";
            if($operation['vis_action'] == 'lock'){
                $lock_icon_class = "vh-lock";
                $lock_status = 0;
                $title = $vis_language['TXTLOCKED'];
            } else {
                $lock_icon_class =  "vh-unlock";
                $lock_status = 1;
                $title = $vis_language['TXTUNLOCKED'];
            }
            echo '<script>$("#vis_lock_ticket_'.$operation['vis_ticket_id'].'").html(\'<div title="'.$title.'" class="btn btn-default btn-sm" onclick="lock_ticket('.$operation['vis_ticket_id'].', '.$lock_status.');"><i class="vh '.$lock_icon_class.' vh-lg"></i></div>\');</script>';
        } else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
    }
    function confirm_delete_comment($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELCOMMENT'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_comment', 'vis_remark_id':".$operation['vis_remark_id'].", 'vis_ticket_id':".$operation['vis_ticket_id']."});";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_comment($operation) {
        global $vis_language;
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object = new class_ticket($database);
        $result = $object->delete_comment($operation['vis_remark_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(VIS_LOCATION_AREA==0) {
            echo ($result)?'success':'error';
        }
        else {
            if($result) {
				list($ticket_info, $ticket_details)=$object->get_ticket(' ticket_id='.$operation['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$object->add_audit_log($ticket_details[0], 36, '', '' , VIS_STAFF_ID,  VIS_LOCATION_AREA);
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
                echo '$("#vis_ticket_post_comment_area_'.$operation['vis_remark_id'].'").remove();';
                echo '</script>';
            }
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
        }
        $database->database_disconnect();
        return $result;
    } 
    
    function show_custom_fields($location, $parent_id, $department_id, $database) {
        global $vis_language;
        $custom_field_var='';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object = new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object = new class_ticket($database);
        if($location[0] == 4)
        {
			$filter=' location='.$location[0].' and customgroup_id = '.$location[1].' and is_enabled=1 ';
		}
		else
		{
			$filter=' (location='.$location[0].' or location='.$location[1].' or location=3 ) and (department_access=0 or find_in_set('.$department_id.', department_access)) and is_enabled=1 ';
		}
        $custom_group = $setting_object->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($custom_group != -1)
        {
			if($location[0] == 4)
			{
				$custom_field_var .='<table cellpadding="5" cellspacing="3" width="100%" cellspacing="0" style="border:1px solid #ddd;;color:#788288;"><tr><td style="background-color:#d9edf7;" colspan="3" width="68%"><strong>'.$vis_language['TXTSURVEYDETAILS'].'</strong></td><td style="background-color:#d9edf7;" colspan="3" width="32%"><strong>'.$vis_language['TXTSURVEYDATE'].'</strong>   : '.$location[3].'</td></tr>';
			}
			else
			{
				$custom_field_var .='<table cellpadding="5" cellspacing="3" width="100%" cellspacing="0" style="border:1px solid #ddd;;color:#788288;"><tr><td style="background-color:#eee;" colspan="3"><strong>'.$vis_language['TXTCUSTOMFIELDS'].'</strong></td></tr>';
			}
            for($i=0; $i<count($custom_group); $i++)
            {
                $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$i]['customgroup_id'].'';
                list($custom_field_info, $custom_fields_details)=$setting_object->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                
                if($custom_fields_details != -1)
                {
					if($location[0] != 4)
					{
						$custom_field_var .='<tr><td style="border-bottom:1px dashed #ddd;" colspan="3" width="100%"><div style="color:#777; font-size:28px;"><strong>'.$custom_group[$i]['customgroup_name'].'</strong></div></td></tr>';
					}
                    for($j=0; $j<count($custom_fields_details); $j++)
                    {  
                        $val='';
                        if($custom_fields_details[$j]['field_type']<4 || $custom_fields_details[$j]['field_type']==8)
                        {
                            $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                            if($custom_data != -1)  $val = $custom_data['content'];
                            else $val = $custom_fields_details[$j]['default_value'];
                            $req = ($custom_fields_details[$j]['is_required']==1)?' *':'';
                            if($custom_fields_details[$j]['field_type']==1){
                              
                                  if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                  {   
                                      $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td> '.$val.'</td></tr>';
                                  }
                                  else
                                  { 
                                      if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {             
                                             $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td >'.$val.'</td></tr>';
                                      }                               
                                      else
                                      {

                                             $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>';
                                      }
                                  }
                            }
                            if($custom_fields_details[$j]['field_type']==2)
                            {
                                 if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                 {
                                    if($val != '') $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>';
                                 }
                                 else
                                 {
                                      if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {             
                                           $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>'; 
                                      }
                                      else
                                      {
                                          $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>'; 
                                      }
                                 }
                            }
                            if( $custom_fields_details[$j]['field_type']==3){
                                if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                {
                                    if($val != '')$custom_field_var.= '<tr><td width="25%"> <div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>';
                                }
                                else
                                {
                                     if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {             
                                            $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>'; 
                                
                                      }
                                      else
                                      {
                                              $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.$val.'</td></tr>'; 
                                      }
                                }
                            }
                            if( $custom_fields_details[$j]['field_type']==8){
                                if($location[0] == 3  && VIS_LOCATION_AREA == 2)    
                                {
                                    if($val != '')$custom_field_var.= '<tr><td width="25%"> <div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.format_datetime(strtotime($val)).'</td></tr>';
                                }
                                else
                                {
                                     if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                      {             
                                            $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.format_datetime(strtotime($val)).'</td></tr>'; 
                                
                                      }
                                      else
                                      {
                                              $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.$custom_fields_details[$j]['field_name'].'</strong></div></td><td width="5%">:</td><td>'.format_datetime(strtotime($val)).'</td></tr>'; 
                                      }
                                }
                            }
                           
                        }
                        else
                        {
                           
                            $filter='field_group='.$custom_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA,'edit_page');
							
							
							 list($sub_customfield_info_lang ,$sub_customfields_details_lang)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                        
                                if($sub_customfields_details != -1)
                                {
                                    if(($location[0] == 3  && VIS_LOCATION_AREA == 2 ))          
                                    {
                                        if($custom_fields_details[$j]['field_type']==4)
                                        {   
                                            $custom_field_check_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></strong></div></td><td width="5%">:</td><td>';
                                            for($k=0;$k< count($sub_customfields_details);$k++)
                                            {
                                                  $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                                  if($custom_data != -1)
                                                  {   
                                                         $vis_check[$k] = 1; 
                                                  }
                                                  if($custom_data['content'] === $sub_customfields_details[$k]['default_value'])$custom_field_check_var.=$sub_customfields_details_lang[$k]['default_value'];
                                            }
                                            $custom_field_check_var .= '</td></tr>';
                                            if(count($vis_check) > 0) $custom_field_var .= $custom_field_check_var ;          
                                            
                                        }
                                        if($custom_fields_details[$j]['field_type']==5)
                                        {
                                            
                                            $custom_field_radio_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';

                                            for($k=0;$k<count($sub_customfields_details);$k++)
                                            {
                                              $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                                if($custom_data != -1)
                                                {
                                                    $radio[$k] = 1;
                                                }
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value'])$custom_field_radio_var.=$sub_customfields_details_lang[$k]['default_value'];
                                                   
                                                $cc_count++;
                                            }
                                           
                                             $custom_field_radio_var .= '</td></tr>';  
                                             if(count($radio) > 0) $custom_field_var  .=$custom_field_radio_var ;
                                        }
                                        if($custom_fields_details[$j]['field_type']==6)
                                        {
                                            
                                            $custom_field_select_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                                if($custom_data != -1)
                                                {
                                                    $vis_select[$k] = 1;
                                                }
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value'])$custom_field_select_var.=addslashes($sub_customfields_details_lang[$k]['default_value']);
                                            }
                                            
                                            $custom_field_select_var.='</td></tr>';
                                            if(count($vis_select) > 0 ) $custom_field_var  .= $custom_field_select_var ;  
                                            $cc_count++;
                                        }
                                        if($custom_fields_details[$j]['field_type']==7)
                                        { 
                                           $custom_field_mulvar.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';
                                                for($k=0;$k<count($sub_customfields_details);$k++) 
                                                {
                                                    $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']); 
                                                    if($custom_data != -1)
                                                    {
                                                         $vis_multiple[$k] = 1;         
                                                    }
                                                    if($custom_data['content'] == $sub_customfields_details[$k]['default_value'])  $custom_field_mulvar.=addslashes($sub_customfields_details_lang[$k]['default_value']);
                                                } 
                                             $custom_field_var.='</td></tr>';
                                             if(count($vis_multiple) > 0 ) $custom_field_var  .= $custom_field_mulvar ;  
                                             $cc_count++;   
                                        }
                                      
                                    }  
                                    else
                                    {    
                                        $flag = array();   
                                        if($custom_fields_details[$j]['field_type']==4)
                                        {
                                            $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';
                                            for($cnt=0;$cnt<count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }
                                            for($k=0;$k< count($sub_customfields_details);$k++)
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);   
                                                if($custom_data['content'] === $sub_customfields_details[$k]['default_value'])
                                                {  
                                                    $sel = $custom_field_var.=$sub_customfields_details_lang[$k]['default_value'].' ';
												}
                                                $cc_count++;
                                            }
                                            $custom_field_var .= '</td></tr>';
                                        }
                                        if($custom_fields_details[$j]['field_type']==5)
                                        {
                                            $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';
                                            for($k=0;$k<count($sub_customfields_details);$k++)
                                            {
                                              $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                                if($custom_data!= -1) 
                                                {
                                                    $flag[$k] = 1;
                                                    $custom_field_var.=addslashes($sub_customfields_details_lang[$k]['default_value']);
                                                }
                                              
                                               $cc_count++;
                                            }
                                            $custom_field_var .= '</td></tr>';
                                        }
                                        if($custom_fields_details[$j]['field_type']==6)
                                        {    
                                            $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value']) 

                                                {
                                                    $custom_field_var.= addslashes($sub_customfields_details_lang[$k]['default_value']).' ';  
                                                }
                                               
                                            }
                                            $custom_field_var.='</td></tr>';
                                            $cc_count++;
                                        }
                                        if($custom_fields_details[$j]['field_type']==7)
                                        { 
                                            if($sub_customfields_details[$k]['is_selected'] == 1 )$selDefault = 'selected="selected"';    
                                            $custom_field_var.='<tr><td width="25%"><div style="color:#666;"><strong>'.addslashes($custom_fields_details[$j]['field_name']).'</strong></div></td><td width="5%">:</td><td>';
                                           
                                            for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);   
                                                if($custom_data['content']== $sub_customfields_details[$k]['default_value']  ) 
                                                {
													  $custom_field_var.=addslashes($sub_customfields_details_lang[$k]['default_value']).' '; 
												}
                                                if(count($flag) <= 0 && $sub_customfields_details[$k]['is_selected'] == 1) $custom_field_var.=addslashes($sub_customfields_details[$k]['default_value']).' ';
                                            }
                                            $custom_field_var.='</td></tr>';
                                            $cc_count++;
                                        }
                                    }
                                }
                            }
                       }
                    
                }
            }
            if($custom_field_var!='')
            {
                $custom_field_var.='</table><br>';   
            }
        }
        return $custom_field_var;
       }
       
    function load_lists($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff_object=new class_staff($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
        $staff_access=$staff_object->get_staff('staff_id='.VIS_STAFF_ID,VIS_STAFF_ID, VIS_LOCATION_AREA);
        $staff_department=$staff_access[0]['department_access'];
         if($staff_department==-2)
        {
			$tempfilter = VIS_TABLE_PREFIX.'staff_group.group_id = '.VIS_TABLE_PREFIX.'staff.group_id and '.VIS_TABLE_PREFIX.'staff_group.group_id='.$staff_access[0]['group_id'].' and '.VIS_TABLE_PREFIX.'staff.staff_id='.VIS_STAFF_ID;
			list($staffgroup_info, $staff_group)=$setting_object->get_staffgroup_ofstaff($tempfilter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($staffgroup_info['department_access']==0)
			$staff_department_array=$staffgroup_info['department_access'];
			else
			$staff_department_array=explode(',', $staffgroup_info['department_access']);
		}
		else
		{
			$staff_department_array=explode(',', $staff_department);
		}
        switch($operation['vis_action']) {
            case 'department':
                if(defined('VIS_ANY_DEPT') && VIS_ANY_DEPT==1)
                {
					/*if($staff_department_array[0]==0 || $staff_department_array==0)
					{*/
						$dept_list = $ticket_object->get_all_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$operation['vis_domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA, VIS_TABLE_PREFIX.'domain.domain_id');
					/*}
					else
					{
						$dept=array();
						$domain_access=array();
						for($i=0;$i<count($staff_department_array); $i++)
						{
							include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'subsetting.php');
							$sub_object=new class_subsetting($database);
							$department=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$operation['vis_domain_id'].' and '.VIS_TABLE_PREFIX.'department.department_id='.$staff_department_array[$i], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
							$dept[]=$department[0];
						}
						for($i=0;$i<count($dept); $i++)
						{
							if($dept[$i]!='')
							$department_access[]=$dept[$i]['department_id'];
						}
						$department_access=array_unique($department_access);
						$department_access=implode(',', $department_access);
						if(substr($department_access, -1)==',') $department_access=substr($department_access,0,-1);
						$dept_list=$ticket_object->get_all_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id in ('.$department_access.')',VIS_STAFF_ID, VIS_LOCATION_AREA);
					}*/  
				}
                else $dept_list = $ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$operation['vis_domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA, VIS_TABLE_PREFIX.'domain.domain_id');
                $txt = $domain_id = $return_value = $select_dept_txt =''; 
				for($i=0;$i<count($dept_list);$i++) {
					$selected ='';
					if($domain_id=="" || ($domain_id != "" && $domain_id != $dept_list[$i]['domain_id'])){
						$domain_id = $dept_list[$i]['domain_id'];
						if($i!=0) $return_value .= '</optgroup>';
					}
					if($operation['vis_selected_id']==$dept_list[$i]['department_id']){
						$selected = "selected='selected'";
						$select_dept_txt = $dept_list[$i]['domain_name'] .' : '. $dept_list[$i]['department_name'];
					}
					$txt = $dept_list[$i]['domain_name']. ' : '. $dept_list[$i]['department_name'];
					$return_value .= '<option value="'.$dept_list[$i]['department_id'].'" '.$selected.'>'.$txt.'</option>';
				}	
				echo '<select id="departmentlist" name="department" class="selectpicker" data-selector-label="'.$select_dept_txt.'" onchange="update_properties(this.value,1);"'.((count($dept_list)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#department").removeClass("open");</script>';
            break;
            case 'status':
                $filter_condtn = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_dept_id'].', department_access))';
                $status_list = $ticket_object->get_status_list($filter_condtn, VIS_STAFF_ID, VIS_LOCATION_AREA);
                $select_txt=$return_value='';
                
                foreach($status_list as $status){ 
					$return_value.='<option style="color:'.$status['color'].';" '.(($status['status_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$status['status_id'].'">'.$status['status_name'].'</option>';
                    if($status['status_id']==$operation['vis_selected_id']) $select_txt = $status['status_name'];
				} 
			
				echo '<select id="statuslist" name="status" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,2);"'.((count($status_list)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#status").removeClass("open");</script>';
				
            break;
            case 'priority':
                $filter_condtn = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_dept_id'].', department_access))';
                $priority_list = $ticket_object->get_priorities_list($userid, VIS_LOCATION_AREA, $filter_condtn);
                $select_txt=$return_value='';
                foreach($priority_list as $priority){ 
					$return_value.='<option style="color:'.$priority['color'].';" '.(($priority['priority_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$priority['priority_id'].'">'.$priority['priority_name'].'</option>';
                    if($priority['priority_id']==$operation['vis_selected_id']) $select_txt = $priority['priority_name'];
				} 
				echo '<select id="prioritylist" name="priority" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,3);"'.((count($priority_list)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#priority").removeClass("open");</script>';
            break;
            case 'type':
                $filter_condtn = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_dept_id'].', department_access))';
                $type_list = $ticket_object->get_type_list($userid, VIS_LOCATION_AREA, $filter_condtn);
                $select_txt=$return_value='';
                foreach($type_list as $type){ 
					$return_value.='<option '.(($type['type_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$type['type_id'].'">'.$type['type_name'].'</option>';
                    if($type['type_id']==$operation['vis_selected_id']) $select_txt = $type['type_name'];
				} 
				echo '<select id="typelist" name="type" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,4);"'.((count($type_list)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#type").removeClass("open");</script>';
            break;
            case 'flag':
                $filter_condtn = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_dept_id'].', department_access))';
                $flag_list=$ticket_object->get_flags_list(VIS_STAFF_ID, VIS_LOCATION_AREA, $filter_condtn);
                $flag='flag';
                include_once(VIS_PATH_TEMPLATE.'ticket_properties.php');
            break;
            case 'owner':
                include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
                $staff_object=new class_staff($database);                   
                $filter=VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$operation['vis_ticket_id'];
                $owner_details=$ticket_object->get_ticket_owner($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
                $ownerids=array();
                $subfilter='';
                if($owner_details!=-1) for($i=0;$i<count($owner_details);$i++){
                    $ownerids[$i].=$owner_details[$i]['staff_id'];
                }
                if($ownerids!=-1 && count($ownerids)>0) $subfilter=' or staff_id in ('.implode(',',$ownerids).') ';
                $staff_list = $staff_object->get_staff('is_enabled=1'.$subfilter.' order by first_name ASC',VIS_STAFF_ID, VIS_LOCATION_AREA, $operation['vis_department_id']);                
                $flag='owner';
				if(VIS_LOCATION_AREA==0) {
                        echo get_xml($staff_list, 'staff_list');
                        return true;
				} else {
					include_once(VIS_PATH_TEMPLATE.'ticket_properties.php');
				}
            break;
            case 'level':
                $filter_condtn = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_dept_id'].', department_access))';
                list($ticket_level_count, $level_list)=$setting_object->get_ticket_level_list( $filter_condtn,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
                $select_txt=$return_value='';
				if($operation['vis_selected_id']==0 || $ticket_item == -1){
					$return_value ='<option selected="selected" value="0">'.$vis_language['TXTSELECT'].'</option>';
				}
				else $return_value .='<option value="0">'.$vis_language['TXTSELECT'].'</option>';
				if($operation['vis_selected_id']==0) $select_txt = $vis_language['TXTSELECT'];
                foreach($level_list as $level){ 
					$return_value.='<option '.(($level['level_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$level['level_id'].'">'.$level['title'].'</option>';
                    if($level['level_id']==$operation['vis_selected_id']) $select_txt = $level['title'];
				} 
				echo '<select id="typelist" name="level" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,6);"'.((count($level_list)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#level").removeClass("open");</script>';
            break;
            case 'ticket_category':
                $filter_condtn = 'is_enabled=1 and (department_access=0 or find_in_set('.$operation['vis_dept_id'].', department_access))';
				list($ticket_cat_count,$ticket_category)=$setting_object->get_ticket_category_list($filter_condtn,'',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
                $select_txt=$return_value='';
				if($operation['vis_selected_id']==0 || $ticket_subcateogy == -1){
					$return_value ='<option selected="selected" value="0">'.$vis_language['TXTSELECT'].'</option>';
				}
				else $return_value .='<option value="0">'.$vis_language['TXTSELECT'].'</option>';
				if($operation['vis_selected_id']==0) $select_txt = $vis_language['TXTSELECT'];
                foreach($ticket_category as $category){ 
					$return_value.='<option '.(($category['category_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$category['category_id'].'">'.$category['title'].'</option>';
                    if($category['category_id']==$operation['vis_selected_id']) $select_txt = $category['title'];
				} 
				echo '<select id="ticket_category" name="ticket_category" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,7);"'.((count($ticket_category)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#ticket_category").removeClass("open");</script>';
            break;
            case 'ticket_subcateogy':
                $filter_condtn = VIS_TABLE_PREFIX.'ticket_subcategory.is_enabled=1 and '.VIS_TABLE_PREFIX.'ticket_subcategory.category_id='.$operation['vis_category_id'];
				list($ticket_cat_count,$ticket_subcateogy)=$setting_object->get_ticket_subcategory_list($filter_condtn,'',VIS_STAFF_ID, VIS_LOCATION_AREA,'');
                $select_txt=$return_value='';
				if($operation['vis_selected_id']==0 || $ticket_subcateogy == -1){
					$return_value ='<option selected="selected" value="0">'.$vis_language['TXTSELECT'].'</option>';
				}
				else $return_value .='<option value="0">'.$vis_language['TXTSELECT'].'</option>';
				if($operation['vis_selected_id']==0) $select_txt = $vis_language['TXTSELECT'];
                foreach($ticket_subcateogy as $subcategory){ 
					$return_value.='<option '.(($subcategory['subcategory_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$subcategory['subcategory_id'].'">'.$subcategory['title'].'</option>';
                    if($subcategory['subcategory_id']==$operation['vis_selected_id']) $select_txt = $subcategory['title'];
				} 
				echo '<select id="ticket_subcateogy" name="ticket_subcateogy" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,8);"'.((count($ticket_subcateogy)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#ticket_subcateogy").removeClass("open");</script>';
            break;
            case 'ticket_item':
                $filter_condtn = VIS_TABLE_PREFIX.'ticket_item.subcategory_id='.$operation['vis_subcategory_id'];
				list($ticket_cat_count,$ticket_item)=$setting_object->get_ticket_item_list($filter_condtn,'',VIS_STAFF_ID, VIS_LOCATION_AREA,'');
                $select_txt=$return_value='';
				if($operation['vis_selected_id']==0 || $ticket_item == -1){
					$return_value ='<option selected="selected" value="0">'.$vis_language['TXTSELECT'].'</option>';
				}
				else $return_value .='<option value="0">'.$vis_language['TXTSELECT'].'</option>';
				if($operation['vis_selected_id']==0) $select_txt = $vis_language['TXTSELECT'];
				
                foreach($ticket_item as $subcategory){ 
					$return_value.='<option '.(($subcategory['item_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$subcategory['item_id'].'">'.$subcategory['title'].'</option>';
                    if($subcategory['item_id']==$operation['vis_selected_id']) $select_txt = $subcategory['title'];
				}
				
				echo '<select id="ticket_item" name="ticket_item" class="selectpicker" data-selector-label="'.$select_txt.'" onchange="update_properties(this.value,9);"'.((count($ticket_item)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#ticket_item").removeClass("open");</script>';
            break;
            case 'assets_location':
				$location_assets=$setting_object->get_locations(" AND (".VIS_TABLE_PREFIX."itil_location.department_access = 0 OR FIND_IN_SET(".$operation['vis_dept_id'].", ".VIS_TABLE_PREFIX."itil_location.department_access)>0)",0, -1, '', VIS_STAFF_ID);
                $select_txt=$return_value='';
				function vis_show_subcategories($location_assets,$call=NULL,$operation) {
				global $vis_language;
				if($call==NULL || $call==''){
					if($operation['vis_selected_id']==0 || $ticket_item == -1){
					$return_value ='<option selected="selected" value="0">'.$vis_language['TXTSELECT'].'</option>';
					}
					else $return_value ='<option value="0">'.$vis_language['TXTSELECT'].'</option>';
				}
				if($operation['vis_selected_id']==0) $select_txt = $vis_language['TXTSELECT'];//echo "<pre>$location_assets===";print_r($location_assets);
         		    foreach($location_assets as $location){ 
						$return_value .='<option '.(($location['location_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$location['location_id'].'">'.$location['name'].'</option>';
								if($location['location_id']==$operation['vis_selected_id']) $select_txt = $location['name'];
							if(isset($location['subcat']) && $location['subcat']!=NULL) { 
								
								 $return_value .= vis_show_subcategories($location['subcat'],'sub_cat',$operation); 
							}
					}
					echo '<script>$("#assets_location").attr("data-selector-label","'.$select_txt.'");</script>';
					return $return_value;
				}
				$return_value = vis_show_subcategories($location_assets,'',$operation);
               /* foreach($location_assets as $location){ 
					$return_value.='<option '.(($location['location_id']==$operation['vis_selected_id'])?'selected="selected"':"").' value="'.$location['location_id'].'">'.$location['name'].'</option>';
                    if($location['location_id']==$operation['vis_selected_id']) $select_txt = $location['name'];
				}*/ 
				echo '<select id="assets_location" name="assets_location" class="selectpicker" onchange="update_properties(this.value,10);"'.((count($assets_location)>10)?' data-live-search="true"':'').'>'.$return_value.'</select><script>$("#assets_location").removeClass("open");</script>';
            break;
        }
        return true;
    }
    function get_custom_fields_values($location, $type, $department_id, $parent_id, $database){

     
        $custom_field_var='';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object = new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object = new class_ticket($database);
		$both_view = ($location[0]==1 || $location[0] == 2)? ' OR location=11 ' : '';
        if($location[0] == 4)
        {
			$filter=' location='.$location[0].' and customgroup_id = '.$location[1].' and is_enabled=1 ';
		}
		else
		{
			$filter=' (location='.$location[0].$both_view.' ) and (department_access=0 or find_in_set('.$department_id.', department_access)) and is_enabled=1 ';
		}
        $custom_group = $setting_object->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($custom_group != -1){
            for($i=0; $i<count($custom_group); $i++){
                $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$i]['customgroup_id'].'';
                list($custom_field_info, $custom_fields_details)=$setting_object->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                if($custom_fields_details != -1){
                    $cc_count=0;
                    for($j=0; $j<count($custom_fields_details); $j++){
                         $val='';   
                        if($custom_fields_details[$j]['field_type']<4 || $custom_fields_details[$j]['field_type']==8){
                            $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                            if($custom_data != -1)  $val = $custom_data['content'];
                            else $val = $custom_fields_details[$j]['default_value'];
                            $req = ($custom_fields_details[$j]['is_required']==1)?' *':'';
                            if($custom_fields_details[$j]['field_type']==1)
                            {
                                if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                }
                                else
                                {
                                     $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                }
                           }
                            if($custom_fields_details[$j]['field_type']==2)
                            {
                               if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                } 
                                else
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                }  
                            }
                            if( $custom_fields_details[$j]['field_type']==3)
                            {
                                if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                }
                                else
                                {
                                     $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                }  
                            }
                            if($custom_fields_details[$j]['field_type']==8)
                            {
                               if(($custom_fields_details[$j]['is_staff_editable'] == 1  &&  VIS_LOCATION_AREA == 2 ) || ($custom_fields_details[$j]['is_user_editable'] == 1 &&  VIS_LOCATION_AREA == 1))  
                                {
                                     $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label">'.$custom_fields_details[$j]['field_name'].$req.' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8"><label class="col-sm-2 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$val.'</label></div></div>';
                                }
                                  
                            }                          
                            $cc_count++;
                        }
                        else{
                             $flag = array();     
                            $filter='field_group='.$custom_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA,'edit_page');
							
							 list($sub_customfield_info_lang ,$sub_customfields_details_lang)=$setting_object->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
							
                            if($sub_customfields_details != -1){
                                if($custom_fields_details[$j]['field_type']==4){
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.addslashes($custom_fields_details[$j]['field_name']).' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8">';
                                    for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                    {
                                          $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                          if($custom_data != -1)  
                                          {
                                                     $flag[$cnt] =  1;
                                          }
                                    }
                                    for($k=0;$k< count($sub_customfields_details);$k++){
                                       $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);   
                                        if(($custom_data['content'] === $sub_customfields_details[$k]['default_value'])) $sel = 'checked="checked"';
                                        else if(count($flag) <= 0 &&  $sub_customfields_details[$k]['is_selected'] == 1)  $sel = 'checked="checked"';   
                                        else $sel='';
                                        if($sel!='')
                                        {
											$custom_field_var.= '<label class="col-sm-1 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$sub_customfields_details_lang[$k]['default_value'].'</label><br>';
										}
                                        $cc_count++;
                                    }
                                    $custom_field_var .= '</div></div>';
                                }
                                if($custom_fields_details[$j]['field_type']==5){
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.addslashes($custom_fields_details[$j]['field_name']).' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8">';
                                    for($k=0;$k<count($sub_customfields_details);$k++){
                                        $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
										
                                        if(($custom_data['content']== $sub_customfields_details[$k]['default_value']) || $sub_customfields_details[$k]['is_selected'] == 1) $sel = 'checked="checked"';
                                        else $sel='';
										if($sel!='')
                                        {
											$custom_field_var.= '<label class="col-sm-1 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$sub_customfields_details_lang[$k]['default_value']."</label>";
										}
										/*if($custom_data!=-1)
                                        {
											$custom_field_var.= '<label class="col-sm-1 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.$custom_data['content']."</label>";
										}*/
                                        $cc_count++;
                                    }
                                    $custom_field_var .= '</div></div>';
                                }
                                if($custom_fields_details[$j]['field_type']==6){
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.addslashes($custom_fields_details[$j]['field_name']).' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8">';
                                    for($k=0;$k<count($sub_customfields_details);$k++) {
                                         $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                        if(($custom_data['content']== $sub_customfields_details[$k]['default_value']) || $sub_customfields_details[$k]['is_selected'] == 1) $sel = 'selected="selected"';
                                        else $sel='';
                                        if($sel!='')
                                        {
											$custom_field_var.= '<label class="col-sm-1 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</label><br>';
										} 
                                    }
                                    
                                    $custom_field_var.='</div></div>';
                                    $cc_count++;
                                }
                                if($custom_fields_details[$j]['field_type']==7){
                                    $custom_field_var.='<div class="form-group"><label class="col-sm-4 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.addslashes($custom_fields_details[$j]['field_name']).' : <br/><i>'.$custom_fields_details[$j]['field_description'].'</i></label><div class="col-sm-8">';
                                    for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                    {
                                          $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);  
                                          if($custom_data != -1)  
                                          {
                                                     $flag[$cnt] =  1;
                                          }
                                    }
                                    for($k=0;$k<count($sub_customfields_details);$k++) {
                                        $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $parent_id, $custom_fields_details[$j]['field_type']);
                                        
                                        if(($custom_data['content']== $sub_customfields_details[$k]['default_value'])) {$sel = 'selected="selected"'; }
                                       
                                        else $sel=''; 
                                        if($sel!='')
                                        {
											$custom_field_var.= '<label class="col-sm-1 control-label" for="'.$custom_fields_details[$j]['field_name'].'">'.addslashes($sub_customfields_details_lang[$k]['default_value']).'</label><br>';
										}  
                                        if(count($flag) == 0 && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'selected="selected"'; 
                                    }
                                    $custom_field_var.='</div></div>';
                                    $cc_count++;
                                }
                            }
                        }
                    }
                }
                //else $custom_field_var='';
            }
        }
        else $custom_field_var='';
        return $custom_field_var;
    }
    
    function get_tickets_merge($operation){
        global $vis_language;
        $database=new class_database();
        $list_chk=explode(",",$operation['vis_ticket_id']);
        $chk_count=count($list_chk);
        if($chk_count<2)
        {
			  echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSNGLTKT'].'");$(".modal").modal("hide");</script>';
			  return false;
		}
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $ticket_list=$object->get_ticket('ticket_id in ('.$operation['vis_ticket_id'].')', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_list=$ticket_list[1];
        $title=$vis_language['TXTMERGETICKET'];
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'merge_tickets.php');
        return true;
    }
	    
    function get_channel_list($operation) {
        $database=new class_database();
        $dept=explode(':',$operation['vis_dept']);
        $filter='is_enabled=1 and (department_access=0 or find_in_set('.$dept[1].', department_access))';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $channels=$object->get_channel($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        $select='';
            $select .= '<select name="vis_channel" id="vis_channel" class="form-control input-sm selectpicker">';
			for($i=0;$i<count($channels);$i++)
				if($channels[$i]['channel_id']!=7){
					$select.='<option value="'.$channels[$i]['channel_id'].'">'.$channels[$i]['channel_name'].'</option>';
				}
            $select .= "</select>";
         echo json_encode( array('channels' => $select ));
        return true;
    }

	function get_ticket_tags_count($operation){
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		$ticket_label=$object->get_ticket_tag($operation['vis_ticket_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($ticket_label==-1)$tag_count=0; else $tag_count = count($ticket_label);
		echo $tag_count;
	}
	function get_ticket_participent_count($operation){
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
        $ticket_details=$object->get_ticket_peoples_recipient($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$recepients=explode(',', $ticket_details[0]['recipients']); $people=explode(',', $ticket_details[0]['people']);  
		if($people[0]=='')$people=0; else $people=count($people); if($recepients[0]=='')$recepients=''; else $recepients=count($recepients);
		echo $people+$recepients;
	}
    // function for load whmcs client details view
    function get_whmcs_details($operation) {
        include(VIS_PATH_TEMPLATE.'whmcs_client_details.php');
        return true;
    }
	function get_service_details($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting=new class_setting($database);
	    $filter2=VIS_TABLE_PREFIX."itil_service_item.item_id=".$operation['vis_service_item_id'];
	    $service_details=$setting->get_service_item_list($filter2,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
	    list($dpinf, $domain)=$setting->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$service_details[0]['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$filter = VIS_TABLE_PREFIX.'customfield.customgroup_id='.$service_details[0]['item_id'].' and '.VIS_TABLE_PREFIX.'customfield.ci_type=2 and '.VIS_TABLE_PREFIX.'customfield_data.parent_id='.$operation['vis_service_id'];
		$service_custom_details=$setting->get_service_custom_data($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		//echo VIS_LOCATION_AREA;
		//print_r($service_custom_details);die;
		$operation['ajax_area']='service';
		include(VIS_PATH_TEMPLATE.'ajax_ticket_attachment.php');
	}
	function get_ci_details($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
		$problem_object=new class_problem($database);
		$filter = " attach_type=0 AND parent_id=".$operation['vis_ticket_id'];
		list($total_ci, $assets_details)=$problem_object->get_attach_ci($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
					
		$database->database_disconnect();
		$operation['ajax_area']='CI';
		include(VIS_PATH_TEMPLATE.'ajax_ticket_attachment.php');		
	}
	function get_problem_details($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
		$problem_object=new class_problem($database);
		$filter7= VIS_TABLE_PREFIX.'itil_problems.problem_id='.$operation['vis_problem_id'];
		list($problems_info, $problems_details)=$problem_object->get_problems($filter7, $limit='', $page='', $sort_by='', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		$operation['ajax_area']='problem';
		include(VIS_PATH_TEMPLATE.'ajax_ticket_attachment.php');		
	}
	function get_changes_details($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'changes.php');
		$changes_object=new class_changes($database);
		$filter9= VIS_TABLE_PREFIX.'itil_changes.changes_id='.$operation['vis_changes_id'];
		list($changes_info, $changes_details)=$changes_object->get_changes($filter9, $limit='', $page='', $sort_by='', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		$operation['ajax_area']='changes';
		include(VIS_PATH_TEMPLATE.'ajax_ticket_attachment.php');		
	}
	function attach_ticket_task($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket=new class_ticket($database);
		$filter='parent_id='.$operation['vis_ticket_id'].' and attach_type=12';
		list($total_task, $attached_task)=$ticket->get_task_attached_ticket($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'attach_ticket_task.php');		
	}
	function get_task_details($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket=new class_ticket($database);
		$filter=VIS_TABLE_PREFIX.'itil_relation.parent_id='.$operation['vis_ticket_id'].' and attach_type=12';
		list($total_task, $attached_task)=$ticket->get_task_attached_ticket($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'ticket_attached_task_list.php');		
	}
	function add_ticket_task($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
		$ticket=new class_ticket($database);
		$problem=new class_problem($database);
		$data=parse_form_array($operation['vis_action']);
			
			if($data['total_attach_count']>0){
				$data['vis_attach_type']=12;
				$data['vis_parent_id']=$data['vis_ticket_id'];
				$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'];
				list($ticket_info, $ticket_details)=$ticket->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
				
				for($i=0;$i<$data['total_attach_count'];$i++){
					if(isset($data['vis_attach_id_'.$i])){
						$data['vis_child_id']=$data['vis_attach_id_'.$i];
						$ret=$problem->add_itil_relation($data,VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						$filter = " attach_type=12 AND child_id=".$data['vis_child_id']." AND parent_id=".$data['vis_ticket_id'];
						list($total_task, $attached_task)=$ticket->get_task_attached_ticket($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						$ticket->add_audit_log($ticket_details[0], 16, $attached_task[0]['task_title'],'', VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
				}
				if($ret){
					echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
					echo "$('#vis_details_list_".$data['vis_ticket_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':".$data['vis_ticket_id'].", 'vis_department_id':".$data['vis_dept_id'].", 'vis_readonly':1});$('.modal').modal('toggle');</script>";
					
				}else{
					 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
				}
			}
	}
	function get_delete_ticket_task($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDETACH'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'delete_ticket_task', 'vis_attach_type':'".$operation['vis_attach_type']."', 'vis_child_id':".$operation['vis_child_id'].", 'vis_parent_id':".$operation['vis_parent_id'].", 'vis_dept_id':".$operation['vis_dept_id']."});";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }
	function delete_ticket_task($operation) {
        global $vis_language;
		$database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket=new class_ticket($database);
		
        $result = $ticket->delete_ticket_task($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($result) {
			echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
			echo "$('#vis_details_list_".$operation['vis_parent_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':".$operation['vis_parent_id'].", 'vis_department_id':".$operation['vis_dept_id'].", 'vis_readonly':1});</script>";
		}
		else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
        return $result;
    }
   function load_view_list($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff_object=new class_staff($database);
        $views_list = '';
        $filter_view_list='is_enabled=1';			
        $views_list = $staff_object->get_view_list($filter_view_list, VIS_STAFF_ID, VIS_LOCATION_AREA);
        for($i=0;$i<count($views_list);$i++) {
            if($views_list[$i]["view_id"] == $operation['view_id']){
                $set_class = " class ='selected'";
                $check='<i class="vh vh-check pull-right"></i>';
            } else {
                $set_class = "";
                $check="";
            }
			if($views_list[$i]["owner"] ==VIS_STAFF_ID || $views_list[$i]["owner"]==0)
            {
            $list.='<li><a '.$set_class.' href="javascript:void(0);" id="view_'. $views_list[$i]["view_id"].'" onclick="vis_change_view(\''.$views_list[$i]["view_id"].'\',\''.$operation['view_operation'].'\',\''.$operation['filter_id'].'\');">'.$check.$views_list[$i]['view_name'].'</a></li>';
			}

        }
        echo '<button class="btn btn-default btn-sm dropdown-toggle action_btn" data-toggle="dropdown">
			<span class="dropdown-label">'.$vis_language['TXTVIEWS'].'&nbsp;</span><span class="caret"></span></button>';
        echo '<ul name="view" class="dropdown-menu">'.$list.'</ul>';
        return true;
    }
    function load_label_list($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff_object=new class_staff($database);
        $labels_list = $this->get_properties('get_labels', '');
        for($i=0;$i<count($labels_list);$i++) { 
            $list.='<li onclick="$(\'#vis_workpanel_div\').visExecution(\'load_module\', \''.addslashes(str_replace("'", '', $labels_list[$i]['label_name'])).'\', {\'vis_module\':\'ticket\', \'vis_operation\':\'search_label_tickets\', \'vis_label_id\':'.$labels_list[$i]['label_id'].'});"><a href="#/ticket/search_label_tickets/'.$labels_list[$i]['label_name'].'/'.$labels_list[$i]['label_id'].'"><span class="padder" style="background-color: '. $labels_list[$i]['label_color'].'; color: #fff;">'.$labels_list[$i]['label_name'].'</span></a></li>';
         }
        echo '<button class="btn btn-default btn-sm dropdown-toggle action_btn" data-toggle="dropdown">
			<span class="dropdown-label">'.$vis_language['TXTLABELS'].'&nbsp;</span><span class="caret"></span></button>';
        echo '<ul name="labels" class="dropdown-menu">'.$list.'</ul>';
        return true;
    }
	
	function advanced_search($operation)
	{   
	    global $vis_language;
		$vis_title = $header_title = $vis_language['TXTADVSEARCH'];
	    $breadcrumb['Home'] = 'index.php'; 
        $breadcrumb[$vis_language['TXTADVSEARCH']] = ''; 
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
		$module_setting=$setting_object->get_module_setting('domain_id='.VIS_DOMAIN.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
	    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');       
        $ticket_object=new class_ticket($database); 
        $domains = $ticket_object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
        $departments=$this->get_properties('get_departments', '');
        $status=$this->get_properties('get_status', '');
        $ticket_types=$this->get_properties('get_types', '');
        $priorities=$this->get_properties('get_priorities', '');
        $flags=$this->get_properties('get_flags', '');
        $owner=$this->get_properties('get_staff', '');
		$category_details=$this->get_properties('get_category', '');
		$subcategory_details=$this->get_properties('get_subcategory', '');
		$item_details=$this->get_properties('get_item', '');
		$level_details=$this->get_properties('get_level', '');
		$location_details=$this->get_properties('get_location', '');
	    
		 include(VIS_PATH_TEMPLATE.'header.php');
		 include(VIS_PATH_TEMPLATE.'advanced_search.php');
		 include(VIS_PATH_TEMPLATE.'footer.php');
		return true;
	}
	
	
    function load_filter_list($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');       
        $ticket_object=new class_ticket($database); 
        $domains = $ticket_object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
        $departments=$this->get_properties('get_departments', '');
        $status=$this->get_properties('get_status', '');
        $ticket_types=$this->get_properties('get_types', '');
        $priorities=$this->get_properties('get_priorities', '');
        $flags=$this->get_properties('get_flags', '');
        $owner=$this->get_properties('get_staff', '');
		$category_details=$this->get_properties('get_category', '');
		$subcategory_details=$this->get_properties('get_subcategory', '');
		$item_details=$this->get_properties('get_item', '');
		$level_details=$this->get_properties('get_level', '');
		$location_details=$this->get_properties('get_location', '');
        include(VIS_PATH_TEMPLATE.'ticket_filter_list.php');
        return true;
    }
	function get_mailchimp_details($operation) {
        include(VIS_PATH_TEMPLATE.'mailchimp_client_details.php');
        return true;
    }
	function mailchimp_client_profile($operation)
    {
	    global $vis_language;
		$operation['mailchimp']='profile';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=28 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
			  $api_key = $api_integration[0]['api_key'];
			  include(VIS_PATH_PLUGINS.'mailchimp/Mailchimp.php');
			  $MailChimp = new MailChimp($api_key);
			  $list = $MailChimp->call('lists/list');
			  for($i=0;$i<count($list['data']);$i++){
				 $member=$MailChimp->call('lists/members', array(
                'id'                => $list['data'][$i]['id']
				));
				
				for($j=0;$j<count($member['data']);$j++){
					$member_info=$MailChimp->call('lists/member-info', array(
                'id'                => $list['data'][$i]['id'],
				'emails'             => array(array('email '=>$member['data'][$j]['email'],'euid'=>$member['data'][$j]['euid'],'leid'=>$member['data'][$j]['leid']))
				));
				if($operation['vis_email']==$member['data'][$j]['email']){
					include(VIS_PATH_TEMPLATE.'mailchimp_client_profile.php');
				  exit; 
				}
				}
			  }
			  include(VIS_PATH_TEMPLATE.'no_record_yet.php'); 
		  }
	}
	function mailchimp_client_activity($operation)
    {
	    global $vis_language;
		$operation['mailchimp']='activity';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=28 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		$activity = array();
		  if(count($api_integration)>0 && $api_integration!=-1){
			  $api_key = $api_integration[0]['api_key'];
			  include(VIS_PATH_PLUGINS.'mailchimp/Mailchimp.php');
			  $MailChimp = new MailChimp($api_key);
			  $list = $MailChimp->call('lists/list');
			  //$list = $MailChimp->call('campaigns/list');
			  for($i=0;$i<count($list['data']);$i++){
				$member_activity=$MailChimp->call('lists/member-activity', array(
						'id'                => $list['data'][$i]['id'],
						'emails'            => array(array('email'=>$operation['vis_email']))
				));
				$activity[$i]= $member_activity;
				 if($activity[0]['error_count']==1){
			  		include(VIS_PATH_TEMPLATE.'no_record_yet.php');
					exit;
				 }
			  }			  			  
			  include(VIS_PATH_TEMPLATE.'mailchimp_client_profile.php');
			  
		  }
	}
	function get_magento_details($operation) {
		$magento_result = array();
		$operation['type']='profile';
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=31 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($magento_info, $magento_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(count($magento_details)>0 && $magento_details!=-1){
			foreach($magento_details as $magento){
				$file_headers = @get_headers($magento['billing_url'].'/api/soap/?wsdl');
				if($file_headers[0] != 'HTTP/1.1 404 Not Found') {
					$client = new SoapClient($magento['billing_url'].'/api/soap/?wsdl');
					$session_magento = $client->login($magento['user_name'], $magento['api_key']);
					if($session_magento){
						$client_info = $client->call($session_magento, 'customer.list', array(array('email' => $operation['vis_email'])));
						if(count($client_info)>0){
							$magento_array['userinfo']=$client_info[0]; 
							$magento_address = $client->call($session_magento, 'customer_address.list', $client_info[0]['customer_id']);
							$magento_array['address']=$magento_address[0];
							$magento_array['magento_url']=$magento['billing_url'];
							$magento_result[]=$magento_array; 
						}
						$client->endSession($session_magento);
					}
				}
			}
		}
		include(VIS_PATH_TEMPLATE.'magento_client_details.php');
        return true;
    }
	function magento_client_profile($operation){
		$magento_result = array();
		$invoice_result = array();
	    global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=31 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($magento_info, $magento_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(count($magento_details)>0 && $magento_details!=-1){
			foreach($magento_details as $magento){
				$file_headers = @get_headers($magento['billing_url'].'/api/soap/?wsdl');
				if($file_headers[0] != 'HTTP/1.1 404 Not Found') {
					$client = new SoapClient($magento['billing_url'].'/api/soap/?wsdl');
					$session_magento = $client->login($magento['user_name'], $magento['api_key']);
					
					if($operation['type']=='profile'){
						$client_info = $client->call($session_magento, 'customer.list', array(array('email' => $operation['vis_email'])));
						if(count($client_info)>0){
							$magento_array['userinfo']=$client_info[0]; 
							$magento_address = $client->call($session_magento, 'customer_address.list', $client_info[0]['customer_id']);
							$magento_array['address']=$magento_address[0];
							$magento_array['magento_url']=$magento['billing_url'];
							$magento_result[]=$magento_array; 
						}
					}elseif($operation['type']=='activity'){
						$order_list = $client->call($session_magento, 'order.list', array(array('customer_email' => $operation['vis_email'])));
						
						if(count($order_list)>0){
							$all_order['magento_url']=$magento['billing_url'];
							$all_order['order_list']=$order_list;
							$final_result[] = $all_order;
						}
					}elseif($operation['type']=='invoice'){
						$magento_invoice = array();
						$order_list = $client->call($session_magento, 'order.list', array(array('customer_email' => $operation['vis_email'])));
						
						if(count($order_list)>0){
							foreach($order_list as $order_info){
								$filter = array(array('order_id' => $order_info['order_id']));
								$invoices = $client->call($session_magento, 'sales_order_invoice.list', $filter);
								if(count($invoices)>0){
									foreach($invoices as $invoices_info){
										$magento_inv['order_details']=$order_info;
										$magento_inv['invoice_details']=$invoices_info;
										$magento_invoice[]=$magento_inv;
									}
								}
							}
							if(count($magento_invoice)>0){
								$all_invoice['magento_url']=$magento['billing_url'];
								$all_invoice['invoice']=$magento_invoice;
								$invoice_result[] = $all_invoice;
							}
						}
					}
					$client->endSession($session_magento);
				}
			}
		}
		include(VIS_PATH_TEMPLATE.'magento_client_profile.php');
        return true;
	}
	 function get_freshbooks_details($operation) {
        include(VIS_PATH_TEMPLATE.'freshbooks_client_details.php');
        return true;
    }
    function freshbooks_client_profile($operation)
    {
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=29 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
		  $domain = $api_integration[0]['admin_user'];
		  $token = $api_integration[0]['api_key'];
		  include(VIS_PATH_PLUGINS.'freshbook/FreshBooksRequest.php');
		  FreshBooksRequest::init($domain, $token);
		  $fb = new FreshBooksRequest('client.list');
			$fb->post(array(
				'email' => $vis_email
			));
			$fb->request();
			if($fb->success())
			{
				$list=$fb->getResponse();
				$client_info=array();
				$client_list=$list['clients']['client'];
				for($i=0;$i<$list['clients']['@attributes']['total'];$i++){
					if($list['clients']['@attributes']['total']==1) $client_list[0] =  $client_list;
					$client_info[$i]['name']=((!empty($client_list[$i]['first_name']))?$client_list[$i]['first_name']:'').''.((!empty($client_list[$i]['last_name']))?$client_list[$i]['last_name']:'');
					$client_info[$i]['email']=(!empty($client_list[$i]['email']))?$client_list[$i]['email']:'';
					$client_info[$i]['username']=(!empty($client_list[$i]['username']))?$client_list[$i]['username']:'';
					$client_info[$i]['home_phone']=(!empty($client_list[$i]['home_phone']))?$client_list[$i]['home_phone']:'';
					$client_info[$i]['mobile']=(!empty($client_list[$i]['mobile']))?$client_list[$i]['mobile']:'';
					$client_info[$i]['organization']=(!empty($client_list[$i]['organization']))?$client_list[$i]['organization']:'';
					$client_info[$i]['city']=(!empty($client_list[$i]['p_city']))?$client_list[$i]['p_city']:'';
					$client_info[$i]['state']=(!empty($client_list[$i]['p_state']))?$client_list[$i]['p_state']:'';
					$client_info[$i]['country']=(!empty($client_list[$i]['p_country']))?$client_list[$i]['p_country']:'';
				}
			}
			else
			{
				echo $fb->getError();
				print_r($fb->getResponse());
			}
		  }
		  $client_info['total']=!empty($client_info)?count($client_info):0;
		  if($client_info['total']==0){
			  include(VIS_PATH_TEMPLATE.'no_record_yet.php');
		  }
		  else {
			  include(VIS_PATH_TEMPLATE.'freshbooks_client_profile.php');
			  exit;
		  }
	}
	 function freshbooks_products($operation)
    {
	    global $vis_language;
	    $project_info = $project_info1= array();
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=29 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
		  $domain = $api_integration[0]['admin_user'];
		  $token = $api_integration[0]['api_key'];
		  include(VIS_PATH_PLUGINS.'freshbook/FreshBooksRequest.php');
		  FreshBooksRequest::init($domain, $token);
		  $fb = new FreshBooksRequest('client.list');
			$fb->post(array(
				'email' => $vis_email
			));
			$fb->request();
			if($fb->success())
			{
				$list=$fb->getResponse();
			}
			for($i=0;$i<$list['clients']['@attributes']['total'];$i++){
				if($list['clients']['@attributes']['total']==1)
				$client_id=$list['clients']['client']['client_id'];
				else
				$client_id=$list['clients']['client'][$i]['client_id'];
		    $fb = new FreshBooksRequest('project.list');
			$fb->post(array(
				'client_id' => array($client_id)
			));
			$fb->request();
			if($fb->success())
			{
				$project_list=$fb->getResponse();
				if(!empty($project_list['projects']['project'])){
				if(!is_array($project_list['projects']['project'][0]))$project_info1[]=$project_list['projects']['project'];
				else 
				{
					for($j=0;$j<count($project_list['projects']['project']);$j++)
					{
						if(!empty($project_list['projects']['project'][$j]))
						$project_info1[]=$project_list['projects']['project'][$j];
					}
			    }
				}
			}
			else
			{
				echo $fb->getError();
				print_r($fb->getResponse());
			}
			}
		  }
		  $view_info['page_count']=(count($project_info1)==0)?0:ceil(count($project_info1)/3);
		  $project_info['page']=$operation['vis_page'];
		  $start=$operation['vis_page']*3;
		  $end=$start+3;
		  if($end>count($project_info1)) $end=count($project_info1);
		  for($i=$start; $i<$end;$i++) 
		  $project_info[]=$project_info1[$i];
		  include(VIS_PATH_TEMPLATE.'freshbooks_projects.php');
		  exit;	
	}
	 function freshbooks_invoices($operation)
    {
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=29 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
		  $domain = $api_integration[0]['admin_user'];
		  $token = $api_integration[0]['api_key'];
		  include(VIS_PATH_PLUGINS.'freshbook/FreshBooksRequest.php');
		  FreshBooksRequest::init($domain, $token);
		  $fb = new FreshBooksRequest('client.list');
			$fb->post(array(
				'email' => $vis_email
			));
			$fb->request();
			if($fb->success())
			{
				$list=$fb->getResponse();
			}
			$invoice_info = $invoice_info1 = array();
			for($i=0;$i<$list['clients']['@attributes']['total'];$i++){
				if($list['clients']['@attributes']['total']==1)
				$client_id=$list['clients']['client']['client_id'];
				else
				$client_id=$list['clients']['client'][$i]['client_id'];
		    $fb = new FreshBooksRequest('invoice.list');
			$fb->post(array(
			
				'client_id' => array($client_id)
			));
			$fb->request();
			if($fb->success())
			{
				
				$invoice_list=$fb->getResponse();
				if(!empty($invoice_list['invoices']['invoice'])){
				if(!is_array($invoice_list['invoices']['invoice'][0]))$invoice_info1[]=$invoice_list['invoices']['invoice'];
				else 
				{
					for($j=0;$j<count($invoice_list['invoices']['invoice']);$j++)
					{
						if(!empty($invoice_list['invoices']['invoice'][$j]))
						$invoice_info1[]=$invoice_list['invoices']['invoice'][$j];
					}
				
			    }
				}
			}
			else
			{
				echo $fb->getError();
				print_r($fb->getResponse());
			}
			}
			}
			$view_info['page_count']=(count($invoice_info1)==0)?0:ceil(count($invoice_info1)/3);
			$invoice_info['page']=$operation['vis_page'];
			$start=$operation['vis_page']*3;
			$end=$start+3;
			if($end>count($invoice_info1)) $end=count($invoice_info1);
			for($i=$start; $i<$end;$i++) 
			$invoice_info[]=$invoice_info1[$i];
		    include(VIS_PATH_TEMPLATE.'freshbooks_invoices.php');
			exit;
	}
	
	//****INSIGHTLY******/
	function insightly_curlcall($service_url,$apikey){
		$insightly_result = array();
		$ch = curl_init($service_url);           
		curl_setopt($ch , CURLOPT_HTTPHEADER, array('Content-Type: application/json', 
													'Authorization: Basic ' . base64_encode($apikey)));
		curl_setopt($ch , CURLOPT_HEADER, 0); 
		curl_setopt($ch , CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($ch , CURLOPT_URL, $service_url);          
		curl_setopt($ch , CURLOPT_RETURNTRANSFER, TRUE);    
		curl_setopt($ch , CURLOPT_SSL_VERIFYPEER, false);        
		$return = curl_exec($ch );    
		$client_info = json_decode($return);
		curl_close($ch);
	
		return $client_info;
	}
	function get_insightly_details($operation) {
		$insightly_result = array();
		$operation['type']='profile';
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=33 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($insightly_info, $insightly_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	
        if(count($insightly_details)>0 && $insightly_details!=-1){
			foreach($insightly_details as $insightly){
				
				$service_url = $insightly['billing_url'].'Contacts?email='.$operation['vis_email'];
				$apikey=$insightly['api_key'];
				$client_info = $this->insightly_curlcall($service_url,$apikey);

				if(count($client_info)>0){
					$insightly_result=$client_info[0]; 
					if($insightly_result->DEFAULT_LINKED_ORGANISATION!=''){
					    $service_url = $insightly['billing_url'].'Organisations?ids='.$insightly_result->DEFAULT_LINKED_ORGANISATION;
						$client_info = $this->insightly_curlcall($service_url,$apikey);
						$organisation_data=$client_info[0];
						$insightly_result->ORGANISATION_NAME=$organisation_data->ORGANISATION_NAME;
						$insightly_result->ORGANISATION_EMAIL=$organisation_data->CONTACTINFOS[1]->DETAIL;
					}
				}
			}
		}
		include(VIS_PATH_TEMPLATE.'insightly_client_details.php');
        return true;
    }
	function get_insightly_notes_details($operation) {
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=33 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($insightly_info, $insightly_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);

        if(count($insightly_details)>0 && $insightly_details!=-1){
			foreach($insightly_details as $insightly){
				
				if($operation['type']=='profile')
					$service_url = $insightly['billing_url'].'Contacts?email='.$operation['vis_email'];
				elseif($operation['type']=='notes')
					$service_url = $insightly['billing_url'].'Contacts/'.$operation['vis_contactid'].'/Notes';
				
				$apikey=$insightly['api_key'];							
				$client_info = $this->insightly_curlcall($service_url,$apikey);
				
				if(count($client_info)>0){
					$insightly_result= ($operation['type']=='profile') ? $client_info[0] : $client_info; 
					if($insightly_result->DEFAULT_LINKED_ORGANISATION!=''){
					    $service_url = $insightly['billing_url'].'Organisations?ids='.$insightly_result->DEFAULT_LINKED_ORGANISATION;
						$client_info = $this->insightly_curlcall($service_url,$apikey);
						$organisation_data=$client_info[0];
						$insightly_result->ORGANISATION_NAME=$organisation_data->ORGANISATION_NAME;
						$insightly_result->ORGANISATION_EMAIL=$organisation_data->CONTACTINFOS[1]->DETAIL;
					}
				}
			}
		}
		include(VIS_PATH_TEMPLATE.'insightly_client_profile.php');
        return true;
    }
	//*******************/
	function get_bigcommerce_details($operation) {
		$bigcommerce_result = array();
		$operation['type']='profile';
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=34 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($bigcommerce_info, $bigcommerce_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(count($bigcommerce_details)>0 && $bigcommerce_details!=-1){
			foreach($bigcommerce_details as $bigcommerce){
							
				$url = $bigcommerce['billing_url']."customers.json?email=".$operation['vis_email'];   
				
				$curl_request = curl_init();
				curl_setopt($curl_request, CURLOPT_URL, $url);
				curl_setopt($curl_request, CURLOPT_HEADER, false);
				curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl_request, CURLOPT_USERPWD, $bigcommerce['user_name'].":".$bigcommerce['api_key']);
				$customer_details = curl_exec($curl_request);
				curl_close($curl_request);
				$customer_details =json_decode($customer_details, true);  
				if(is_array($customer_details) && !isset($customer_details[0]['status'])){
					//////////////////CUSTOMER Address//////////////
					$curl_request = curl_init();
					curl_setopt($curl_request, CURLOPT_URL, $customer_details[0]['addresses']['url']);
					curl_setopt($curl_request, CURLOPT_HEADER, false);
					curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($curl_request, CURLOPT_USERPWD, $bigcommerce['user_name'].":".$bigcommerce['api_key']);
					$customer_addresss = curl_exec($curl_request);
					curl_close($curl_request);
					$customer_addresss =json_decode($customer_addresss, true);
					$bigcommerce_array['customer_details']=$customer_details[0];
					$bigcommerce_array['address']=$customer_addresss[0];
					$bigcommerce_array['bigcommerce_path']=$bigcommerce['billing_url'];
					$bigcommerce_result[]=$bigcommerce_array; 
				}
			}
		}
		include(VIS_PATH_TEMPLATE.'bigcommerce_client_details.php');
        return true;
    }
	function bigcommerce_client_profile($operation){
		$bigcommerce_result = array();
		
	    global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		
		$filter='integration_type=34 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($bigcommerce_info, $bigcommerce_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(count($bigcommerce_details)>0 && $bigcommerce_details!=-1){
			foreach($bigcommerce_details as $bigcommerce){
				
				if($operation['type']=='profile'){
					
					$url = $bigcommerce['billing_url']."customers.json?email=".$operation['vis_email'];   
					$curl_request = curl_init();
					curl_setopt($curl_request, CURLOPT_URL, $url);
					curl_setopt($curl_request, CURLOPT_HEADER, false);
					curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($curl_request, CURLOPT_USERPWD, $bigcommerce['user_name'].":".$bigcommerce['api_key']);
					$customer_details = curl_exec($curl_request);
					curl_close($curl_request);
					$customer_details =json_decode($customer_details, true);  
					if(is_array($customer_details) && !isset($customer_details[0]['status'])){
						//////////////////CUSTOMER Address//////////////
						$curl_request = curl_init();
						curl_setopt($curl_request, CURLOPT_URL, $customer_details[0]['addresses']['url']);
						curl_setopt($curl_request, CURLOPT_HEADER, false);
						curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
						curl_setopt($curl_request, CURLOPT_USERPWD, $bigcommerce['user_name'].":".$bigcommerce['api_key']);
						$customer_addresss = curl_exec($curl_request);
						curl_close($curl_request);
						$customer_addresss =json_decode($customer_addresss, true);
						$bigcommerce_array['customer_details']=$customer_details[0];
						$bigcommerce_array['address']=$customer_addresss[0];
						$bigcommerce_array['bigcommerce_path']=$bigcommerce['billing_url'];
						$bigcommerce_result[]=$bigcommerce_array; 
					}
				}elseif($operation['type']=='activity'){
										
					$url = $bigcommerce['billing_url']."customers.json?email=".$operation['vis_email'];   
					$curl_request = curl_init();
					curl_setopt($curl_request, CURLOPT_URL, $url);
					curl_setopt($curl_request, CURLOPT_HEADER, false);
					curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($curl_request, CURLOPT_USERPWD, $bigcommerce['user_name'].":".$bigcommerce['api_key']);
					$customer_details = curl_exec($curl_request);
					
					curl_close($curl_request);
					$customer_details =json_decode($customer_details, true);  
					if(is_array($customer_details) && !isset($customer_details[0]['status'])){
						//////////////////CUSTOMER ORDER//////////////
						$order_url = $bigcommerce['billing_url']."orders.json?customer_id=".$customer_details[0]['id'];
						$curl_request = curl_init();
						curl_setopt($curl_request, CURLOPT_URL, $order_url);
						curl_setopt($curl_request, CURLOPT_HEADER, false);
						curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
						curl_setopt($curl_request, CURLOPT_USERPWD, $bigcommerce['user_name'].":".$bigcommerce['api_key']);
						$customer_order = curl_exec($curl_request);
						curl_close($curl_request);
						$customer_order =json_decode($customer_order, true);
						
						if(isset($customer_order[0]['id'])){
							$bigcommerce_array['order']=$customer_order;
							$bigcommerce_array['bigcommerce_path']=$bigcommerce['billing_url'];
							$bigcommerce_result[]=$bigcommerce_array;
						}
						 
					}
				}
			}
		}
		
		include(VIS_PATH_TEMPLATE.'bigcommerce_client_profile.php');
        return true;
	}
	function get_jira_details($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		$filter='type=1 and ticket_id='.$operation['vis_ticketid'];
		$jira_link_detail=$ticket_object->get_jira_ticket_link($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'jira.php');
	}
	function get_jira_create_issue($operation) {
	    global $vis_language;
		$operation['jira']='createissue';
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        //$vis_email = $operation['vis_email'];
        $filter = ' integration_type=35 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		//$activity = array();
		  if(count($api_integration)>0 && $api_integration!=-1){
			$username = $api_integration[0]['user_name']; $password = $api_integration[0]['db_password'];			 
			$url = $api_integration[0]['billing_url']."/rest/api/latest/project";
			$ch = curl_init();
			$headers = array(
			 	'Accept: application/json',
			 	'Content-Type: application/json'
			);
			//$test = "This is the content of the custom field.";
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
			$result = curl_exec($ch);
			$jira_product =json_decode($result,true);
			curl_close($ch);
			$ch = curl_init();
			$url1=$api_integration[0]['billing_url'].'/rest/api/2/issue/createmeta?projectKeys='.$jira_product[0]['key'];
			//$test = "This is the content of the custom field.";
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_URL, $url1);
			curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
			$result1 = curl_exec($ch);
			$issue_type =json_decode($result1,true);
			curl_close($ch);
			$filter1=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticketid'];
			list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter1, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
			$post_details=$ticket_object->get_ticket_post($operation['vis_ticketid'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA, '', '');
			$ticket_details=$ticket_details[0];
			$database->database_disconnect();
			include(VIS_PATH_TEMPLATE.'jira_activity.php');
		  }
    }
	function get_jira_issue_type($operation){
		    $ch = curl_init();
		    $url1=$operation['vis_jira_url'].'/rest/api/2/issue/createmeta?projectKeys='.$operation['vis_jira_hash'];
			//$test = "This is the content of the custom field.";
			$headers = array(
			 	'Accept: application/json',
			 	'Content-Type: application/json'
			);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_URL, $url1);
			curl_setopt($ch, CURLOPT_USERPWD, $operation['vis_username'].':'.$operation['vis_password']);
			$result1 = curl_exec($ch);
			$issue_type =json_decode($result1,true);
			
			curl_close($ch);
			if(count($issue_type)>10) $vis_scroll= 'data-live-search="true"';
			echo '<select class="form-control selectpicker" data-size="auto" data-container="body" name="vis_issue_type" id="vis_issue_type" '.$vis_scroll.'>';               
              for($i=0;$i<count($issue_type['projects'][0]['issuetypes']);$i++){
                 if($issue_type['projects'][0]['issuetypes'][$i]['subtask']==''){ echo '<option value="'.$issue_type['projects'][0]['issuetypes'][$i]['name'].'">'.$issue_type['projects'][0]['issuetypes'][$i]['name'].'</option>'; }
              }              
            echo '</select>';
	}
	function create_jira_issue($operation){
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$jira_details = array();
		$jira_details=parse_form_array($operation['vis_action']);
		$url = $jira_details['vis_jira_url'].'/rest/api/2/issue/';
		$data = array('fields' => array('project' => array('key' => $jira_details['vis_jira_product'],),'summary' => $jira_details['vis_subject'],'description' => $jira_details['vis_ticket_post'],"issuetype" => array(		 
			//"self" => "xxxx",
			//"id" => "xxxx",
			//"description" => "xxxxx",
			//"iconUrl" => "xxxxx",
			"name" => $jira_details['vis_issue_type'],
			//"subtask" => false
		),
		),
		);
		$ch = curl_init();
		$headers = array(
			'Accept: application/json',
			'Content-Type: application/json'
		);
		//$test = "This is the content of the custom field.";
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERPWD, $jira_details['vis_username'].':'.$jira_details['vis_password']);
		$result = curl_exec($ch);
		$created_jira_issue = json_decode($result,true);
		$ch_error = curl_error($ch);
		if(isset($created_jira_issue['id'])){
			list($dpinf, $domain)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$jira_details['vis_domain'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$url2 =$jira_details['vis_jira_url']."/rest/api/latest/issue/".$created_jira_issue['key']."/remotelink";  
			$ch = curl_init();
			$data = array('object' => array('url' => $domain[0]['domain_url'].'manage/#/ticket/ticket_details/'.$jira_details['ticket_hash'].'/'.$jira_details['vis_ticketid'],'title'=>$jira_details['vis_subject']));			
			
			$headers = array(
				'Accept: application/json',
				'Content-Type: application/json'
			);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
			curl_setopt($ch, CURLOPT_URL, $url2);
			curl_setopt($ch, CURLOPT_USERPWD, $jira_details['vis_username'].':'.$jira_details['vis_password']);
			$result = curl_exec($ch);
			$link_data = json_decode($result,true);
			curl_close($ch);
			$operation['vis_type']=1;
			$operation['link_id']=$link_data['id'];
			$operation['vis_jira_hash']=$created_jira_issue['key'];
			$operation['vis_ticketid']=$jira_details['vis_ticketid'];
			if(isset($link_data['id']) && $link_data['id']!=''){
				$jira_link = $ticket_object->add_link_jira_issue($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
				include(VIS_PATH_TEMPLATE.'jira_activity.php');
				echo "<script>$('#vis_details_list').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'jira_issue','vis_domain':'".$jira_details['vis_domain']."','vis_ticketid':'".$jira_details['vis_ticketid']."'}); $('#issue_id_error').hide(); </script>";
				
			}			
		}
		$database->database_disconnect();
		//$info = curl_getinfo($ch);
		//echo '<pre>'; print_r($info); echo '</pre>';
		curl_close($ch);
	}
	function jira_issue($operation){
		global $vis_language;
		$operation['jira']='linkissue';
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		$filter='type=1 and ticket_id='.$operation['vis_ticketid'];
		$jira_link_details=$ticket_object->get_jira_ticket_link($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
		if($jira_link_details!=-1){
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$object=new class_setting($database);
			$filter = ' integration_type=35 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
			$api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$database->database_disconnect();
			$api_integration =   $api_integration[1];
			if(count($api_integration)>0 && $api_integration!=-1){
				$username = $api_integration[0]['user_name']; $password = $api_integration[0]['db_password'];
				$url=$api_integration[0]['billing_url']."/rest/api/latest/issue/".$jira_link_details[0]['issue_hash']."/remotelink/".$jira_link_details[0]['link_id'];	
				$ch = curl_init();
				$headers = array(
					'Accept: application/json',
					'Content-Type: application/json'
				);	 
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_VERBOSE, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
				$result = curl_exec($ch);
				$jira_link_issue =json_decode($result,true);
				curl_close($ch) ;
				
				$url1=$api_integration[0]['billing_url']."/rest/api/2/search?jql=key=".$jira_link_details[0]['issue_hash'];	
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_VERBOSE, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
				curl_setopt($ch, CURLOPT_URL, $url1);
				curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
				$result1 = curl_exec($ch);
				$jira_issue_details =json_decode($result1,true);
				curl_close($ch) ;	
			}
		}
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'jira_activity.php');
	}
	
	function link_jira_issue($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		list($dpinf, $domain)=$object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.VIS_DOMAIN, '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$filter = ' integration_type=35 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		if(count($api_integration)>0 && $api_integration!=-1){
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
            $ticket_object=new class_ticket($database);
			$filter1=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticketid'];
			list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter1, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
			//$post_details=$ticket_object->get_ticket_post($operation['vis_ticketid'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA, '', '');
			$ticket_details=$ticket_details[0];
			$username = $api_integration[0]['user_name']; $password = $api_integration[0]['db_password'];
			//$url=$api_integration[0]['billing_url']."/rest/api/2/search?jql=key=".$operation['vis_jira_hash']."";
			
			$url2 =$api_integration[0]['billing_url']."/rest/api/latest/issue/".$operation['vis_jira_hash']."/remotelink";  
			$ch = curl_init();
			$data = array('object' => array('url' => $domain[0]['domain_url'].'manage/#/ticket/ticket_details/'.$ticket_details['ticket_hash'].'/'.$operation['vis_ticketid'],'title'=>$ticket_details['subject']));
			$headers = array(
				'Accept: application/json',
				'Content-Type: application/json'
			);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
			curl_setopt($ch, CURLOPT_URL, $url2);
			curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
			$result = curl_exec($ch);
			$link_data = json_decode($result,true);
			curl_close($ch);
			$operation['vis_type']=1;
			$operation['link_id']=$link_data['id'];
			if(isset($link_data['id']) && $link_data['id']!=''){
				$jira_link = $ticket_object->add_link_jira_issue($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
				include(VIS_PATH_TEMPLATE.'jira_activity.php');
				echo "<script>$('#vis_details_list').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'jira_issue','vis_domain':'".$operation['vis_domain']."','vis_ticketid':'".$operation['vis_ticketid']."'}); $('#issue_id_error').hide(); </script>";
				
			}else{
				$operation['jira']='linkissue';
				$jira_link_details=-1;
				include(VIS_PATH_TEMPLATE.'jira_activity.php');
				echo "<script>$('#issue_id_error').show();$('#issue_id_error').html('".$vis_language['TXTNOMATCHFOUND']."'); </script>";
			}
			$database->database_disconnect();			
		}		
	}
	function unlink_jira_issue($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		$filter = 'ticket_id='.$operation['vis_ticketid'].' and type=1';
		$ret = $ticket_object->delete_link_jira_issue($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		if($ret) {
			$operation['jira']='linkissue';
			$jira_link_details=-1;
			include(VIS_PATH_TEMPLATE.'jira_activity.php');	
	    }			
	}

	function get_blesta_details($operation) {
        include(VIS_PATH_TEMPLATE.'blesta_client_details.php');
        return true;
    }
    function blesta_client_profile($operation)
    {
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=36 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
        $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
		  $url=$api_integration[0]['billing_url'];
		  $username = $api_integration[0]['user_name'];
		  $api_key = $api_integration[0]['api_key'];
		  include(VIS_PATH_PLUGINS.'blesta/blesta_api.php');
		  $api = new BlestaApi($url, $username, $api_key);
		  $user_resp = $api->get("users", "getByUsername", array('username' =>  $vis_email));
		  $user_response=$user_resp->response();
		  $user_details = get_object_vars($user_response);
		  $user_id=$user_details['id'];
		  if(!empty($user_details))
		  {
			  $client_response = $api->post("clients", "getByUserId", array('user_id' => $user_id));
			  $client_resp = $client_response->response();
			  $client_details = get_object_vars($client_resp);
			  if(!empty($client_details))
			  {
				  $client_info=array();
				  $client_info['name']=((!empty($client_details['first_name']))?$client_details['first_name']:'').''.((!empty($client_details['last_name']))?$client_details['last_name']:'');
				  $client_info['email']=(!empty($client_details['email']))?$client_details['email']:'';
				  $client_info['username']=(!empty($client_details['username']))?$client_details['username']:'';
				  $client_info['status']=(!empty($client_details['status']))?$client_details['status']:'';
				  $client_info['organization']=(!empty($client_details['group_name']))?$client_details['group_name']:'';
				  $client_info['address']=(!empty($client_details['address1']))?$client_details['address1']:'';
				  $client_info['city']=(!empty($client_details['city']))?$client_details['city']:'';
				  $client_info['state']=(!empty($client_details['state']))?$client_details['state']:'';
				  $client_info['country']=(!empty($client_details['country']))?$client_details['country']:'';
				  $client_info['company']=(!empty($client_details['company']))?$client_details['company']:'';	  
			  }
			  else
			  {
				  print_r($client_response->errors());
			  }
		  }
		  }
		  $client_info['total']=!empty($client_info)?count($client_info):0;
		  if($client_info['total']==0){
			  include(VIS_PATH_TEMPLATE.'no_record_yet.php');
		  }
		  else {
			  include(VIS_PATH_TEMPLATE.'blesta_client_profile.php');
			  exit;
		  }
	}
	 function blesta_invoices($operation)
    {
	      global $vis_language;
          $database=new class_database();
          include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
          $object=new class_setting($database);
          $vis_email = $operation['vis_email'];
          $filter = ' integration_type=36 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
          $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	      $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
		  $url=$api_integration[0]['billing_url'];
		  $username = $api_integration[0]['user_name'];
		  $api_key = $api_integration[0]['api_key'];
		  include(VIS_PATH_PLUGINS.'blesta/blesta_api.php');
		  $api = new BlestaApi($url, $username, $api_key);
		  $user_resp = $api->get("users", "getByUsername", array('username' =>  $vis_email));
		  $user_response=$user_resp->response();
		  $user_details = get_object_vars($user_response);
		  $user_id=$user_details['id'];
		  if(!empty($user_details))
		  {
			  $client_response = $api->post("clients", "getByUserId", array('user_id' => $user_id));
			  $client_resp = $client_response->response();
			  $client_details = get_object_vars($client_resp);
			  $client_id=$client_details['id'];
			  if(!empty($client_details))
			  {
			  $invoice_response = $api->get("invoices", "getList", array('client_id' => $client_id));
			  $invoice_resp = $invoice_response->response();
			  if(!empty($invoice_resp))
			  {
				  $invoice_info=$invoice_info1=array();
				  for($i=0;$i<count($invoice_resp);$i++)
				  {
					 $invoice_details = get_object_vars($invoice_resp[$i]);
					 $invoice_info1[]=$invoice_details;
				  } 	  
			  }
			  else
			  {
				  print_r($invoice_response->errors());
			  }
			  }
	      } 
		  }
		  $view_info['page_count']=(count($invoice_info1)==0)?0:ceil(count($invoice_info1)/3);
		  $invoice_info['page']=$operation['vis_page'];
		  $start=$operation['vis_page']*3;
		  $end=$start+3;
		  if($end>count($invoice_info1)) $end=count($invoice_info1);
		  for($i=$start; $i<$end;$i++) 
		  $invoice_info[]=$invoice_info1[$i];
		  include(VIS_PATH_TEMPLATE.'blesta_invoices.php');
		  exit;
	}
	 function blesta_packages($operation)
    {
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        $vis_email = $operation['vis_email'];
        $filter = ' integration_type=36 and '.VIS_TABLE_PREFIX.'integration.domain_id= '.$operation['vis_domain'].' ';
          $api_integration = $object->get_integration_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	      $api_integration =   $api_integration[1];
		  if(count($api_integration)>0 && $api_integration!=-1){
		  $url=$api_integration[0]['billing_url'];
		  $username = $api_integration[0]['user_name'];
		  $api_key = $api_integration[0]['api_key'];
		  include(VIS_PATH_PLUGINS.'blesta/blesta_api.php');
		  $api = new BlestaApi($url, $username, $api_key);
		  $user_resp = $api->get("users", "getByUsername", array('username' =>  $vis_email));
		  $user_response=$user_resp->response();
		  $user_details = get_object_vars($user_response);
		  $user_id=$user_details['id'];
		  if(!empty($user_details))
		  {
			  $client_response = $api->post("clients", "getByUserId", array('user_id' => $user_id));
			  $client_resp = $client_response->response();
			  $client_details = get_object_vars($client_resp);
			  $client_id=$client_details['id'];
			  if(!empty($client_details))
			  {
			  $package_response = $api->get("services", "getList", array('client_id' => $client_id));
			  $package_resp = $package_response->response();
			  if(!empty($package_resp))
			  {
				  $package_info=$package_info1=array();
				  for($i=0;$i<count($package_resp);$i++)
				  {
					 $package_details = get_object_vars($package_resp[$i]);
					 $package = get_object_vars($package_details['package']);
					 $package_price_details = get_object_vars($package_details['package_pricing']);
					  $package_info1[$i]['pack_id']=(!empty($package['id']))?$package['id']:'';
					  $package_info1[$i]['pack_name']=(!empty($package['name']))?$package['name']:'';
					  $package_info1[$i]['client_name']=((!empty($package_details['client_first_name']))?$package_details['client_first_name']:'').' '.((!empty($package_details['client_last_name']))?$package_details['client_last_name']:''); 
					  $package_info1[$i]['qty']=(!empty($package_details['qty']))?$package_details['qty']:'';
					  $package_info1[$i]['status']=(!empty($package['status']))?$package['status']:'';
					  $package_info1[$i]['term']=((!empty($package_price_details['term']))?$package_price_details['term']:'').' '.((!empty($package_price_details['period']))?$package_price_details['period']:'');
					  $package_info1[$i]['price']=(!empty($package_price_details['price']))?$package_price_details['price']:'';
					  $package_info1[$i]['currency']=(!empty($package_price_details['currency']))?$package_price_details['currency']:'';
				  } 	  
			  }
			  else
			  {
				  print_r($package_response->errors());
			  }
			  }
			 }
		  }
		  $new_package_info=array_unique($package_info1, SORT_REGULAR);
		  $view_info['page_count']=(count($new_package_info)==0)?0:ceil(count($new_package_info)/3);
		  $package_info['page']=$operation['vis_page'];
		  $start=$operation['vis_page']*3;
		  $end=$start+3;
		  if($end>count($new_package_info)) $end=count($new_package_info);
		  for($i=$start; $i<$end;$i++) 
		  $package_info[]=$new_package_info[$i];
		  include(VIS_PATH_TEMPLATE.'blesta_package.php');
		  exit;	
	}	
	function get_labels($operation) {
		global $vis_language;
	    $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
	    $ticket_object=new class_ticket($database);
		$department_details=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($department_details!=-1){
			if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) {
				if($filter!='') $filter.=' and ';
				$filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))';
			}
			if($filter!='') $filter.=' and ';
			$filter.='is_enabled=1';
			$label_list=$ticket_object->get_labels_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			$database->database_disconnect();
			echo get_xml($label_list, 'labels');
		}
    }


	function get_tickets_reply($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		$reply_module ='ticket';
		if(isset($operation['vis_problem_id'])){
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
			$problem_object=new class_problem($database);
			$filter1 = " attach_type=1 AND child_id=".$operation['vis_problem_id'];
			list($total_ticket, $attached_ticket)=$problem_object->get_ticket_attached_problem($filter1, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($attached_ticket==-1){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");$(".modal").modal("toggle");</script>';
				return false;
			}else{
				$attached_id='';
				foreach($attached_ticket as $ticket_details)
					$attached_id .=$ticket_details['ticket_id'].',';
				$operation['vis_ticket_id']=substr($attached_id, 0, -1);
			}
			$reply_module ='problem';
		}
		##reply all linked tickets		
		if(isset($operation['vis_changes_id'])){
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
			$problem_object=new class_problem($database);
			$filter1 = " attach_type=6 AND child_id=".$operation['vis_changes_id'];
			list($total_ticket, $attached_ticket)=$problem_object->get_ticket_attached_problem($filter1, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($attached_ticket==-1){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");$(".modal").modal("toggle");</script>';
				return false;
			}else{
				$attached_id='';
				foreach($attached_ticket as $ticket_details)
					$attached_id .=$ticket_details['ticket_id'].',';
				$operation['vis_ticket_id']=substr($attached_id, 0, -1);
			}
			$reply_module ='changes';
		}
		###reply all linked tickets		
        $ticket_list=$object->get_ticket('ticket_id in ('.$operation['vis_ticket_id'].')', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $ticket_list=$ticket_list[1];
        
		$status_id=array();
		$status_department=$object->get_status_list('is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$status_department1='';
		for($i=0;$i<count($status_department); $i++)
		{
			$department_list=$status_department[$i]['department_access'];
			if($department_list==0 || $staff_department==0 || $staff_department_array==0){
				$list[]=$status_department[$i];
			}
			else{
				$status_department1=explode(',', $department_list);
				for($j=0;$j<count($staff_department_array); $j++){
					if(!in_array($status_department[$i]['status_id'],$status_id)){
						if(in_array($staff_department_array[$j], $status_department1)){
							$list[]=$status_department[$i];
							$status_id[]=$status_department[$i]['status_id'];
						}
					}
				}
			}
		}
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'reply_mass_tickets.php');
        return true;
    }
	
	function mass_reply_tickets($operation) { //print_r($operation); die;
        global $vis_language, $operation_hnd;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff_object=new class_staff($database);	
		$data['vis_ticket_post'] = addslashes($data['vis_ticket_post']);
		if(isset($operation['vis_action']))$data=parse_form_array($operation['vis_action']); else $data=$operation;
		list($count_ticket,$ticket_list)=$ticket_object->get_ticket('ticket_id in ('.$data['vis_ticket_mass_id'].')', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		
		$ticket_array=explode(',',$data['vis_ticket_mass_id']);
		
		if(!isset($data['vis_ticket_post']) || (isset($data['vis_ticket_post']) && trim(strip_tags($data['vis_ticket_post'],"<img>"))=="")) {			
             echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGPOSTMESSAGENOTFOUND'].'"); </script>';
            return false;
        }

		if($count_ticket['total']>0){
			foreach($ticket_list as $ticket_details){ 
				$action = '';
				
				if(trim($ticket_details['recipients'])=='') 
					$ticket_details['recipients']=$ticket_details['email'];
				
				if($ticket_details['email']=='' && $ticket_details['channel_id']==4){
					include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
					$client_object=new class_client($database);
					$filter='salt="'.$ticket_details['salt'].'"';
					list($client_info, $client_details)=$client_object->get_client($filter, 1, 0, '', '', VIS_LOCATION_AREA);
					$ticket_details['recipients']=$client_details[0]['user_name'];	
					$ticket_details['client_id']=$client_details[0]['client_id'];			
				}
				if($ticket_details['email']=='' && $ticket_details['channel_id']==3){
					$ticket_details['recipients']=$ticket_details['last_replier_email'];
				}
				$ticket_details['recipients']=trim($ticket_details['recipients'], ' ,');
								
				$draftpost_details=$ticket_object->get_ticket_draftpost($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
				$signaturedata=-1;$signature='';
				
				$signaturedata=$staff_object->get_signature('staff_id='.VIS_STAFF_ID.' and department_id='.$ticket_details['department_id'].' and is_forum=0', VIS_STAFF_ID, VIS_LOCATION_AREA);
				
				if($signaturedata!=-1) $signature=$signaturedata[0]['content'];
				$ticket_posts=(isset($signature) && $signature!='')? $data['vis_ticket_post'].'<br /><br />'.$signature:$data['vis_ticket_post'];
				
				$from_email=$ticket_object->get_from_email($ticket_details['department_id'] ,VIS_STAFF_ID, VIS_LOCATION_AREA);
				$vis_from =$from_email[0]['override_name'].' &lt;'.$from_email[0]['override_email'].'&gt;';
				
				
				if(isset($data['vis_sendmail']) && $data['vis_sendmail']==1){
					$action .= 'vis_sendmail=1&';
				}
				if(isset($data['vis_private']) && $data['vis_private']==1){
					$action .= 'vis_private=1&';
				}
				$vis_attachments= '';
				if(isset($data['vis_attachments']) && $data['vis_attachments']!=""){
					$vis_attachments = $data['vis_attachments'];
				}
				
				$vis_internal_ticket = ($ticket_details['client_id']==0)?1:0; 
				
				$action .= 'vis_post_id='.$draftpost_details['draft_id'].'&vis_ticket_id='.$ticket_details['ticket_id'].'&vis_channel='.$ticket_details['channel_id'].'&vis_to_email='.$ticket_details['recipients'].'&vis_internal_ticket='.$vis_internal_ticket.'&vis_people=&vis_search_text=&vis_ticket_post='.urlencode($ticket_posts).'&vis_location=1&vis_attachments='.$vis_attachments.'&vis_department='.$ticket_details['department_id'].'&vis_status='.$data['vis_status'].'&vis_subject='.$ticket_details['subject'].'&vis_from='.$vis_from.'&vis_module=ticket&vis_operation=reply_ticket';
				$mass_array =array();
				$mass_array['vis_action']= $action;
				$mass_array['vis_ticket_mass']= '1';
				$ret = $this->reply_ticket($mass_array); 
			}
		}else{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
		}
				       
        if($ret) {
			if($data['reply_module']=='ticket'){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_workpanel_div").visExecution("load_area", {"vis_module":"ticket", "vis_operation":"filter_ticket", "vis_filter_id": 1}); $("#vis_global_msg_div").visExecution("load_operations",{"vis_module":"staff", "vis_operation":"refresh_leftpanel"}); $(".modal").modal("toggle");</script>';
			}else if($data['reply_module']=='problem'){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle");</script>';
			}else if($data['reply_module']=='changes'){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle");</script>';
			}
        }
        else
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
        $database->database_disconnect();
        return true;
    }
	function get_problem_solution($operation){
		global $vis_language;
		
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
		$problem_object=new class_problem($database);
		$filter=VIS_TABLE_PREFIX.'itil_problems.problem_id='.$operation['vis_problem_id'];
		list($problems_info, $problems_details)=$problem_object->get_problems($filter, $limit, $page, $sort_by, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$problems_details=$problems_details[0];

		//echo '<pre>===='; print_r($problems_details); echo '====</pre>';
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'selfhelp.php');
		$selfhelp_object=new class_selfhelp($database);
		$solution_details = -1;
		$data ='';
		if($operation['vis_solution_type']==0 && $problems_details['permanent_id']!=''){	
			$filter='article_id='.$problems_details['permanent_id'];
			list($categories_info, $solution_details)=$selfhelp_object->get_article($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
		if($operation['vis_solution_type']==1 && $problems_details['workaround_id']!=''){		
			$filter='article_id='.$problems_details['workaround_id'];
			list($categories_info, $solution_details)=$selfhelp_object->get_article($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
		if($solution_details!=-1){
			$data = $solution_details[0]['content']."<br>";
		}
		$database->database_disconnect();
		echo json_encode(array('list' => $data));
		return true;
	}
	
	##reply all linked tickets
	
	function get_changes_solution($operation){
		global $vis_language;
		
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'problem.php');
		$problem_object=new class_problem($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'changes.php');
        $changes_object=new class_changes($database);
		
		$filter=VIS_TABLE_PREFIX.'itil_changes.changes_id='.$operation['vis_changes_id'];
		 list($changes_info, $changes_details)=$changes_object->get_changes($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		//list($problems_info, $problems_details)=$problem_object->get_problems($filter, $limit, $page, $sort_by, VIS_STAFF_ID, VIS_LOCATION_AREA);
		//echo '<pre>===='; print_r($changes_details); echo '====</pre>';
		$changes_details=$changes_details[0];
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'selfhelp.php');
		$selfhelp_object=new class_selfhelp($database);
		$solution_details = -1;
		$data ='';
		$html='';
		if($operation['vis_solution_type']==0 && $changes_details['rollout']!=''){	
			$chnage_att_arr = explode(',',$changes_details['rollout_attachment']);
			
			$query = "SELECT `attachment_id`, `file_name` FROM `avis_attachment` WHERE  `attachment_id` in (".substr($changes_details['rollout_attachment'], 0, -1).")";
			$result = $database->query_exec($query);
			$resarr = $database->fetch_result_array($result);
			$temp = array();
			for($t=0;$t<count($resarr);$t++){
				$temp[$resarr[$t]['attachment_id']] = $resarr[$t]['file_name']; 
			}
			
			for($i=0;$i<(count($chnage_att_arr)-1);$i++){
			 $html .=	'<div class="btn-group wrapper-xxs">
								<span class="btn btn-xs alert-success">'.$temp[$chnage_att_arr[$i]].'</span>
								<button class="btn btn-xs alert-success" type="button" data-dismiss="alert" onclick="$(this).parent().remove(); vis_remove_attachment('.$chnage_att_arr[$i].',\'vis_attachments\');"><i class="vh vh-cross"></i></button>
							</div>';
			}
			$solution_details = $changes_details['rollout'].'#*****#'.$changes_details['rollout_attachment'].'#*****#'.$html;
		}
		if($operation['vis_solution_type']==1 && $changes_details['backout']!=''){		
			$chnage_att_arr = explode(',',$changes_details['backout_attachment']);
			
			$query = "SELECT `attachment_id`, `file_name` FROM `avis_attachment` WHERE  `attachment_id` in (".substr($changes_details['backout_attachment'], 0, -1).")";
			$result = $database->query_exec($query);
			$resarr = $database->fetch_result_array($result);
			$temp = array();
			for($t=0;$t<count($resarr);$t++){
				$temp[$resarr[$t]['attachment_id']] = $resarr[$t]['file_name']; 
			}
			for($i=0;$i<(count($chnage_att_arr)-1);$i++){
			 $html .=	'<div class="btn-group wrapper-xxs">
								<span class="btn btn-xs alert-success">'.$temp[$chnage_att_arr[$i]].'</span>
								<button class="btn btn-xs alert-success" type="button" data-dismiss="alert" onclick="$(this).parent().remove(); vis_remove_attachment('.$chnage_att_arr[$i].',\'vis_attachments\');"><i class="vh vh-cross"></i></button>
							</div>';
			}
			$solution_details = $changes_details['backout'].'#*****#'.$changes_details['backout_attachment'].'#*****#'.$html;			
			
			
			
		}
		if($solution_details!=-1){
			$data = $solution_details."<br>";
		}
		$database->database_disconnect();
		echo json_encode(array('list' => $data));
		return true;
	}
	
	##reply all linked tickets
	
    //client feedback
	function get_feedback($operation)
	{
		global $vis_language;
	    $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
		list($info, $modules)=$object->get_module('is_enabled=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        foreach($modules as $var) $module[$var['module']]=1;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        $userid=(defined('VIS_CLIENT_ID'))?VIS_CLIENT_ID:VIS_STAFF_ID;
        $filter1=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter1, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
		$ticket_details = $ticket_details[0];
        $derpartment_id = $ticket_details['department_id'];
        $ticket_id = $operation['ticket_id'];
        $breadcrumb['Home'] = 'index.php';  
		$breadcrumb['Feedback'] = ''; 
		$vis_title = $header_title='Feedback';
        $location=array(0=>3, 1=>3);
        $custIds = $ticket_object->get_custom_fields_id($operation['ticket_id']);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_obj=new class_setting($database);
        $module_setting=$setting_obj->get_module_setting('domain_id='.$domain.' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(isset($module_setting['vis_show_priority']) && ($module_setting['vis_show_priority']==0 ||$module_setting['vis_show_priority']==1))
			    $ticket_priority = -1;
		 if(isset($module_setting['vis_show_tickettype']) && ($module_setting['vis_show_tickettype']==0 || $module_setting['vis_show_tickettype']==1))
				$ticket_type = -1;
				
        if(VIS_ITIL==1){
				 $filter1='ticket_id='.$ticket_details['ticket_id'];
				 $service_ticket_details=$ticket_object->get_service_ticket_list($filter1, VIS_STAFF_ID, VIS_LOCATION_AREA);
				 $filter2=VIS_TABLE_PREFIX."itil_service_item.item_id=".$service_ticket_details[0]['service_item_id'];
				 $service_details=$setting_obj->get_service_item_list($filter2,$data='',VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
				 list($dpinf, $domain)=$setting_obj->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$service_details[0]['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				 $filter3 = VIS_TABLE_PREFIX.'customfield.customgroup_id='.$service_details[0]['item_id'].' and '.VIS_TABLE_PREFIX.'customfield.ci_type=2 and '.VIS_TABLE_PREFIX.'customfield_data.content!=""';
				 $service_custom_details=$setting_obj->get_service_custom_data($filter3, VIS_STAFF_ID, VIS_LOCATION_AREA);
		} 
			
		if( $custIds == -1)
        {
			$ticket_feedback =  (isset($data[2]))?$data[2] :'ticket-feedback';        
			$custom_field_var = $this->get_custom_fields($location, 0, $derpartment_id, $ticket_id, $database);
			$staffSettings=$object->get_settings('title="vis_head_menu_staffNm" and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    }
	    else $custom_field_var =$this->edit_custom_fields($location, $ticket_id , $derpartment_id, $database,1);
		
		
        include(VIS_PATH_TEMPLATE.'header.php');
        include(VIS_PATH_TEMPLATE.'client_feedback.php');
        include(VIS_PATH_TEMPLATE.'footer.php');
        return true;
	}
    function get_ticket_feedback($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        if(isset($operation['vis_readonly']) && $operation['vis_readonly']==1) $readonly=1;
        else $readonly=0;
        if($operation['vis_static_area'] == 'vis_feedback_popup_form')$readonly=1;
        $location=array(0=>'0', 1=>'3', 2=>'3');
		$custom_field_var=$this->edit_custom_fields($location, $operation['vis_ticket_id'], $operation['vis_department_id'], $database,$readonly); 
		
        $database->database_disconnect();
		if($operation['vis_static_area'] == 'vis_feedback_popup_form'){ 
			include(VIS_PATH_TEMPLATE.'feedback_details.php');
		}
		else{
			if($custom_field_var!='') echo '<form class="form-horizontal" name="frm_edit_custom" id="frm_edit_custom" method="post">'.$custom_field_var.'</form>';
			else echo '<section class="wrapper fullFrame" id="no_record_yet"><div class="fullMiddle">'.$vis_language['TXTNOTHINGTODISPLAY'].'</div></section>';
		}
        return true;
    }
	function service_request($operation){
        global $vis_language;
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'subsetting.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
	    $database=new class_database();
        $setting_object=new class_setting($database);
		$sub_object=new class_subsetting($database);
		$ticket_object=new class_ticket($database);
		$filter1 = VIS_TABLE_PREFIX.'itil_service_category.is_enabled=1';
        $service_cat_details=$setting_object->get_service_category_list($filter1,$data,VIS_STAFF_ID, VIS_LOCATION_AREA,$limit='');
		$department_details=$ticket_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
		//list($department_info,$department_details)=$sub_object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1','',0,0,VIS_STAFF_ID, VIS_LOCATION_AREA);
		/*$filter=VIS_TABLE_PREFIX.'staff.is_enabled=1 and '.VIS_TABLE_PREFIX.'staff.staff_id='.VIS_STAFF_ID;
        list($domain,$staff_list)=$setting_object->get_staff($filter,'','','',VIS_STAFF_ID, VIS_LOCATION_AREA);*/		
		$from_email=$ticket_object->get_from_email(0, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'service_request.php');
        return true;
    }
	
	 function article_search($operation){
		  global $vis_language;
		 include(VIS_PATH_TEMPLATE.'attach_article.php');
        return true;
	 }
	 ##listing popup
	 function show_schedule_details($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		$res	=	$ticket_object->get_schedule_type(" sch.ticket_id =".$operation['vis_ticket_id']);
		$res_ch	=	$ticket_object->get_chanel($operation['vis_ticket_id']);
		$startdate	=	date('M-jS, Y g:i a',($res[1][0]['startdate']+(VIS_TIMEZONE)));
		$enddate	=	date('M-jS, Y g:i a',($res[1][0]['enddate']+(VIS_TIMEZONE)));
		$arr_sch_type	=	array("Never","Daily","Weekly","Monthly");
		$arr_sch_days	=	array("1"=>"Sun","Mon","Tue","Wend","Thu","Fri","Sat");
		
		if($res[1][0]['scedule_type']== 1 ){
			$arr_days	=	explode(',',$res[1][0]['days']);
			for($i=0;$i<=count($arr_days);$i++){
				if($arr_days[$i]!= 0) $days[] = $arr_sch_days[$i+1];
			}
			$days = implode(',&nbsp;',$days);
		}else if($res[1][0]['scedule_type']== 2 ){
			$days	=	$arr_sch_days[$res[1][0]['days']];
		}
		
		if($res_ch['channel_id']<=18 && strstr($res_ch['icon_path'], "vh vh-")) {
			$icon = '<i class="'.$res_ch['icon_path'].' vh-lg"></i>';
		}else{
		 if(file_exists(VIS_PATH_PROFILE.$res_ch['icon_path']))
						$icon = '<img src="'.VIS_PATH_PROFILE.$res_ch['icon_path'].'" class="thumb-xxs">';
					else
						$icon = '<i class="vh vh-channel vh-lg"></i>';
		}
        if(isset($operation['vis_ticket_id']) && $operation['vis_ticket_id']!=""){
           	$details_txt= '<div><p class="form-group">'.$icon.'<b>&nbsp;&nbsp;'.$vis_language['TXTTICKETSCHEDULE'].'</b></p> ';			
			$details_txt .= '<p class="form-group"><label><b>'.$vis_language['TXTSTARTDATE'].'</b>: '.$startdate.'</label></p>';
 			if($res[1][0]['scedule_type']!= 0 ){ $details_txt .= '<p class="form-group"><label><b>'.$vis_language['TXTENDDATE'].'</b>: '.$enddate.'</label></p>'; }		
			$details_txt .= '<p class="form-group"><label><b>'.$vis_language['TXTRECURRENCE'].'</b>: '.$arr_sch_type[$res[1][0]['scedule_type']];
			if($res[1][0]['scedule_type']!= 0 && $res[1][0]['scedule_type'] != 3){	$details_txt .= ' ('.$days.')'; }
			$details_txt .= '</label></p></div>';
		}
		echo $details_txt;
    }
	
	function get_ticket_post($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $ticket_details = $ticket_details[0];
		$page=(isset($operation['vis_page']) && $operation['vis_page']!='')?$operation['vis_page']:1;
        $post_setting=$ticket_object->get_ticket_post_setting($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$post_setting['postcount'] = !isset($post_setting['postcount']) ? 10 : $post_setting['postcount'];
        $total_post_count=$ticket_object->get_total_post_count($ticket_details['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $post_details=$ticket_object->get_ticket_post($ticket_details['ticket_id'], 0, VIS_STAFF_ID, VIS_LOCATION_AREA, $page, $post_setting['postcount']); 
		$post_paging_count=($total_post_count==0 || $post_setting['postcount']==0)?0:ceil($total_post_count/$post_setting['postcount']);
        $show_inline_img=$ticket_object->get_inline_image_flag($ticket_details['ticket_id'], $post_setting['domainid'], VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $post_count=count($post_details);
		for($i=0;$i<count($post_details);$i++){
				$comment_details[$i]=(VIS_COMMENT_ACCESS==0)?-1:$ticket_object->get_post_comment($post_details[$i]['post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
				$validation_error[$i]=$ticket_object->get_post_error(' parent_id ='.$post_details[$i]['post_id'].' and remark_method = 1' , VIS_STAFF_ID, VIS_LOCATION_AREA);	
            }
			
			
       include(VIS_PATH_TEMPLATE.'ticket_post_list.php');
	}
	function pause_ticket_sla($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		//echo "<pre>";print_r($operation);
		
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $ticket_details = $ticket_details[0];
		if($ticket_details!=-1){
			
			if($ticket_details['due_time']<=0 && $ticket_details['user_replied']==1 && $ticket_details['status_id']!=3 && $ticket_details['sdue_time']!=0)$data['pause_dtime'] = $vis_language['TXTOVERDUE'];
			elseif($ticket_details['due_time']>0 && $ticket_details['user_replied']==1 && $ticket_details['status_id']!=3)$data['pause_dtime'] = $ticket_details['due_time'];
			else $data['pause_dtime'] = $vis_language['TXTUNDUE'];
			
			if($ticket_details['resolution_time']<=0 && $ticket_details['status_id']!=3 && $ticket_details['rdue_time']!=0) $data['pause_rtime'] = $vis_language['TXTOVERDUE']; 
			elseif($ticket_details['resolution_time']>0 && $ticket_details['status_id']!=3) $data['pause_rtime'] = $ticket_details['resolution_time'];
			else $data['pause_rtime'] = $vis_language['TXTUNDUE'];
			
			//$data['pause_dtime'] = $ticket_details['due_time'];
			//$data['pause_rtime'] = $ticket_details['resolution_time'];
			$data=array_merge($operation, $data);
			$res=$ticket_object->pause_sla($data, VIS_STAFF_ID, VIS_LOCATION_AREA);	
			if($res){
				$ticket_object->add_audit_log($ticket_details, 50, '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				global $operation_hnd;
				$operation_hnd->operation_flow($data,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
				$staff_object=new class_staff($database);
				$staff_object->apply_task_automation($data, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			}
			echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
			echo "$('#vis_details_list_".$operation['vis_ticket_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':".$operation['vis_ticket_id'].", 'vis_department_id':".$ticket_details['department_id'].", 'vis_readonly':1});</script>";
			
		}else{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
		}
	}
	function resume_ticket_sla($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		//echo "<pre>";print_r($operation);
		
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $ticket_details = $ticket_details[0];
		if($ticket_details!=-1){
			$data['pause_dtime'] = $ticket_details['pause_dtime'];
			$data['pause_rtime'] = $ticket_details['pause_rtime'];
			$data=array_merge($operation, $data);
			$res=$ticket_object->resume_sla($data, VIS_STAFF_ID, VIS_LOCATION_AREA);	
			if($res){
				$ticket_object->add_audit_log($ticket_details, 51, '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				global $operation_hnd;
				$operation_hnd->operation_flow($data,VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
				$staff_object=new class_staff($database);
				$staff_object->apply_task_automation($data, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
			}
			echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");';
			echo "$('#vis_details_list_".$operation['vis_ticket_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':".$operation['vis_ticket_id'].", 'vis_department_id':".$ticket_details['department_id'].", 'vis_readonly':1});</script>";
			
		}else{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].' "); </script>';
		}
	}
	##Redmine 
	function get_readmine_details($operation){
		global $vis_language;
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);			
		$filter='integration_type=37 and ticket_id='.$operation['vis_ticketid'];
		$redmine_link_details=$ticket_object->get_redmine_ticket_link($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'redmine.php');
	}
	function redmine_issue($operation){
		global $vis_language;
		$operation['redmine']='linkissue';
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);		
		$check_redmine_status	=	$sett_obj->get_redmine('check_status');		
		$projectAll	=	$sett_obj->get_redmine('projectAll');		
		$filter='integration_type=37 and ticket_id='.$operation['vis_ticketid'];
		$redmine_link_details=$ticket_object->get_redmine_ticket_link($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		//$issueByProjectId	=	$client->api('issue')->all(array('project_id' => 3));		
		if($redmine_link_details!=-1){			
			$issue_details 	=	$sett_obj->get_redmine('showIssue',array('issue_id' => $redmine_link_details[0]['link_id']));		
		}		
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'redmine_activity.php');
	}
	function link_redmine_issue($operation){ 
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);	
		$check_redmine_status	=	$sett_obj->get_redmine('check_status');	
		$ret= $ticket_object->link_redmine_issue($operation);
		if($ret==1) {
			if($operation['vis_ticketid']=='' && $operation['vis_ticket_id']!=''){ $operation['vis_ticketid'] = $operation['vis_ticket_id'];}
			$filter='integration_type=37 and ticket_id='.$operation['vis_ticketid'];
			$redmine_link_details = $ticket_object->get_redmine_ticket_link($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($redmine_link_details!=-1){			
				$issue_details 	=	$sett_obj->get_redmine('showIssue',array('issue_id' => $redmine_link_details[0]['link_id']));
			}
			$msg= 1;
			$operation['redmine']='linkissue';			
			include(VIS_PATH_TEMPLATE.'redmine_activity.php');	
	    }	
		$database->database_disconnect();		
	}
	function unlink_redmine_issue($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		$filter = 'ticket_id='.$operation['vis_ticketid'].' and integration_type=37';
		$ret = $ticket_object->delete_link_jira_issue($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$database->database_disconnect();
		if($ret) {
			$operation['redmine']='linkissue';
			$redmine_link_details=-1;
			$vis_hide = 1;
			$msg=0;
			include(VIS_PATH_TEMPLATE.'redmine_activity.php');	
	    }			
	}
	function get_issue($operation){ 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);		
		$check_redmine_status	=	$setting_object->get_redmine('check_status');
		$vis_project	=	$operation['vis_project'];
		$proj_arr	=	array('project_id' => $vis_project); 
		$redmine_issue_list	=	$setting_object->get_redmine('issueByProjectId',$proj_arr);
		if(count($redmine_issue_list['issues']) > 5) $src= 'data-live-search="true"' ;
		echo '<select class="form-control input-sm selectpicker"  id="vis_issue" name="vis_issue" '.$src.' >';						
		echo '<option value="0" >'.$vis_language['TXTSELECTISSUE'].'</option>';				
		for($i=0;$i< count($redmine_issue_list['issues']); $i++){
			echo '<option value="'.$redmine_issue_list['issues'][$i]['id'].'" >'.$redmine_issue_list['issues'][$i]['id'].' - '.$redmine_issue_list['issues'][$i]['subject'].'</option>';	
		}
		echo '</select>';
	}
	function get_redmine_create_issue($operation) {
	    global $vis_language;
		$operation['redmine']	=	'createissue';
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);		
		$check_redmine_status	=	$sett_obj->get_redmine('check_status');		
		$projectAll	=	$sett_obj->get_redmine('projectAll');		
		$ticket_details = $ticket_object->get_ticket_details($operation['vis_ticketid']);
		$ticket_details 	=	$ticket_details[1][0];
		//print_r($ticket_details);
		$database->database_disconnect();
		include(VIS_PATH_TEMPLATE.'redmine_activity.php');	
			
    }
	function create_redmine_issue($operation){ 
		global $vis_language;
		$database=new class_database();
		$data=parse_form_array($operation['vis_action']);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);		
			
		$query	=	"SELECT `domain_url` FROM `".VIS_TABLE_PREFIX."domain` WHERE  `domain_id` = ".VIS_DOMAIN;	
		$result=$database->query_exec($query);
        $dom_result = $database->fetch_result_array($result);
		
		$query	=	"SELECT  `ticket_hash` FROM `".VIS_TABLE_PREFIX."ticket` WHERE  `ticket_id` = ".$data['vis_ticketid'];	
		$result=$database->query_exec($query);
        $ticket_result = $database->fetch_result_array($result);
		
		$query	=	"SELECT `post_id`,`content` FROM `".VIS_TABLE_PREFIX."ticket_post` WHERE  `ticket_id` = ".$data['vis_ticketid'];		
		$result=$database->query_exec($query);
        $post_result = $database->fetch_result_array($result);
		$post_data = '';
		for($i=(count($post_result)-1);$i>=0;$i--){
			$post_data	.=	$post_result[$i]['content']."\n\n";
			$parent_id[] =  $post_result[$i]['post_id'];
		}
		$helpdesk_url = $dom_result[0]['domain_url']."manage/#/ticket/ticket_details/".$ticket_result[0]['ticket_hash']."/".$data['vis_ticketid'];
		$post_data = $post_data."<br/>Helpdesk Url:<br/><a href='".$helpdesk_url."' target='_blank' >".$helpdesk_url."</a>";
		$post_data = str_replace("</p>","\n",$post_data); 
		$post_data = str_replace("<br>","\n",$post_data);
		$post_data = str_replace("<br/>","\n",$post_data);		
		$post_data= strip_tags($post_data);
		##atachment
		$query	=	"SELECT * FROM `avis_attachment` WHERE `parent_id` IN (".implode(',',$parent_id).")";	
		$result=$database->query_exec($query);
        $att_result = $database->fetch_result_array($result);
		$attchmentFiles = array();
		$customeFields	= array();
		## uncomment following $customeFields for testing purpose on ocr-inc's redmine setup			
		/*$customeFields	= array(
									array('id' => 43, 'name' => 'Client issue/Ref #', 'value' => '' ),
									array('id' => 2, 'name' => 'Primary Mod/Ref #', 'value' => 'HelpDesk'),
									array('id' => 26, 'name' => 'Rel Notes Reqd/Ref #', 'value' => 'Yes' ),
									array('id' => 54, 'name' => 'Issue in/Ref #', 'value' => 'CLIENT' ),	
									array('id' => 32, 'name' => 'Client Name', 'value' => 'HelpDesk'),
							   ); */
		if($att_result!=-1){
			for($a=0;$a<count($att_result);$a++){
				$filecontent = file_get_contents(VIS_PATH_FILES.$att_result[$a]['content']);			
				$upload = $sett_obj->get_redmine('uploadFileToIssue',$filecontent);
				$file_type	=	explode('/',$att_result[$a]['file_type']);
				$attchmentFiles[]	=	array(
											  'token' => $upload->upload->token,
											  'filename' => $att_result[$a]['file_name'],
											  'content_type' => 'application/'.$file_type[0],										  
											);			
			}
		}
		##Post redmine data		
		$issue_data	=	array('issue'=>array(
								'project_id' => $data['vis_project'],
								'subject' => $data['vis_subject'],
								'description' => $post_data,	
								'uploads' => $attchmentFiles,	
								'custom_fields' => $customeFields,
							 ),); 					 
		$createIssue	=	$sett_obj->get_redmine('createIssue',$issue_data);
		$ins_issue_id	=	$createIssue['issue']['id']; 
		$data['vis_issue'] = $ins_issue_id;	
		$data['vis_ticket_id'] = $data['vis_ticketid'];
		$ticket_object->link_redmine_issue($data,$ins_issue_id);
		
		$filter='integration_type=37 and ticket_id='.$data['vis_ticketid'];
		$redmine_link_details = $ticket_object->get_redmine_ticket_link($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($redmine_link_details!=-1){			
			$issue_details 	=	$sett_obj->get_redmine('showIssue',array('issue_id' => $redmine_link_details[0]['link_id']));
			$operation['redmine']='linkissue';	
			include(VIS_PATH_TEMPLATE.'redmine_activity.php');	
			echo "<script>$('#vis_details_list').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'redmine_issue','vis_ticketid':'".$data['vis_ticketid']."'}); </script>";
		}		
		$database->database_disconnect();		
	}
	##Exotel
	function open_new_exo_auto_ticket($operation) { 
	    global $vis_language, $operation_hnd;
	    $is_approved=1;
        $is_banned=0;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $database=new class_database();
        if((VIS_LOCATION_AREA == 2 || VIS_LOCATION_AREA == 4)) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
	    $client_obj=new class_client($database);
        $ticket_object=new class_ticket($database);
		$userid = ($data['vis_staff']!='')?$data['vis_staff']:'0';
		
        $ret=$ticket_object->add_ticket($data, $userid, VIS_LOCATION_AREA); 
	    $data['vis_ticket_id']=$ret;	
		 if($ret) {
            global $operation_hnd;
            $data['vis_is_client']=(isset($data['vis_as_client']))?1:0;			
		    $data['vis_module']='ticket';
            $data['vis_operation']='open_new_ticket';
			$data['vis_department'] = 1;
			$data['vis_exotel'] = 1;
			$operation_hnd->check_automation($data, $database);
												
			if($operation['vis_cronschedule_flag']!=1){
            $operation_hnd->operation_flow($data, $userid, VIS_LOCATION_AREA, $database);
			}
	    }
	    return $ret;
    }
	#create auto exotel ticket via cron for manage portal
	function exo_staff_auto_ticket($operation){  //error_reporting( E_ALL );
		global $vis_language, $operation_hnd;
		$database=new class_database();
		include_once(VIS_PATH_PLUGINS.'exotel/class_exotel.php'); ##exotel integration	
		$obj_exotel	=	new class_exotel();	
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php'); 
		$setting_obj=new class_setting($database);	
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
		$ticket_obj=new class_ticket($database);
		
		$filter='integration_type=38 AND is_enabled = 1';
		list($exotel_info, $exotel_details)=$setting_obj->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA,' ORDER bY domain_id DESC');			
		$update_rec = array();
		if($exotel_details!=-1){ 
			for($i=0;$i<count($exotel_details);$i++){ 
				$exo_data = array("exotel_sid"=>$exotel_details[$i]['host_name'],
							  "exotel_token"=>$exotel_details[$i]['user_name'],
							 );
				$domain_filter = '';
				if($exotel_details[$i]['domain_id']!=0){ $domain_filter = " AND domain=".$exotel_details[$i]['domain_id']; }
				$query = "SELECT `id`,`sid`,`staff_id`,`domain`,`request_type`,`department` FROM `avis_exo_call_details` WHERE `auto_ticket` = 0 AND `sid`<>'' AND `sid`<>'Array'  ".$domain_filter." LIMIT 0,50";
				$result=$database->query_exec($query);
				$sid_arr = $database->fetch_result_array($result); 
			
				 for($d=0;$d<count($sid_arr);$d++){
				 
					if($sid_arr[$d]['request_type']==0){ //call
						$call_details = $obj_exotel->get_call_details($sid_arr[$d]['sid'],$exo_data);
						$e_app = $this->check_exophone_isactive($exotel_details[$i]['integration_id'],$call_details['Call']['PhoneNumberSid']);					
						$ticket_id =0;	
						if($call_details['Call']['Status']=='completed'){
						//if($call_details['Call']['Status']=='completed' && $call_details['Call']['Direction']== 'outbound-api'){		
						//if($call_details['Call']['Direction']== 'outbound-api'){
							$subject = 'Exotel client '.trim($call_details['Call']['To']).'_'.microtime();
						
							$html ='';
							$html .= '<p> '.$vis_language['TXTFROM'].' : '.$call_details['Call']['From'].'</p>';
							$html .= '<p>'.$vis_language['TXTTO'].' : '.$call_details['Call']['To'].'</p>';
							$html .= '<p>'.$vis_language['TXTEXOPHONE'].' : '.$call_details['Call']['PhoneNumberSid'].'</p>';
							$html .= '<p>'.$vis_language['TXTSTARTDATE'].' : '.format_datetime(strtotime($call_details['Call']['StartTime'])).'</p>';
							$html .= '<p>'.$vis_language['TXTENDDATE'].' : '.format_datetime(strtotime($call_details['Call']['EndTime'])).'</p>';
							$html .= '<p>'.$vis_language['TXTDURATION'].' : '.$call_details['Call']['Duration'].' '.$vis_language['TXTSECONDS'].'</p>';
							$html .= '<p>'.$vis_language['TXTPRICE'].' : '.$call_details['Call']['Price'].'</p>';
							$html .= '<p>'.$vis_language['TXTDIRECTION'].' : '.$call_details['Call']['Direction'].'</p>';
							$html .= '<p>'.$vis_language['TXTSTATUS'].' : '.$call_details['Call']['Status'].'</p>';
							if($call_details['Call']['RecordingUrl'] !='' && !is_array($call_details['Call']['RecordingUrl'])){
							$html .= '<p>'.$vis_language['TXTRECORDING'].' : <audio src="'.trim($call_details['Call']['RecordingUrl']).'" controls preload="auto" autobuffer></audio></p>';
							}
							$data = array();
							$data['subject'] = $subject;
							$data['ticket_post'] = $html;
							$data['domain'] = $sid_arr[$d]['domain'];
							$data['contact_no'] = $call_details['Call']['To'];
							$data['staff_id'] =  $sid_arr[$d]['staff_id'];	
							$data['exophone'] = $call_details['Call']['PhoneNumberSid'];
						}
						
					}else if($sid_arr[$d]['request_type']==1){ //sms				   
						$call_details = $obj_exotel->get_sms_details($sid_arr[$d]['sid'],$exo_data);
							$e_app= 1;
							$subject = 'Exotel SMS '.trim($call_details['SMSMessage']['To']).'_'.microtime();
						
							$html ='';
							$html .= '<p> '.$vis_language['TXTFROM'].' : '.$call_details['SMSMessage']['From'].'</p>';
							$html .= '<p>'.$vis_language['TXTTO'].' : '.$call_details['SMSMessage']['To'].'</p>';
							$html .= '<p>'.$vis_language['TXTBODY'].' : '.str_replace("\r\n","<br/>",$call_details['SMSMessage']['Body']).'</p>';
							$html .= '<p>'.$vis_language['TXTSENSTDATE'].' : '.format_datetime(strtotime($call_details['SMSMessage']['DateSent'])).'</p>';						
							$html .= '<p>'.$vis_language['TXTPRICE'].' : '.$call_details['SMSMessage']['Price'].'</p>';
							$html .= '<p>'.$vis_language['TXTDIRECTION'].' : '.$call_details['SMSMessage']['Direction'].'</p>';
							$html .= '<p>'.$vis_language['TXTSTATUS'].' : '.$call_details['SMSMessage']['Status'].'</p>';						
							$data = array();
							$data['subject'] = $subject;
							$data['ticket_post'] = $html;
							$data['domain'] = $sid_arr[$d]['domain'];
							$data['contact_no'] = $call_details['SMSMessage']['To'];
							$data['staff_id'] =  $sid_arr[$d]['staff_id'];	
							$data['dept'] = $sid_arr[$d]['department'];
							
					}
					if($e_app!=-1){
						$ticket_id = $ticket_obj->exo_create_staff_auto_ticket($data);
						if($ticket_id){ 
						 $query 	 = "UPDATE `avis_exo_call_details` SET `auto_ticket`=".$ticket_id." WHERE `id` ='".$sid_arr[$d]['id']."'";
						 $result	 = $database->query_exec($query);	    
						}	
					}else{
						$query 	 = "UPDATE `avis_exo_call_details` SET `auto_ticket`='-1' WHERE `id` ='".$sid_arr[$d]['id']."'";
						 $result	 = $database->query_exec($query);						
					}
							
		
				 }//record for			
			} 	//app for loop	
		
		}
	}//func	
	function check_exophone_isactive($integration_id,$exo_phone){
		$database=new class_database();
		$query = "SELECT * FROM avis_exotel_apps WHERE `integration_id` = '".$integration_id."' AND `auto_ticket`=1 AND FIND_IN_SET('".trim($exo_phone)."', exophones )"; 
		  
		  $result	 = $database->query_exec($query);
		   $exo_app = $database->fetch_result_array($result);
		   return $exo_app;
	}	
	###Exotel
	##Form creation tool
	
	function forms($operation) { 
        global $vis_language;
		$action = explode('/',strstr($_SERVER['REQUEST_URI'],'?/'));
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object = new class_setting($database);
        
		$domain_detaiis = $setting_object->get_domain_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		for($d=0;$d<count($domain_detaiis);$d++){
			$dom_arr[]= $domain_detaiis[$d]['domain'];
		}
		$other_domain = 0;
		
		if(isset($_SERVER['HTTP_REFERER'])){
			$ref = explode('//',$_SERVER['HTTP_REFERER']);
			$dom = $ref[1];
			if(strcasecmp(substr($ref[1],0,4),'www.')==0){
				$dom = substr($ref[1],4,strlen($ref[1]));
			}
			$dom = explode('/',$dom);
			$dom =$dom[0];
			$other_domain = (in_array($dom,$dom_arr))?0:1;
		}		
		
		
			$filter=VIS_TABLE_PREFIX.'formgroup.formgroup_id='.$action[3].' ';
			$form_group = $setting_object->get_form_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			
			if($other_domain==1 || $form_group[0]['hdformheader']!=1){
				echo '<style>#iframe_hd_container,#iframe_hd_header,#iframe_hd_div,#v4wid{ display:none!important; } </style>';
			}

            //$header_title=($form_group[0]['form_name'])?$form_group[0]['form_name']:$vis_language['TXTSUBMITTICKET'];
												$header_title=$vis_language['TXTFORM'];
												
			if($other_domain!=1){ 
				$title = $vis_title = $header_title;
				$breadcrumb['Home'] = 'index.php'; 
				$breadcrumb[$header_title] = ''; 				
			}
			
            include(VIS_PATH_TEMPLATE.'header.php');		
            $form_field_var=$this->get_form_fields($action[3]); 
			$query = "SELECT count(*) FROM `avis_formfield` WHERE `field_type` <> 10 AND `is_enabled`=1 AND `formgroup_id` =".$form_group[0]['formgroup_id'];
			$result = $database->query_exec($query); 
			$ffc= $database->fetch_result($result);
			if($form_group[0]['is_enabled']==1 && $ffc['count(*)']!=0){			
				include(VIS_PATH_TEMPLATE.'submit_form.php');
				include(VIS_PATH_TEMPLATE.'footer.php');
			}else{  include(VIS_PATH_TEMPLATE.'no_form_data.php'); }
            
            return false;       
       
    }
	function get_form_fields($form_id){
		global $vis_language;
		$database=new class_database();
        $form_field_var='';
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object = new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object = new class_ticket($database);
        //for($i=0;$i<count($location); )
		$filter=VIS_TABLE_PREFIX.'formgroup.formgroup_id='.$form_id.' ';
        $form_group = $setting_object->get_form_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		//echo'==='.print_r($form_group); die;
		
	    if($form_group != -1){
            for($i=0; $i<count($form_group); $i++){
                $filter=' '.VIS_TABLE_PREFIX.'formfield.formgroup_id='.$form_group[$i]['formgroup_id'].' and '.VIS_TABLE_PREFIX.'formfield.is_enabled=1 ';;
                list($form_field_info, $form_fields_details)=$setting_object->get_formfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
			    if($form_fields_details != -1){
                    $cc_count=0;                    
					//echo '<pre>'; print_r($form_fields_details); echo '</pre>';				
                    for($j=0; $j<count($form_fields_details); $j++){
						$label = (trim($form_fields_details[$j]['field_description']!=''))?'<label class="control-label">'.stripslashes($form_fields_details[$j]['field_description']).'</label>':'';
                         $val=''; 
						 $placeholder = stripslashes($form_fields_details[$j]['placeholder']);
						 $tooltip = stripslashes($form_fields_details[$j]['tooltip']);
						 $html_attribute = stripslashes($form_fields_details[$j]['html_attribute']);
						 $is_required = $form_fields_details[$j]['is_required'];
						 $is_inline	=	$form_fields_details[$j]['inline'];
						 $is_editor	=	$form_fields_details[$j]['is_editor'];
						 
                        if($form_fields_details[$j]['field_type']<4 || $form_fields_details[$j]['field_type']==8 || $form_fields_details[$j]['field_type']==9 || $form_fields_details[$j]['field_type']==10){
                            $val = stripslashes($form_fields_details[$j]['default_value']);
                            $req = ($form_fields_details[$j]['is_required']==1)?' <span class="vh-red">*</span>':'';    
							
							
							if($form_fields_details[$j]['field_type']==1)
                            {
							       $form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$tooltip.'" for="'.$form_fields_details[$j]['field_name'].'">'.$form_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><input type="text" value="'.$val.'"  name="field'.$form_fields_details[$j]['formfield_id'].'" id="field'.$form_fields_details[$j]['formfield_id'].'" class="form-control input-sm"  title="'.$tooltip.'" placeholder="'.$placeholder.'"  '.$html_attribute.' >
								   '.$label.'</div></div>';                                
                           }
                           if($form_fields_details[$j]['field_type']==2)
                            {       
									
                                    $form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$form_fields_details[$j]['field_name'].'" title="'.$tooltip.'">'.$form_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><input type="password" name="field'.$form_fields_details[$j]['formfield_id'].'" id="field'.$form_fields_details[$j]['formfield_id'].'" class="form-control input-sm" value="'.$val.'" title="'.$tooltip.'" placeholder="'.$placeholder.'"   '.$html_attribute.' >
									'.$label.'</div></div>';								
                            }
                            if( $form_fields_details[$j]['field_type']==3)
                            {                              
                                    $form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$form_fields_details[$j]['field_name'].'" title="'.$tooltip.'">'.$form_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><textarea name="field'.$form_fields_details[$j]['formfield_id'].'" id="field'.$form_fields_details[$j]['formfield_id'].'" class="form-control input-sm" title="'.$tooltip.'" placeholder="'.$placeholder.'"   '.$html_attribute.' >'.$val.'</textarea>
									'.$label.'</div></div>';
									if($is_editor==1){
										$form_field_var.='<script>
														$(function() {
															$("#field'.$form_fields_details[$j]['formfield_id'].'").redactor({
																buttonSource: true,
																minHeight: 180, // pixels
																maxHeight: 180,
																imageUpload: "index.php?vis_tmpst=" + new Date().getTime() + "&vis_module=ticket&vis_operation=upload_file&vis_static_area=editor_image_upload",
																imageUploadParam: "files",
																cleanOnPaste: false,
																paragraphize: false,
																replaceDivs: false,
																linebreaks: true,
																deniedTags: ["html", "head", "link", "body", "meta", "script","applet"]
															});
															$(".redactor-toolbar").attr("z-index", "3 !important");
														});
												</script>';
									}
                                  
                            }
                            if($form_fields_details[$j]['field_type']==8)
                            {							  
								$form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" title="'.$tooltip.'">'.$form_fields_details[$j]['field_name'].$req.'</label><div class="col-sm-8"><span class="input-group-addon no-padder no-borders"><input type="text" name="field'.$form_fields_details[$j]['formfield_id'].'" id="field'.$form_fields_details[$j]['formfield_id'].'" class="form-control input-sm start" value="'.$val.'"   title="'.$tooltip.'" placeholder="'.$placeholder.'"   '.$html_attribute.' ></span>'.$label.'</div></div>';							
                                  
                            } 


							if($form_fields_details[$j]['field_type']==9)
                            {
							   $attachment = $form_fields_details[$j]['no_of_file'];
							   $dispfile = ($attachment>0)?'':'display:none';
							   if($attachment>0){
							   $form_field_var.= '<div class="form-group m-b-none">
								 <label for="file" class="col-sm-2 control-label">'.$form_fields_details[$j]['field_name'].$req.'</label>							
								<div class="col-sm-2 control-label" style="text-align: left !important;'.$dispfile.'">
									<span class="btn btn-link btn-sm link btn_upload_file" id="vis_attach_file'.$form_fields_details[$j]['formfield_id'].'">'.$vis_language['TXTATTACHFILE'].'<input class="form-control" type="file" id="fileupload'.$form_fields_details[$j]['formfield_id'].'"></span>
									<input type="hidden" id="vis_max_attach'.$form_fields_details[$j]['formfield_id'].'" name="vis_max_attach'.$form_fields_details[$j]['formfield_id'].'" value="'.($attachment-1).'" />
									<input type="hidden" id="vis_attachment_count'.$form_fields_details[$j]['formfield_id'].'" name="vis_attachment_count'.$form_fields_details[$j]['formfield_id'].'" value="0" />';
									//<div style="display:none;" id="vis_attachments'.$form_fields_details[$j]['formfield_id'].'"></div>
								$form_field_var.= '</div>
								<div class="col-sm-6 p-l-none">
									   <div id="progress'.$form_fields_details[$j]['formfield_id'].'" class="progress" style="display:none; height:14px;"><div class="progress-bar progress-bar-success"></div></div>
								</div>
							  </div>
							  <div class="form-group">
								 <label for="Message" class="col-sm-2 control-label"></label>
								 <div id="vis_new_attachments'.$form_fields_details[$j]['formfield_id'].'" class="col-sm-8 p-l-none"></div>
							  </div>
							  ';
						   }
						  
						   ?>
						   <script>
						   $(function () {
										var url = 'index.php?vis_module=ticket&vis_operation=upload_file&vis_field_id=<?=$form_fields_details[$j]['formfield_id']; ?>';
										$('#fileupload<?=$form_fields_details[$j]['formfield_id']; ?>').fileupload({
											url: url,
											add: function (e, data) {
												var size=(data.files[0].size / 1000000).toFixed(2);
												var max_upload_size=parseInt('<?=ini_get('upload_max_filesize')?>');
												if(size>max_upload_size)
												{
													 $("#vis_submit_err_div").show(); 
													 $("#vis_submit_err_div").html('<?php echo $vis_language['MSGSIZEERROR']; ?>'); window.scrollTo(0,0);
													 setTimeout(function(){$("#vis_submit_err_div").hide();},10000);
												}
												else
												{
													data.submit();
												}
											},
											done: function (e, data) {
												if(data.result == 1) {
													  $("#vis_submit_err_div").show(); 
													 $("#vis_submit_err_div").html('<?php echo $vis_language['ERRORMSGEXTENSION']; ?>'); window.scrollTo(0,0);
													 setTimeout(function(){$("#vis_submit_err_div").hide();},10000);
													
												}
												else if(data.result == 2) {
													 $("#vis_submit_err_div").show(); 
													 $("#vis_submit_err_div").html('<?php echo $vis_language['MSGSIZEERROR']; ?>'); window.scrollTo(0,0);
													 setTimeout(function(){$("#vis_submit_err_div").hide();},10000);
													
												}
												else if(data.result == 3) {
													 $("#vis_submit_err_div").show(); 
													 $("#vis_submit_err_div").html('<?php echo $vis_language['MSGSLECTUPLOADCSVFILE']; ?>'); window.scrollTo(0,0);
													 setTimeout(function(){$("#vis_submit_err_div").hide();},10000);
													
												}
												else if(data.result == 4) {
													 $("#vis_submit_err_div").show(); 
													 $("#vis_submit_err_div").html('<?php echo $vis_language['MSGERROPRT']; ?>'); window.scrollTo(0,0);
													 setTimeout(function(){$("#vis_submit_err_div").hide();},10000);
												}
												else
												{
													$("#vis_new_attachments<?=$form_fields_details[$j]['formfield_id']; ?>").append(data.result);
													var max_attach=$("#vis_max_attach<?=$form_fields_details[$j]['formfield_id']; ?>").val();
													var attachments=$("#vis_attachment_count<?=$form_fields_details[$j]['formfield_id']; ?>").val();
													$("#vis_attachment_count<?=$form_fields_details[$j]['formfield_id']; ?>").val(eval(parseInt(attachments)+1));
													if(attachments>=max_attach) $("#vis_attach_file<?=$form_fields_details[$j]['formfield_id']; ?>").css('display','none');
													
												}
												 $('#progress<?=$form_fields_details[$j]['formfield_id']; ?>').css( 'display','none');
												 $('#progress<?=$form_fields_details[$j]['formfield_id']; ?> .progress-bar').css( 'width','0%');
											},
											progressall: function (e, data) {
												$('#progress<?=$form_fields_details[$j]['formfield_id']; ?>').css( 'display','');
												var progress = parseInt(data.loaded / data.total * 100, 10);
												$('#progress<?=$form_fields_details[$j]['formfield_id']; ?> .progress-bar').css(
													'width',
													progress + '%'
												);
											}
										});
									});
						   </script>
						   <?

						   }	
						   if($form_fields_details[$j]['field_type']==10)
                            {
							       $form_field_var.='<div class="form-group"><div class="col-sm-12">'.stripslashes($form_fields_details[$j]['field_description']).'</div></div>';
                                
                           }
                            $cc_count++;
                        }
                        else{ 
                             $flag = array();     
                            $filter='field_group='.$form_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$setting_object->get_formfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                            if($sub_customfields_details != -1){
                                if($form_fields_details[$j]['field_type']==4){
                                    $form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$form_fields_details[$j]['field_name'].'" title="'.$tooltip.'">'.stripslashes($form_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                    
                                    for($k=0;$k< count($sub_customfields_details);$k++){
                                       $sel='';
									    $sel= ($sub_customfields_details[$k]['is_selected']==1)?'checked':'';
									   $class = ($is_inline==1 && $k<(count($sub_customfields_details)))?'-inline':'';
                                        	$form_field_var.='<label class="checkbox'.$class.' i-checks"><input type="checkbox" '.$sel.' name="field'.$sub_customfields_details[$k]['formfield_id'].'" id="field'.$sub_customfields_details[$k]['formfield_id'].'" value="'.$sub_customfields_details[$k]['default_value'].'"  title="'.$tooltip.'" placeholder="'.$placeholder.'"   '.$html_attribute.' > <i></i> '.$sub_customfields_details[$k]['default_value'].'</label> ';
										
                                        $cc_count++;
                                    }
									$form_field_var .= (trim(stripslashes($form_fields_details[$j]['field_description']))!='')?'<br/>':'';
                                    $form_field_var .= $label.'</div></div>';
                                }
                                if($form_fields_details[$j]['field_type']==5){
                                    $form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$form_fields_details[$j]['field_name'].'" title="'.$tooltip.'">'.stripslashes($form_fields_details[$j]['field_name']).'</label><div class="col-sm-8">';
                                    
									for($k=0;$k<count($sub_customfields_details);$k++){
                                         $sel= ($sub_customfields_details[$k]['is_selected']==1)?'checked':'';
										$class = ($is_inline==1 && $k<(count($sub_customfields_details)))?'pull-left':'';
                                          $form_field_var.='<div class="radio i-checks m-r-lg '.$class.'"><label><input type="radio" '.$sel.' name="field'.$form_fields_details[$j]['formfield_id'].'[]" id="field'.$sub_customfields_details[$k]['formfield_id'].'" value="'.stripslashes($sub_customfields_details[$k]['default_value']).'"  title="'.$tooltip.'" '.$html_attribute.' > <i></i> '.$sub_customfields_details[$k]['default_value'].'</label></div>';
										 
                                        $cc_count++;
                                    }
									$form_field_var .= (trim(stripslashes($form_fields_details[$j]['field_description']))!='')?'<br/><br/>':'';
                                    $form_field_var .= $label.'</div></div>';
                                }
                                if($form_fields_details[$j]['field_type']==6){
                                    $form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$form_fields_details[$j]['field_name'].'" title="'.$tooltip.'">'.stripslashes($form_fields_details[$j]['field_name']).'</label><div class="col-sm-8"><select name="field'.$form_fields_details[$j]['formfield_id'].'" id="field'.$form_fields_details[$j]['formfield_id'].'" class="form-control input-sm selectpicker"  title="'.$tooltip.'"  placeholder="'.$placeholder.'"   '.$html_attribute.'>';
									 
                                    for($k=0;$k<count($sub_customfields_details);$k++) {
                                          $sel='';										
											if(count($flag) == 0 && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'selected="selected"';										  
                                        	$form_field_var.='<option value="'.stripslashes($sub_customfields_details[$k]['default_value']).'" '.$sel.'>'.stripslashes($sub_customfields_details[$k]['default_value']).'</option>';
                                    }
                                    
                                    $form_field_var.='</select>'.$label.'</div></div>';
                                    $cc_count++;
                                }
                                if($form_fields_details[$j]['field_type']==7){
								        //$tooltip = (trim($tooltip)=='')?stripslashes($form_fields_details[$j]['field_name']):$tooltip;
                                    	$form_field_var.='<div class="form-group"><label class="col-sm-2 control-label" for="'.$form_fields_details[$j]['field_name'].'" title="'.$tooltip.'">'.stripslashes($form_fields_details[$j]['field_name']).'</label><div class="col-sm-8"><select name="field'.$form_fields_details[$j]['formfield_id'].'[]" id="field'.$form_fields_details[$j]['formfield_id'].'" multiple="multiple" size="5" class="form-control input-sm selectpicker"  title="'.$tooltip.'"  placeholder="'.$placeholder.'"  '.$html_attribute.'>';			 
                                         
                                    for($k=0;$k<count($sub_customfields_details);$k++) {
                                          $sel='';
										  
                                        if(count($flag) == 0 && $sub_customfields_details[$k]['is_selected'] == 1)$sel = 'selected="selected"'; 
                                           $form_field_var.='<option value="'.stripslashes($sub_customfields_details[$k]['default_value']).'" '.$sel.'>'.stripslashes($sub_customfields_details[$k]['default_value']).'</option>';
                                    }
                                    $form_field_var.='</select>'.$label.'</div></div>';
                                    $cc_count++;
                                }
                            }
                        }
                    }
                }
                //else $form_field_var='';
            }
        }
        else { $form_field_var=''; }
        return $form_field_var;
    }

    
###Form creation tool
//delete custom report mass action- np
	function delete_mass_filter($operation){
		 $list_chk=array();
			global $vis_language;
									$options=parse_form_array($operation['vis_action']);
				$property=$options['action'];
													
				foreach($options as $data=>$value) if(preg_match('/vis_global_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
												
													$database=new class_database();
													include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
			$object=new class_ticket($database);
			$ret=$object->delete_mass_filter($list_chk, VIS_STAFF_ID, VIS_LOCATION_AREA);
									
													if(!$ret)
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
			   else
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#global_menu").visExecution("load_area", {"vis_module":"home", "vis_operation":"load_global_menu"}); $("#vis_workpanel_div").visExecution("load_area",{"vis_module":"'.$operation['vis_current_module'].'", "vis_operation":"'.$operation['vis_current_operation'].'"}); </script>';
	return true;	
	}
	function get_capsulecrm_details($operation) {
		$insightly_result = array();
		$operation['type']='profile';
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=41 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($capcrm_info, $capcrm_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    //print_r($capcrm_details);
        if(count($capcrm_details)>0 && $capcrm_details!=-1){
			foreach($capcrm_details as $capcrm){
				//$service_url = $capcrm['billing_url'].'Contacts?email='.$operation['vis_email'];
				//$service_url = $capcrm['billing_url'].'api/party?email='.$operation['vis_client_email'].'';
				$service_url = $capcrm['billing_url'].'api/party?email='.$operation['vis_client_email'].'';
				$apikey=$capcrm['api_key'];
				$capsulecrm_info = $this->capsulecrm_curlcall($service_url,$apikey,$operation['type'],$capcrm['billing_url'],$operation);
			}
		}
		include(VIS_PATH_TEMPLATE.'capsulecrm_client_details.php');
        return true;
    }
    function capsulecrm_curlcall($service_url,$apikey,$type,$capsulecrm_url,$operation){
		 global $vis_language;
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $service_url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept:application/json'));
		curl_setopt($curl, CURLOPT_USERPWD, "".$apikey.":x");
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		//curl_setopt($curl, CURLOPT_HEADER, 1);
		//curl_setopt($curl, CURLOPT_POST, true);
		 $result = curl_exec($curl);
		 $result = json_decode($result,true);
		if($type=='profile') 
			return $result;
		else if($type=='cases'){
			//echo '<pre>';
			//print_r($result);
			$curl = curl_init();
			$case_url =$capsulecrm_url.'api/party/'.$result['parties']['person']['id'].'/kase';
			curl_setopt($curl, CURLOPT_URL, $case_url);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept:application/json'));
			curl_setopt($curl, CURLOPT_USERPWD, "".$apikey.":x");
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			//curl_setopt($curl, CURLOPT_HEADER, 1);
			//curl_setopt($curl, CURLOPT_POST, true);

			$result = curl_exec($curl);
			$result = json_decode($result,true);
			return $result;
		}else if($type=='tasks'){
			//echo '<pre>';
			//print_r($result);
			$curl = curl_init();
			if($operation['status']!='')$task_status=$operation['status']; else $task_status='OPEN';
			$case_url =$capsulecrm_url.'api/tasks?status='.$task_status;
			curl_setopt($curl, CURLOPT_URL, $case_url);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept:application/json'));
			curl_setopt($curl, CURLOPT_USERPWD, "".$apikey.":x");
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			//curl_setopt($curl, CURLOPT_HEADER, 1);
			//curl_setopt($curl, CURLOPT_POST, true);

			$result = curl_exec($curl);
			$result = json_decode($result,true);
			return $result;
		}else if($type=='addtasks'){
				$data = array("task"=>array("description" => $operation['description'],"dueDateTime" => date("Y-m-d",strtotime($operation['due_date'])).'T'.date("H:i:s",strtotime($operation['due_date'])).'Z'));
				$data= json_encode($data);
				$curl = curl_init();
				$addtask_url =$capsulecrm_url.'api/task';
				curl_setopt($curl, CURLOPT_URL, $addtask_url);
				curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
				curl_setopt($curl, CURLOPT_USERPWD, "".$apikey.":x");
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl, CURLOPT_HEADER, true);
				curl_setopt($curl, CURLOPT_POST, true);
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
				$result = curl_exec($curl);
				//print_r($result);
				echo "<script>$('#vis_details_list').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_capsulecrm_cases_details','vis_domain':'".$operation['vis_domain']."', 'type':'tasks'});</script>";
		}		
	}
	function get_capsulecrm_cases_details($operation) {
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=41 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($capcrm_info, $capcrm_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	    //print_r($capcrm_details);
        if(count($capcrm_details)>0 && $capcrm_details!=-1){
			foreach($capcrm_details as $capcrm){
				$service_url = $capcrm['billing_url'].'api/party?email='.$operation['vis_client_email'].'';
				$apikey=$capcrm['api_key'];
				$capsulecrm_info = $this->capsulecrm_curlcall($service_url,$apikey,$operation['type'],$capcrm['billing_url'],$operation);
			}
		}
		include(VIS_PATH_TEMPLATE.'capsulecrm_client_profile.php');
        return true;
    }
	function get_api_custom_field_details($operation){
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $sett_obj=new class_setting($database);
		
		$filter=' (location in (1,2,11)) and (department_access=0 or find_in_set('.$operation['vis_department'].', department_access)) and is_enabled=1 ';
        $custom_group=$sett_obj->get_custom_group_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(VIS_LOCATION_AREA==0){
			//Custom field array for API
		  for($c=0;$c<count($custom_group);$c++){
		  $filter=' '.VIS_TABLE_PREFIX.'customfield.customgroup_id='.$custom_group[$c]['customgroup_id'].' and '.VIS_TABLE_PREFIX.'customfield.is_enabled=1 ';
		  list($custom_field_info, $custom_fields_details)=$sett_obj->get_customfield(0, $filter,'', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA); // $custom_fields_details & $custom_group used 
			if($custom_fields_details != -1){
                	for($j=0; $j<count($custom_fields_details); $j++)
                    {  
				        $val='';
                        if($custom_fields_details[$j]['field_type']<4 || $custom_fields_details[$j]['field_type']==8)
                        {
                            $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $operation['vis_ticket_id'], $custom_fields_details[$j]['field_type']);
                            //if($custom_data != -1) 
								$custom_fields_details[$j]['custom_field_data'] = $custom_data;
							/*	$val = $custom_data['content'];
                           // else $val = $custom_fields_details[$j]['default_value'];
                            $req = ($custom_fields_details[$j]['is_required']==1)?' *':'';
                            if($custom_fields_details[$j]['field_type']==1){
                                             $custom_field_var.=$val;
                            }
                            if($custom_fields_details[$j]['field_type']==2)
                            {
											$custom_field_var.=$val; 
                                                                     
                            }
                            if( $custom_fields_details[$j]['field_type']==3){
                                              $custom_field_var.=$val; 
                            }
                            if( $custom_fields_details[$j]['field_type']==8){
                                              $custom_field_var.=format_datetime(strtotime($val)); 
                            }*/
                        }
                        else
                        {
                            $filter='field_group='.$custom_fields_details[$j]['field_group'].' ';
                            list($sub_customfield_info ,$sub_customfields_details)=$sett_obj->get_customfield(1, $filter, '', 0, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
                                if($sub_customfields_details != -1)
                                {
                                     $flag = array();   
                                        if($custom_fields_details[$j]['field_type']==4)
                                        {
                                              /*for($cnt=0;$cnt<count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }*/
									        for($k=0;$k< count($sub_customfields_details);$k++)
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $operation['vis_ticket_id'], $custom_fields_details[$j]['field_type']); 
												$sub_customfields_details[$k]['custom_field_data'] = $custom_data;
											    $cc_count++;
                                            }
											$custom_fields_details[$j]['checkbox_group']=$sub_customfields_details;
                                        }
                                        if($custom_fields_details[$j]['field_type']==5)
                                        {
                                            for($k=0;$k<count($sub_customfields_details);$k++)
                                            {
                                              $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $operation['vis_ticket_id'], $custom_fields_details[$j]['field_type']);  
                                                
                                                    $flag[$k] = 1;
                                                   $sub_customfields_details[$k]['custom_field_data'] = $custom_data;
                                               $cc_count++;
                                            }
											$custom_fields_details[$j]['radio_group']=$sub_customfields_details;
                                        }
                                        if($custom_fields_details[$j]['field_type']==6)
                                        {    
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($custom_fields_details[$j]['customfield_id'], $operation['vis_ticket_id'], $custom_fields_details[$j]['field_type']);
												//if($custom_data!=-1)$custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
                                             	
													$custom_fields_details[$j]['custom_field_data'][$k] = $custom_data;
                                                
                                            }
                                            $cc_count++;
                                        }
                                        if($custom_fields_details[$j]['field_type']==7)
                                        { 
                                            if($sub_customfields_details[$k]['is_selected'] == 1 )$selDefault = 'selected="selected"';    
                                            for($cnt=0;$cnt< count($sub_customfields_details);$cnt++)
                                            {
                                               $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$cnt]['customfield_id'], $ticket_details['ticket_id'], $custom_fields_details[$j]['field_type']);  
                                               if($custom_data != -1)  
                                               {
                                                     $flag[$cnt] =  1;
                                               }
                                            }
											//echo '<pre>';
											//print_r($sub_customfields_details);
                                            for($k=0;$k<count($sub_customfields_details);$k++) 
                                            {
                                                $custom_data = $ticket_object->get_customfield_data($sub_customfields_details[$k]['customfield_id'], $operation['vis_ticket_id'], $custom_fields_details[$j]['field_type']);   
											   
													$sub_customfields_details[$k]['custom_field_data'] = $custom_data;
												
                                                if(count($flag) <= 0 && $sub_customfields_details[$k]['is_selected'] == 1) $custom_field_var.=addslashes($sub_customfields_details[$k]['default_value']).' ';
                                            }
											$custom_fields_details[$j]['multiselect_group']=$sub_customfields_details;
                                            $cc_count++;
                                        }
                                    
                                }
                            }
				       }
					   $custom_group[$c]['custom_group'] = $custom_fields_details;
				}
		    }   
		     $custom_details = array();
				header('Content-Type: application/json');
				$custom_details['custom_fields']=$custom_group;
				echo get_xml($custom_details, 'ticket');
				return true;
		}
		$database->database_disconnect();
        return true;
		
	}
	
	/*function execute_ticket_cron($cron_time,$criteria_time='',$sub_criteria='')
	{
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting=new class_setting($database);
		$ticket=new class_ticket($database);
		$mail_object=new class_mail($database);
		$staff_object=new class_staff($database);
		$operation_hnd=new operation();
		
		//ticket schesule start
	    $res_sche=$ticket->get_checkticket_schedule();
		if($res_sche!=-1){
			if($res_sche['total']>0){
				$ticket->execute_schedule_ticket();
					}
		}
		//ticket schesule end
		
		//exotel auto ticket creation start
		$this->exo_staff_auto_ticket();
		//exotel auto ticket creation end
		
		//send after overdue and unresolved tickets send alert and check workflow on_last_activity event
		//$diff = 'unix_timestamp()'-$cron_time;		
		/*$detail=$ticket->get_ticket('due_time >= '.$diff.' and due_time < unix_timestamp() and user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
		 $timevar = time();
		 $diff = time() - $cron_time;		
		 if($sub_criteria=='1')
		{
				$detail=$ticket->get_ticket(' (due_time-'.$criteria_time.') >= ('.$diff.') and (due_time-'.$criteria_time.') < '.$timevar.' and user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
		}
		else{
			$detail=$ticket->get_ticket(' (due_time+'.$criteria_time.') >= ('.$diff.') and (due_time+'.$criteria_time.') < '.$timevar.' and user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
		}
		list($info, $tickets)=$detail;
	 
	   echo "<pre> tickets ==> ";
	   print_r($tickets);
		
		if($tickets!=-1) for($i=0;$i<count($tickets);$i++)
		{
				if((isset($tickets[$i]['pause_dtime']) && $tickets[$i]['pause_dtime']=="") && (isset($tickets[$i]['pause_rtime']) && $tickets[$i]['pause_rtime']==""))
				{
					$tickets[$i]['vis_module']='ticket';
					$tickets[$i]['vis_operation']='after_overdue';
					$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
					$staff_object->apply_task_automation($tickets[$i], 0, VIS_LOCATION_AREA, $database);
					$operation = 'update_properties';
					$tickets[$i]['send_alert'] = 1 ; 
					$mail_object->email_notify($tickets[$i], $operation,'', VIS_LOCATION_AREA) ;
				}
		}

		$detail=$ticket->get_ticket('resolution_time>=(unix_timestamp()-'.$cron_time.') and resolution_time<unix_timestamp() and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
		list($info, $tickets)=$detail;
		if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
			$tickets[$i]['vis_module']='ticket';
			$tickets[$i]['vis_operation']='on_unresolved';
			$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
			$operation = 'update_properties';    
			$tickets[$i]['send_alert'] = 1 ;
			$mail_object->email_notify($tickets[$i], $operation,'',VIS_LOCATION_AREA);
		}
	   
		list($roundrobin_info, $roundrobin_details)=$setting->get_roundrobin('is_enabled=1', '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($roundrobin_details!=-1){
			    for($j=0;$j<count($roundrobin_details);$j++)
			    {
					 $roundrobin_action=$setting->get_roundrobin_action($roundrobin_details[$j]['roundrobin_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
                     
                    if($roundrobin_action[4]!=0) { 
						$filter_rr = VIS_TABLE_PREFIX.'ticket.receive_date+'.$roundrobin_action[4].'<=  unix_timestamp() and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0';
						$filter= $filter_rr;//.' ticketid not in (select ticket_id from '.VIS_TABLE_PREFIX.'ticket_assign where owner_id!=0) '
						$detail=$ticket->get_ticket($filter, '', 0, '', 0, VIS_LOCATION_AREA);
						
						list($info, $tickets)=$detail;
						
						if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
							
							$owner_filter=VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$tickets[$i]['ticket_id'];
							$ticket_owner_array=$ticket->get_ticket_owner($owner_filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
							if($ticket_owner_array==-1) {
								$data['vis_cron_flag'] = 1;
								$data=array_merge($data, $tickets[$i]);
								$staff_object->apply_roundrobin($data, 0, VIS_LOCATION_AREA, $database,$roundrobin_details[$j]['roundrobin_id']);
						   }
					 }	
				}
			}
		}		
		
		$setting->update_cron_time();				
	}
	*/
	function execute_ticket_cron($cron_time,$overdue='',$resolution='')
	{
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting=new class_setting($database);
		$ticket=new class_ticket($database);
		$mail_object=new class_mail($database);
		$staff_object=new class_staff($database);
		$operation_hnd=new operation();
		//ticket schesule start
	    $res_sche=$ticket->get_checkticket_schedule();
		if($res_sche!=-1){
			if($res_sche['total']>0){
				$ticket->execute_schedule_ticket();
					}
		}	 
		$this->exo_staff_auto_ticket();		 
		$timevar = time();
		$diff = time() - $cron_time;
       if(count($overdue) >0 && count($resolution)>0)
	   {		   
		   $filter ='user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0';
		   if($overdue['sub_criteria']=='1')
			{
				$filter .= ' and (due_time-'.$overdue['criteria_time'].') >= ('.$diff.') and (due_time-'.$overdue['criteria_time'].') < '.$timevar;
			}
			else{
				 $filter .= ' and (due_time+'.$overdue['criteria_time'].') >= ('.$diff.') and (due_time+'.$overdue['criteria_time'].') < '.$timevar;
			}
			$filter =' status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0';
			if($resolution['sub_criteria']=='1')
			{
				$filter .= ' and (resolution_time-'.$resolution['criteria_time'].') >= ('.$diff.') and (resolution_time-'.$resolution['criteria_time'].') < '.$timevar;
			}
			else{
				 $filter .= ' and (resolution_time+'.$resolution['criteria_time'].') >= ('.$diff.') and (resolution_time+'.$resolution['criteria_time'].') < '.$timevar;
			}
			$detail=$ticket->get_ticket($filter,'', 0, '', 0, VIS_LOCATION_AREA);
			list($info, $tickets)=$detail;					
			if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
				$tickets[$i]['vis_module']='ticket';
				$tickets[$i]['vis_operation']='on_unresolved';
				$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
				$operation = 'update_properties';    
				$tickets[$i]['send_alert'] = 1 ;
				$mail_object->email_notify($tickets[$i], $operation,'',VIS_LOCATION_AREA);
				$tickets[$i]['vis_operation']='after_overdue';
				$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);				 
				$mail_object->email_notify($tickets[$i], $operation,'',VIS_LOCATION_AREA);
			}			
	    }		   
		elseif($overdue['criteria_id']=='17' || $resolution['criteria_id']=='17')
		{
			$criteria_time = 0;
			$criteria_time = (count($overdue)>0)? $overdue['criteria_time']:$resolution['criteria_time'];
			$sub_criteria =  (count($overdue)>0)? $overdue['sub_criteria']:$resolution['sub_criteria'];
		 	if($sub_criteria=='1')
			{
				$detail=$ticket->get_ticket(' (due_time-'.$criteria_time.') >= ('.$diff.') and (due_time-'.$criteria_time.') < '.$timevar.' and user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
			}
			else{
				$detail=$ticket->get_ticket(' (due_time+'.$criteria_time.') >= ('.$diff.') and (due_time+'.$criteria_time.') < '.$timevar.' and user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
			}
			list($info, $tickets)=$detail;
			if($tickets!=-1) for($i=0;$i<count($tickets);$i++)
				{
						if((isset($tickets[$i]['pause_dtime']) && $tickets[$i]['pause_dtime']=="") && (isset($tickets[$i]['pause_rtime']) && $tickets[$i]['pause_rtime']==""))
						{
							$tickets[$i]['vis_module']='ticket';
							$tickets[$i]['vis_operation']='after_overdue';
							$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
							$staff_object->apply_task_automation($tickets[$i], 0, VIS_LOCATION_AREA, $database);
							$operation = 'update_properties';
							$tickets[$i]['send_alert'] = 1 ; 
							$mail_object->email_notify($tickets[$i], $operation,'', VIS_LOCATION_AREA) ;
						}
				}
		}
		elseif($overdue['criteria_id']=='27' || $resolution['criteria_id']=='27')
		{
			$criteria_time =0;
			$criteria_time = (count($overdue)>0)? $overdue['criteria_time']:$resolution['criteria_time'];
			$sub_criteria =  (count($overdue)>0)? $overdue['sub_criteria']:$resolution['sub_criteria'];

			if($sub_criteria=='1')
			{
				$detail=$ticket->get_ticket(' (resolution_time-'.$criteria_time.') >= ('.$diff.') and (resolution_time-'.$criteria_time.') < '.$timevar.'  and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
			}
			else{
				$detail=$ticket->get_ticket(' (resolution_time+'.$criteria_time.') >= ('.$diff.') and (resolution_time+'.$criteria_time.') < '.$timevar.'  and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
			}
			list($info, $tickets)=$detail;
			if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
				$tickets[$i]['vis_module']='ticket';
				$tickets[$i]['vis_operation']='on_unresolved';
				$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
				$staff_object->apply_task_automation($tickets[$i], 0, VIS_LOCATION_AREA, $database);
				$operation = 'update_properties';    
				$tickets[$i]['send_alert'] = 1 ;
				$mail_object->email_notify($tickets[$i], $operation,'',VIS_LOCATION_AREA);
			}			
		}
		elseif($criteria_id==''){
			$detail=$ticket->get_ticket('due_time >= '.$diff.' and due_time < unix_timestamp() and user_replied=1 and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA);
				list($info, $tickets)=$detail;
				if($tickets!=-1) for($i=0;$i<count($tickets);$i++)
				{
						if((isset($tickets[$i]['pause_dtime']) && $tickets[$i]['pause_dtime']=="") && (isset($tickets[$i]['pause_rtime']) && $tickets[$i]['pause_rtime']==""))
						{
							$tickets[$i]['vis_module']='ticket';
							$tickets[$i]['vis_operation']='after_overdue';
							$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
							$operation = 'update_properties';
							$tickets[$i]['send_alert'] = 1 ; 
							$mail_object->email_notify($tickets[$i], $operation,'', VIS_LOCATION_AREA) ;
						}
				}
				
	    $detail=$ticket->get_ticket('resolution_time>=(unix_timestamp()-'.$cron_time.') and resolution_time<unix_timestamp() and status_id!=3 and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0', '', 0, '', 0, VIS_LOCATION_AREA); 
			list($info, $tickets)=$detail;
			if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
				$tickets[$i]['vis_module']='ticket';
				$tickets[$i]['vis_operation']='on_unresolved';
				$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
				$operation = 'update_properties';    
				$tickets[$i]['send_alert'] = 1 ;
				$mail_object->email_notify($tickets[$i], $operation,'',VIS_LOCATION_AREA);
			}
		}	   
		list($roundrobin_info, $roundrobin_details)=$setting->get_roundrobin('is_enabled=1', '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($roundrobin_details!=-1){
			    for($j=0;$j<count($roundrobin_details);$j++)
			    {
					 $roundrobin_action=$setting->get_roundrobin_action($roundrobin_details[$j]['roundrobin_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
           
                    if($roundrobin_action[4]!=0) { 
						$filter_rr = VIS_TABLE_PREFIX.'ticket.receive_date+'.$roundrobin_action[4].'<=  unix_timestamp() and is_deleted=0 and '.VIS_TABLE_PREFIX.'ticket.is_spam = 0';
						$filter= $filter_rr;//.' ticketid not in (select ticket_id from '.VIS_TABLE_PREFIX.'ticket_assign where owner_id!=0) '
						$detail=$ticket->get_ticket($filter, '', 0, '', 0, VIS_LOCATION_AREA);
						list($info, $tickets)=$detail;
						if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
							$owner_filter=VIS_TABLE_PREFIX.'ticket_assign.ticket_id='.$tickets[$i]['ticket_id'];
							$ticket_owner_array=$ticket->get_ticket_owner($owner_filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
							if($ticket_owner_array==-1) {
								$data['vis_cron_flag'] = 1;
								$data=array_merge($data, $tickets[$i]);
								$staff_object->apply_roundrobin($data, 0, VIS_LOCATION_AREA, $database,$roundrobin_details[$j]['roundrobin_id']);
						   }
					 }	
				}
			}
		}		
		
		$setting->update_cron_time();				
	}

	function ticket_comment_edit($operation)
	{
		 global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);

        $comment_details=$ticket_object->get_post_error('remark_id ='.$operation['vis_remark_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
         include(VIS_PATH_TEMPLATE.'ticket_comment_edit.php');
         return true;
	}
	
	function update_ticket_comment($operation)
	{
		 global $vis_language;
        $data=parse_form_array($operation['vis_action']);
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $data['vis_ticket_comment'] = str_replace(array("\r\n","\r","\n"),"<br>",$data['vis_ticket_comment']);
        $data['content'] =  $data['vis_ticket_comment'];
        if((!isset($data['vis_ticket_comment']) || trim(strip_tags($data['vis_ticket_comment'],"<img>")) == '')) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGPOSTMESSAGENOTFOUND'].'"); </script>';
           // return false;
		}
        $result=$object->set_remark($data['vis_remark_id'], $data, '', VIS_STAFF_ID, VIS_LOCATION_AREA);     
        if(!$result)
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        else{
			 list($ticket_info, $ticket_details)=$object->get_ticket(' ticket_id='.$operation['vis_ticket_id'], 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			 $object->add_audit_log($ticket_details[0], 37, '', '' , VIS_STAFF_ID, VIS_LOCATION_AREA);
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_ticket_comment_content_text_'.$data['vis_remark_id'].'").show(); $("#vis_ticket_comment_content_edit_'.$data['vis_remark_id'].'").hide(); $("#vis_ticket_comment_content_text_'.$data['vis_remark_id'].'").html("'.$data['vis_ticket_comment'].'"); </script>';
		}
		$database->database_disconnect();
        return $result;
	}
	
	
	function send_approvals($operation){		
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff_object=new class_staff($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
		$mobject=new class_mail($database);	
		
		if(isset($operation['vis_send_request']) && $operation['vis_send_request']=='success'){
			$data=parse_form_array($operation['vis_action']);
			
			
			if(($data['total_group']>0) && $data['member']=='team')
			 {
			    $staffid_in_group=array();
				$groupid=array();
				$staffid_bygroup_details=array();
				$filter_data=array();
				$iddata=array();
				 
				$data['vis_parent_id']=$data['vis_ticket_id'];
				$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'];
				list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				
				$query_string="";
				$grpid=array();
				for($i=0;$i<$data['total_group'];$i++)
				{
				 if(isset($data['vis_group_id_'.$i]))
				 {
					$grpid[$i]=$data['vis_group_id_'.$i];
				 }	
				}
					
				$group_count=count($grpid);
				for($i=0;$i<$data['total_group'];$i++)
				{
				 if($group_count>1)
					{				
					if(isset($data['vis_group_id_'.$i]))
					{
						if($i==($group_count-1))
						{ 
							$query_string[]=$data['vis_group_id_'.$i];
						}
						else
						{
							$query_string[]=$data['vis_group_id_'.$i];
						}
					}
				}
				else
					{
						if(isset($data['vis_group_id_'.$i])){
								$query_string[]=$data['vis_group_id_'.$i];
						}
					}	
				}
					
					$query_filter=VIS_TABLE_PREFIX.'staff.is_enabled=1 and '.VIS_TABLE_PREFIX.'staff.group_id in ('.implode(',',$query_string).') and '.VIS_TABLE_PREFIX.'department.department_id='.$data['vis_dept_id'];
					
					//THIS ONE FOR EMPTY GRPS
					list($staffid_bygroup_details,$emptygroup)=$staff_object->get_staffid_in_group($query_filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
					if(count($query_string)>count($emptygroup)){
						$totals=count($query_string);
					}else{
						$totals=count($emptygroup);
					}
					$empty_groups=array();
					
					for($i=0;$i<$totals;$i++){
						for($j=0;$j<count($emptygroup);$j++){
							if($query_string[$i]==$emptygroup[$j]['group_id']){
								$empty_groups[]=$emptygroup[$j]['group_id'];
							}else{}
						}
					}
					
					$ids=implode(',',$empty_groups);
					$staffgroup_list = $staff_object->get_staff_group('is_enabled=1 and group_id in('.$ids.')',VIS_STAFF_ID, VIS_LOCATION_AREA);
					if($staffgroup_list!=-1){
					for($i=0;$i<count($staffgroup_list);$i++){
						if(!empty($staffgroup_list[$i]['group_name'])){
						$teamarray[$i]=$staffgroup_list[$i]['group_name'];
						}
					}
					$team_names=implode(',',$teamarray);
					}
					$team_names="No staff in ".$team_names." team";
					
					if(count($teamarray)>0){					
						echo "<script>$('#vis_global_msg_div').visInterface('load_global_message', '".$team_names."')</script>";
						return false;
					}
					//THIS ONE FOR EMPTY GRPS ENDS
					
				$data['vis_parent_id']=$data['vis_ticket_id'];
				$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'];
				list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					
					for($i=0;$i<$data['total_staff'];$i++)
					{					
						if(isset($staffid_bygroup_details[$i]['staff_id'])){
						$data['vis_staff_id']=$staffid_bygroup_details[$i]['staff_id'];
						$filter = VIS_TABLE_PREFIX.'ticket_approvals.parent_id='.$data['vis_parent_id'].' AND approvals_type=0 AND '.VIS_TABLE_PREFIX.'ticket_approvals.staff_id='.$data['vis_staff_id'];
						list($approvals_info, $approvals_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			//			echo "DATA TO DISPLAY : "."<pre>";print_r($approvals_details);echo "</pre>";
					
						if($approvals_details !=-1){
							$filter =' parent_id='.$data['vis_parent_id'].' AND staff_id='.$data['vis_staff_id'];
							$ret=$ticket_object->disabled_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						}
						$ret=$ticket_object->add_approvals($data,VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						$staff_list = $staff_object->get_staff('is_enabled=1 and staff_id='.$data['vis_staff_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
												
						$data1['subject']=$ticket_details[0]['subject'];
						$data1['domain_id']=$ticket_details[0]['domain_id'];
						$data1['ticket_hash']=$ticket_details[0]['ticket_hash'];
						$data1['staff']=$staff_list[0];
						$data1['template_id']=33;
						
						$data1['vis_module']='ticket';
						$data1['ticket_id']=$data['vis_ticket_id'];
						//echo "DATA 1 ARRAY :";echo "<pre>";print_r($data1);echo "</pre>";echo "<br>";
						
						
						$rert=$mobject->email_notify($data1, 'ticket_approval_mail', VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						$ticket_object->add_audit_log($ticket_details[0], 53, $staff_list[0]['first_name'].' '.$staff_list[0]['last_name'],'', VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
					
					}
					
					if($ret){
					echo "<script>$('#vis_global_msg_div').visInterface('load_global_message', '".$vis_language['MSGSUCCOPRT']."');$('#vis_details_list_".$data['vis_ticket_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':'".$data['vis_ticket_id']."', 'open_approvals':'yes' }); set_active_tab('ticket_details');$('.modal').modal('toggle');</script>";
				}
				  
			 }				
			
				 elseif($data['total_staff']>0)
			{
				$data['vis_parent_id']=$data['vis_ticket_id'];
				$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'];
				list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				for($i=0;$i<$data['total_staff'];$i++){
					
					if(isset($data['vis_staff_id_'.$i])){
						
						$data['vis_staff_id']=$data['vis_staff_id_'.$i];
						$filter = VIS_TABLE_PREFIX.'ticket_approvals.parent_id='.$data['vis_parent_id'].' AND approvals_type=0 AND '.VIS_TABLE_PREFIX.'ticket_approvals.staff_id='.$data['vis_staff_id'];
						list($approvals_info, $approvals_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
							
						if($approvals_details !=-1){
							$filter =' parent_id='.$data['vis_parent_id'].' AND staff_id='.$data['vis_staff_id'];
							$ret=$ticket_object->disabled_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
						}
						$ret=$ticket_object->add_approvals($data,VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						$staff_list = $staff_object->get_staff('is_enabled=1 and staff_id='.$data['vis_staff_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
												
						$data1['subject']=$ticket_details[0]['subject'];
						$data1['domain_id']=$ticket_details[0]['domain_id'];
						$data1['ticket_hash']=$ticket_details[0]['ticket_hash'];
						$data1['staff']=$staff_list[0];
						$data1['template_id']=33;
						
						$data1['vis_module']='ticket';
						$data1['ticket_id']=$data['vis_ticket_id'];
						//echo "DATA 1 ARRAy ===>";echo "<pre>";print_r($data1);echo "</pre>";
						$rert=$mobject->email_notify($data1, 'ticket_approval_mail', VIS_STAFF_ID, VIS_LOCATION_AREA);
						
						$ticket_object->add_audit_log($ticket_details[0], 53, $staff_list[0]['first_name'].' '.$staff_list[0]['last_name'],'', VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
				}
				if($ret){
					echo "<script>$('#vis_global_msg_div').visInterface('load_global_message', '".$vis_language['MSGSUCCOPRT']."');$('#vis_details_list_".$data['vis_ticket_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':'".$data['vis_ticket_id']."', 'open_approvals':'yes' }); set_active_tab('ticket_details');$('.modal').modal('toggle');</script>";
				}
			}
		}
		else{
				
			$staff_list = $staff_object->get_staff('is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA, $operation['vis_dept_id']);
			$staffgroup_list = $staff_object->get_staff_group('is_enabled=1',VIS_STAFF_ID, VIS_LOCATION_AREA);
			
			$database->database_disconnect();
			include(VIS_PATH_TEMPLATE.'ticket_sendapprovals_request.php');
		}
        return true;
	}
		//THIS ONE FOR TICKET APPROVALS STATUS ENDS
	function change_approve_status($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
				
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		//echo "<pre>";print_r($ticket_details);echo "</pre>";
				
		$ret=$ticket_object->update_approve_status($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
		//echo "update status result == >"."<pre>";print_r($ret);echo "</pre>";
		if(!$ret){
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
		}else{
		
			$status = $operation['status'];
			$status = ($status==1)? 'Approved' : (($status==2)? 'Canceled' : 'Rejected');
			$ticket_object->add_audit_log($ticket_details[0], 54, $status, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
	
		$database->database_disconnect();
		return $ret;
		
	}
	//THIS ONE FOR TICKET APPROVALS STATUS ENDS
	//THIS ONE FOR TICKET APPROVALS REJECTION STARTS
	function reject_approvals($operation){
		
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		
		
		if(isset($operation['vis_reject']) && $operation['vis_reject']=='success'){
		
			$data=parse_form_array($operation['vis_action']);
			if(trim($data['vis_remark'])==''){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQFLDDESC'].'"); </script>';
				return false;
			}
		
			$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$data['vis_ticket_id'];
			list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					
			$ret=$ticket_object->update_approve_remark($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
			
			if(!$ret){
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");</script>';
				return false;
			}else{
				echo "<script>$('#vis_global_msg_div').visInterface('load_global_message', '".$vis_language['MSGSUCCOPRT']."');$('#vis_details_list_".$data['vis_ticket_id']."').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_details', 'vis_action':'details', 'vis_ticket_id':'".$data['vis_ticket_id']."', 'open_approvals':'yes'}); set_active_tab('ticket_details');$('.modal').modal('toggle');</script>";
			}
		}
		else{
			include(VIS_PATH_TEMPLATE.'ticket_remarks.php');
		}
		return true;
	}
	//THIS ONE FOR TICKET APPROVALS REJECTION ENDS
	
	//THIS ONE FOR TICKET APPROVALS STARTS
	function send_approve_reminder($operation){
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
		$mobject=new class_mail($database);	
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff_object=new class_staff($database);	
		$ret = -1;
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticket_id'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		
		if($ticket_details!=-1){
			
			$filter = VIS_TABLE_PREFIX.'ticket_approvals.parent_id='.$operation['vis_ticket_id'].' AND approvals_type=0 AND '.VIS_TABLE_PREFIX.'ticket_approvals.staff_id='.$operation['staff_id'].' AND '.VIS_TABLE_PREFIX.'ticket_approvals.approvals_id='.$operation['approve_id'];
			list($approvals_info, $approvals_details)=$ticket_object->get_approvals($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
			
			if($approvals_details !=-1){			
				$staff_list = $staff_object->get_staff('is_enabled=1 and staff_id='.$operation['staff_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($staff_list!=-1){
					$data1['subject']=$ticket_details[0]['subject'];
					$data1['domain_id']=$ticket_details[0]['domain_id'];
					$data1['ticket_hash']=$ticket_details[0]['ticket_hash'];
					$data1['staff']=$staff_list[0];
					$data1['template_id']=33;
									
					$data1['vis_module']='ticket';
					$data1['ticket_id']=$operation['vis_ticket_id'];
					$ret=$mobject->email_notify($data1, 'ticket_approval_mail', VIS_STAFF_ID, VIS_LOCATION_AREA);
					$changes_object->add_audit_log($changes_details[0], 55, $staff_list[0]['first_name'].' '.$staff_list[0]['last_name'],'', VIS_STAFF_ID, VIS_LOCATION_AREA);
				}	
			}
		}
		return $ret;
	}
	##vtiger
	function vt_status($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"HelpDesk":"Cases";	
		$vt_module_desc	=	$setting_object->get_vtiger('module_desc',$vt_data);

		$vt_ticket_priorities = $vt_module_desc['fields'][3]['type']['picklistValues'];
		$vt_ticketstatus	=	$vt_module_desc['fields'][5]['type']['picklistValues'];
		
		$html =   '<div class="col-xs-4">
									 <div class="form-group col-xs-10">
										<label for="taskPriority">'.$vis_language['TXTSTATUS'].'</label> 
										<select class="form-control input-sm selectpicker" id="vis_vt_status" name="vis_vt_status" ';
										if(count($vt_ticketstatus) > 5) $src= 'data-live-search="true"' ; 
						  $html .=      '>';

										   for($i=0;$i<count($vt_ticketstatus);$i++) {                                      
										    $html .= '<option value="'.$vt_ticketstatus[$i]['value'].'" >'.$vt_ticketstatus[$i]['label'].'</option>'; } 
							 $html .=			'</select>
									 </div>			 
									 
							</div>							
							<div class="col-xs-4">
									 <div class="form-group col-xs-10">
										<label for="taskPriority">'.$vis_language['TXTPRIORITY'].'</label> 
										<select class="form-control input-sm selectpicker" id="vis_vt_priority" name="vis_vt_priority" ';
										if(count($vt_ticket_priorities) > 5) $src= 'data-live-search="true"' ;  
										$html .= '>';
										
										   for($i=0;$i<count($vt_ticket_priorities);$i++) {                                      
										   $html .= '<option value="'.$vt_ticket_priorities[$i]['value'].'" >'.$vt_ticket_priorities[$i]['label'].'</option>'; } 
										$html .= '</select>
									 </div>			 
									 
							</div>';
		echo $html;								
    }
	function vt_create_ticket($data) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);
		
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$data['vis_vt_user']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];		
		$vt_datanw = $vt_data;
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"HelpDesk":"Cases";		
		$ticketstatus 	= ($vt_data['vtiger_lic']==1)?"ticketstatus":"casestatus";
		$ticketpriority = ($vt_data['vtiger_lic']==1)?"ticketpriorities":"casepriority";
		$ticket_title	= ($vt_data['vtiger_lic']==1)?"ticket_title":"title";
		$moduleidx["Contacts"] = ($vt_data['vtiger_lic']==1)?"12x":"4x";
		$convert = str_replace("<br />", "\n", $data['vis_ticket_post']);
		$convert = str_replace("<br/>", "\n", $convert);
		$convert = str_replace("<br>", "\n", $convert);
		$convert = str_replace("</p>", "\n", $convert);
		$convert = str_replace("<p>", "", $convert);
		
		$description = strip_tags($convert);
		$title = $data['vis_subject'];
		$vt_status = $data['vis_vt_status'];
		$vt_priority = $data['vis_vt_priority'];
		$c_email = ($data['vis_new_ticket_list_client']!='')?$data['vis_new_ticket_list_client']:$data['vis_client_email'] ;
		
		$qry = "SELECT * FROM    Contacts WHERE email ='".$c_email."' OR mobile='".$c_email."'"; 
		
		$vt_datanw['query'] = $qry;
		$contact_record = $setting_object->get_vtiger('do_query',$vt_datanw);
		$vt_data['arr'] = array(
								"description"=>$description,
								$ticket_title=>$title,
								$ticketstatus=>$vt_status,
								$ticketpriority=>$vt_priority
								);
		if($c_email!=''){ $vt_data['arr']["contact_id"] = $contact_record[0]['id']; }
		$vt_ticket_id =  $setting_object->get_vtiger('create_record',$vt_data);
		
		return $vt_ticket_id;
		
		//print_r($contact_record);
	}
	function get_vtiger_details($operation) { 
		//echo '<pre>'; print_r($operation); echo '</pre>';		 
		$operation['type']='Tickets';
		global $vis_language;		
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
		
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND domain_id='.$operation['vis_domain']);	 
		
		/*
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticketid'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        
			$tickete_subject = $ticket_details[0]['subject'];*/

		if($vt_acc_list!=-1){
			$vt_acc_list_tmp = $vt_acc_list[0]; 
			$vt_data['vtiger_url']	= trim($vt_acc_list_tmp['vtiger_url']);
			$vt_data['vtiger_user']	= trim($vt_acc_list_tmp['vtiger_user']);
			$vt_data['vtiger_key']	= trim($vt_acc_list_tmp['vtiger_key']);
			$vt_data['vtiger_lic'] 	= trim($vt_acc_list_tmp['vtiger_lic']);	
			$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"HelpDesk":"Cases";	
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,5"; 		
			$vt_data['query'] = $qry;
			$vt_ticket_records = $setting_object->get_vtiger('do_query',$vt_data);

			$ticketstatus 	= ($vt_data['vtiger_lic']==1)?"ticketstatus":"casestatus";
			$ticketpriority = ($vt_data['vtiger_lic']==1)?"ticketpriorities":"casepriority";
			$ticket_title	= ($vt_data['vtiger_lic']==1)?"ticket_title":"title";
			$ticket_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";
			$vt_ticket_priorities = $vt_ticketstatus = "";
			
			/*$vt_module_desc	=	$setting_object->get_vtiger('module_desc',$vt_data); print_r($vt_module_desc);
			$vt_ticket_priorities = $vt_module_desc['fields'][3]['type']['picklistValues'];
			$vt_ticketstatus	=	$vt_module_desc['fields'][6]['type']['picklistValues'];
			*/
			
		}	
		if($operation['click_type']=="vt_ticket"){
			include(VIS_PATH_TEMPLATE.'vtiger_ticket_list.php');
		}else{ 
			include(VIS_PATH_TEMPLATE.'vtiger_details.php');
		}
        return true;
    }
    function vt_ticket_list($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= trim($vt_acc_list[0]['vtiger_lic']);
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"HelpDesk":"Cases";	
		
	    if($vt_acc_list!=-1){
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,5"; 		
				$vt_data['query'] = $qry;
				$vt_ticket_records = $setting_object->get_vtiger('do_query',$vt_data);
				
				$ticketstatus 	= ($vt_data['vtiger_lic']==1)?"ticketstatus":"casestatus";
				$ticketpriority = ($vt_data['vtiger_lic']==1)?"ticketpriorities":"casepriority";
				$ticket_title	= ($vt_data['vtiger_lic']==1)?"ticket_title":"title";
				$ticket_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";
			if($vt_ticket_records!=-1){
				include(VIS_PATH_TEMPLATE.'vt_ticket_list.php'); 
			}else{
			include(VIS_PATH_TEMPLATE.'no_record_yet.php'); }
		}else{
			include(VIS_PATH_TEMPLATE.'no_record_yet.php'); 
		}
					
    }
	function lm_vtiger_ticket($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);
		 if($operation['vis_integration_id']==-1){$operation['vis_integration_id'] = $operation['temp_id']; }
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"HelpDesk":"Cases";		
		//print_r($vt_data);
		
		$start = 0;
		$limit = 5;
		$page = 1;
		if(isset($operation['vis_page'])){ 
			$load_more_id = "load_more_".$operation['vis_page']+1;			
			$start = $operation['vis_page']*$limit;
			$page = $operation['vis_page']+1;		
			
		}
		
	    if($vt_acc_list!=-1){
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT $start,$limit"; 
				$vt_data['query'] = $qry;
				$vt_ticket_records = $setting_object->get_vtiger('do_query',$vt_data);
				
				$ticketstatus 	= ($vt_data['vtiger_lic']==1)?"ticketstatus":"casestatus";
				$ticketpriority = ($vt_data['vtiger_lic']==1)?"ticketpriorities":"casepriority";
				$ticket_title	= ($vt_data['vtiger_lic']==1)?"ticket_title":"title";
				$ticket_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";		
				include(VIS_PATH_TEMPLATE.'vt_ticket_list.php'); 
		}
	}
	
	
	
	function vt_create_ticket_from_list($operation){ 
		global $vis_language;		
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);		
		$data=parse_form_array($operation['vis_action']);		
		
		$filter=VIS_TABLE_PREFIX.'ticket.ticket_id='.$operation['vis_ticketid'];
		list($ticket_info, $ticket_details)=$ticket_object->get_ticket($filter, '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $query = "SELECT  `content` FROM `".VIS_TABLE_PREFIX."ticket_post` WHERE `ticket_id` = '".$operation['vis_ticketid']."' ORDER BY  `post_id` DESC LIMIT 0,1";
		$result=$database->query_exec($query);
        $result = $database->fetch_result_array($result);			
		$data['vis_ticket_post'] = $result[0]['content'];
		$data['vis_subject']= $ticket_details[0]['subject'];		
		$data['vis_new_ticket_list_client'] = $ticket_details[0]['email'];
		//print_r($data);
		//$data['vis_vt_user'] != -1
		//$data['vis_vt_status'] !=""
		//$data['vis_vt_priority'] !="" 
		if($data['vis_vt_user']!=-1){
		 $msg = $vt_ticket_id = $this->vt_create_ticket($data);
		}else{ $vt_ticket_id = -1; }		 
		if($data['vis_vt_user'] != -1 && $vt_ticket_id>0){
			echo "<script> $('#vt_list').visExecution('load_operations', {'vis_module':'ticket', 'vis_operation':'vt_ticket_list', 'vis_integration_id':'".$operation['vis_integration_id']."'});  </script>";
			
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "' . $vis_language['MSGSUCCOPRT'] . '");$("#btn_create_ticket").button("reset"); </script>';
		}else{
			 echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].$msg.'"); </script>';
		}
		
	}
	function get_vt_opp_details($operation) {
		global $vis_language;		
		$database=new class_database();
		
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
		
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 ');		//AND domain_id='.$operation['vis_domain']
		
		if($vt_acc_list!=-1){
			$vt_acc_list_tmp = $vt_acc_list[0]; 
			$vt_data['vtiger_url']	= trim($vt_acc_list_tmp['vtiger_url']);
			$vt_data['vtiger_user']	= trim($vt_acc_list_tmp['vtiger_user']);
			$vt_data['vtiger_key']	= trim($vt_acc_list_tmp['vtiger_key']);
			$vt_data['vtiger_lic'] 	= $vt_acc_list_tmp['vtiger_lic'];	
			$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Potentials":"Potentials";	
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,5"; 		
			$vt_data['query'] = $qry;
			$vt_opp_records = $setting_object->get_vtiger('do_query',$vt_data);
			$opp_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";		
			
		}	
		include(VIS_PATH_TEMPLATE.'vtiger_opp_details.php');
        return true;
    }
	function vt_opp_list($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Potentials":"Potentials";	
		
	    if($vt_acc_list!=-1){
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,5"; 
				$vt_data['query'] = $qry;
				$vt_opp_records = $setting_object->get_vtiger('do_query',$vt_data);
				$opp_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";				
				if($vt_opp_records!=-1){
					include(VIS_PATH_TEMPLATE.'vt_opp_list.php'); 
				}else{
					include(VIS_PATH_TEMPLATE.'no_record_yet.php'); }
				
		}else{
			include(VIS_PATH_TEMPLATE.'no_record_yet.php'); 
		}
					
    }
	function vt_opportunity($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 ');	//AND domain_id='.$operation['vis_domain']	
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Potentials":"Potentials";
		
		$vt_opp_module_desc = $setting_object->get_vtiger('module_desc',$vt_data);
		
		$opportunity_type 	= $vt_opp_module_desc['fields'][5]['type']['picklistValues'];
		$leadsource			= $vt_opp_module_desc['fields'][7]['type']['picklistValues'];
		$sales_stage		= $vt_opp_module_desc['fields'][8]['type']['picklistValues'];
	    //Accounts
		$qry = "SELECT * FROM   Accounts "; 
		$vt_data['query'] = $qry;
		$related_to = $setting_object->get_vtiger('do_query',$vt_data);
		
		//owner
		$qry = "SELECT * FROM   Users "; 
		$vt_data['query'] = $qry;
		$assigned_user_id = $setting_object->get_vtiger('do_query',$vt_data);
		
		//Campaigns
		$qry = "SELECT * FROM   Campaigns "; 
		$vt_data['query'] = $qry;
		$campaignid = $setting_object->get_vtiger('do_query',$vt_data);
				
		//Contacts
		$qry = "SELECT * FROM   Contacts "; 
		$vt_data['query'] = $qry;
		$contact_id = $setting_object->get_vtiger('do_query',$vt_data);
				
		include(VIS_PATH_TEMPLATE.'vtiger_create_opp.php'); 
		
					
    }
	function vt_opp_form($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Potentials":"Potentials";	
		
	    $vt_opp_module_desc = $setting_object->get_vtiger('module_desc',$vt_data);
		
		$opportunity_type 	= $vt_opp_module_desc['fields'][5]['type']['picklistValues'];
		$leadsource			= $vt_opp_module_desc['fields'][7]['type']['picklistValues'];
		$sales_stage		= $vt_opp_module_desc['fields'][8]['type']['picklistValues'];
	    
		//Accounts
		$qry = "SELECT * FROM   Accounts "; 
		$vt_data['query'] = $qry;
		$related_to = $setting_object->get_vtiger('do_query',$vt_data);
		
		//owner
		$qry = "SELECT * FROM   Users "; 
		$vt_data['query'] = $qry;
		$assigned_user_id = $setting_object->get_vtiger('do_query',$vt_data);
		
		//Campaigns
		$qry = "SELECT * FROM   Campaigns "; 
		$vt_data['query'] = $qry;
		$campaignid = $setting_object->get_vtiger('do_query',$vt_data);
				
		//Contacts
		$qry = "SELECT * FROM   Contacts "; 
		$vt_data['query'] = $qry;
		$contact_id = $setting_object->get_vtiger('do_query',$vt_data);	
			
		include(VIS_PATH_TEMPLATE.'vt_opp_form.php');

		
					
    }
	function vt_create_opp($operation) { //echo '<pre>'; print_r($operation); echo '</pre>';
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Potentials":"Potentials";	
		//print_r($vt_data);		
		$data=parse_form_array($operation['vis_action']);		
		
		$vt_data["arr"] = array();
		
		if(isset($data["potentialname"]) && $data["potentialname"]!=''){ $vt_data['arr']["potentialname"] = $data["potentialname"]; }
		
		if(isset($data["amount"]) && $data["amount"]!=''){ $vt_data['arr']["amount"] = $data["amount"]; }
		
		if(isset($data["related_to"]) && $data["related_to"]!=''){ $vt_data['arr']["related_to"] = $data["related_to"]; }
		
		if(isset($data["closingdate"]) && $data["closingdate"]!=''){ $vt_data['arr']["closingdate"] = urlencode($data["closingdate"]) ; }
		
		if(isset($data["opportunity_type"]) && $data["opportunity_type"]!=''){ $vt_data['arr']["opportunity_type"] = $data["opportunity_type"]; }
		
		if(isset($data["nextstep"]) && $data["nextstep"]!=''){ $vt_data['arr']["nextstep"] = $data["nextstep"]; }
		
		if(isset( $data["leadsource"]) && $data["leadsource"]!=''){ $vt_data['arr']["leadsource"] = $data["leadsource"]; }
		
		if(isset($data["sales_stage"]) && $data["sales_stage"]!=''){ $vt_data['arr']["sales_stage"] = $data["sales_stage"]; }
		
		if(isset($data["assigned_user_id"]) && $data["assigned_user_id"]!='' ){ $vt_data['arr']["assigned_user_id"] = $data["assigned_user_id"] ; }
		
		if(isset($data["probability"]) && $data["probability"]!=''){ $vt_data['arr']["probability"] = $data["probability"]; }
		
		if(isset($data["campaignid"]) && $data["campaignid"]!=''){ $vt_data['arr']["campaignid"] = $data["campaignid"];  }
		
		if(isset($data["description"]) && $data["description"]!=''){ $vt_data['arr']["description"] = $data["description"]; }
		
		if(isset($data["forecast_amount"]) && $data["forecast_amount"]!=''){ $vt_data['arr']["forecast_amount"] = $data["forecast_amount"]; }
		
		if(isset($data["contact_id"]) && $data["contact_id"]!=''){ $vt_data['arr']["contact_id"] = $data["contact_id"]; }
		
		//echo '<pre>'; print_r($vt_data); echo '</pre>';
		$vt_opp_id =  $setting_object->get_vtiger('create_record',$vt_data);
		
		if(is_numeric($vt_opp_id) && $vt_opp_id!=-1){
			$data['vis_vt_id'] = $vt_opp_id;
			$data['vis_vt_opration'] = 'update_opp';
			if($vt_data['vtiger_lic']==1){  $this->vt_curl_post($vt_data['vtiger_url'],$data);
			}
			echo "<script> $('#vis_details_list').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_vt_opp_details', 'type':'opportunities'});
			</script>";
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "' . $vis_language['MSGSUCCOPRT'] . '"); </script>';			
			
		}else{
			echo "<script>$('#btn_add_ticket').button('reset');</script>";
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].$vt_opp_id.'"); </script>';
		}
	
	
	}
	function lm_vtiger_opp($operation) {
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Potentials":"Potentials";	
		//print_r($vt_data);
		
		$start = 0;
		$limit = 5;
		$page = 1;
		if(isset($operation['vis_page'])){ 
			$load_more_id = "load_more_".$operation['vis_page']+1;			
			$start = $operation['vis_page']*$limit;
			$page = $operation['vis_page']+1;		
			
		}
		
	    if($vt_acc_list!=-1){
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT $start,$limit"; 
				$vt_data['query'] = $qry;
				$vt_opp_records = $setting_object->get_vtiger('do_query',$vt_data);
				$opp_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";				
				include(VIS_PATH_TEMPLATE.'vt_opp_list.php'); 
		}
	}
	
	
	
	//projects
	function get_vt_project_details($operation) {
		global $vis_language;		
		$database=new class_database();
		
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
		
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 ');		//AND domain_id='.$operation['vis_domain']
		
		if($vt_acc_list!=-1){
			$vt_acc_list_tmp = $vt_acc_list[0]; 
			$vt_data['vtiger_url']	= trim($vt_acc_list_tmp['vtiger_url']);
			$vt_data['vtiger_user']	= trim($vt_acc_list_tmp['vtiger_user']);
			$vt_data['vtiger_key']	= trim($vt_acc_list_tmp['vtiger_key']);
			$vt_data['vtiger_lic'] 	= $vt_acc_list_tmp['vtiger_lic'];	
			$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Project":"Project";	
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,5"; 		
			$vt_data['query'] = $qry;
			$vt_proj_records = $setting_object->get_vtiger('do_query',$vt_data);
			$proj_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";		
			//print_r($vt_proj_records);
		}	
		include(VIS_PATH_TEMPLATE.'vtiger_proj_details.php');
        return true;
    }
	function vt_proj_list($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Project":"Project";	
		
	    if($vt_acc_list!=-1){
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,5"; 
				$vt_data['query'] = $qry;
				$vt_proj_records = $setting_object->get_vtiger('do_query',$vt_data);
				$proj_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";			
				
				if($vt_proj_records!=-1){
					include(VIS_PATH_TEMPLATE.'vt_proj_list.php'); 
				}else{
					include(VIS_PATH_TEMPLATE.'no_record_yet.php'); }
		}else{
			include(VIS_PATH_TEMPLATE.'no_record_yet.php'); 
		}
					
    }
	function vt_project($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 ');	//AND domain_id='.$operation['vis_domain']	
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Project":"Project";
		
		$vt_proj_module_desc = $setting_object->get_vtiger('module_desc',$vt_data);		
		$projectstatus			= $vt_proj_module_desc['fields'][4]['type']['picklistValues'];		
		$projecttype 	= $vt_proj_module_desc['fields'][5]['type']['picklistValues'];	
		$projectpriority		= $vt_proj_module_desc['fields'][11]['type']['picklistValues'];
		$progress = $vt_proj_module_desc['fields'][12]['type']['picklistValues'];
	    //Accounts
		$qry = "SELECT * FROM   Accounts "; 
		$vt_data['query'] = $qry;
		$related_to = $setting_object->get_vtiger('do_query',$vt_data);
		
		//owner
		$qry = "SELECT * FROM   Users "; 
		$vt_data['query'] = $qry;
		$assigned_user_id = $setting_object->get_vtiger('do_query',$vt_data);
		
		//Campaigns
		$qry = "SELECT * FROM   Campaigns "; 
		$vt_data['query'] = $qry;
		$campaignid = $setting_object->get_vtiger('do_query',$vt_data);
				
		//Contacts
		$qry = "SELECT * FROM   Contacts "; 
		$vt_data['query'] = $qry;
		$contact_id = $setting_object->get_vtiger('do_query',$vt_data);
				
		include(VIS_PATH_TEMPLATE.'vtiger_create_proj.php'); 
		
					
    }
	function vt_create_proj($operation) { 
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Project":"Project";	
		//print_r($vt_data);		
		$data=parse_form_array($operation['vis_action']);		
		
		$vt_data["arr"] = array();
		
		if(isset($data["projectname"]) && $data["projectname"]!=''){ $vt_data['arr']["projectname"] = $data["projectname"]; }
		
		if(isset($data["startdate"]) && $data["startdate"]!=''){ $vt_data['arr']["startdate"] = $data["startdate"]; }
		
		if(isset($data["targetenddate"]) && $data["targetenddate"]!=''){ $vt_data['arr']["targetenddate"] = $data["targetenddate"]; }
		
		if(isset($data["actualenddate"]) && $data["actualenddate"]!=''){ $vt_data['arr']["actualenddate"] = $data["actualenddate"] ; }
		
		if(isset($data["projectstatus"]) && $data["projectstatus"]!=''){ $vt_data['arr']["projectstatus"] = $data["projectstatus"]; }
		
		if(isset($data["projecttype"]) && $data["projecttype"]!=''){ $vt_data['arr']["projecttype"] = $data["projecttype"]; }
		
		if(isset( $data["linktoaccountscontacts"]) && $data["linktoaccountscontacts"]!=''){ $vt_data['arr']["linktoaccountscontacts"] = $data["linktoaccountscontacts"]; }
		
		if(isset($data["assigned_user_id"]) && $data["assigned_user_id"]!=''){ $vt_data['arr']["assigned_user_id"] = $data["assigned_user_id"]; }
		
		if(isset($data["targetbudget"]) && $data["targetbudget"]!='' ){ $vt_data['arr']["targetbudget"] = $data["targetbudget"] ; }
		
		if(isset($data["projecturl"]) && $data["projecturl"]!=''){ $vt_data['arr']["projecturl"] = $data["projecturl"]; }
		
		if(isset($data["projectpriority"]) && $data["projectpriority"]!=''){ $vt_data['arr']["projectpriority"] = $data["projectpriority"];  }
		
		if(isset($data["progress"]) && $data["progress"]!=''){ $vt_data['arr']["progress"] = $data["progress"]; }
		
		if(isset($data["description"]) && $data["description"]!=''){ $vt_data['arr']["description"] = $data["description"]; }	
		
		$vt_opp_id =  $setting_object->get_vtiger('create_record',$vt_data);
		
		if(is_numeric($vt_opp_id) && $vt_opp_id!=-1){
			$data['vis_vt_id'] = $vt_opp_id;
			$data['vis_vt_opration'] = 'update_proj';
			if($vt_data['vtiger_lic']==1){ $this->vt_curl_post($vt_data['vtiger_url'],$data);
			}
			echo "<script> $('#vis_details_list').visExecution('load_operations',{'vis_module':'ticket', 'vis_operation':'get_vt_project_details', 'type':'projects'});
			</script>";
			
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "' . $vis_language['MSGSUCCOPRT'] . '"); </script>';		
			
		}else{
			echo "<script>$('#btn_add_ticket').button('reset');</script>";
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].$vt_opp_id.'"); </script>';
		}
	
	
	}
	function get_vt_proj_details($operation) {
		global $vis_language;		
		$database=new class_database();
		
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_object=new class_setting($database);
		
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 ');		//AND domain_id='.$operation['vis_domain']
		
		if($vt_acc_list!=-1){
			$vt_acc_list_tmp = $vt_acc_list[0]; 
			$vt_data['vtiger_url']	= trim($vt_acc_list_tmp['vtiger_url']);
			$vt_data['vtiger_user']	= trim($vt_acc_list_tmp['vtiger_user']);
			$vt_data['vtiger_key']	= trim($vt_acc_list_tmp['vtiger_key']);
			$vt_data['vtiger_lic'] 	= $vt_acc_list_tmp['vtiger_lic'];	
			$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Project":"Project";	
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT 0,100"; 		
			$vt_data['query'] = $qry;
			$vt_proj_records = $setting_object->get_vtiger('do_query',$vt_data);
			$proj_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";		
			
		}	
		include(VIS_PATH_TEMPLATE.'vtiger_proj_details.php');
        return true;
    }
	function lm_vtiger_proj($operation) {
		global $vis_language;	
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting_object=new class_setting($database);	
		$vt_acc_list = $setting_object->vtiger_integration_list('integration_type=48 and is_enabled=1 AND integration_id='.$operation['vis_integration_id']);		
		$vt_data['vtiger_url']	= trim($vt_acc_list[0]['vtiger_url']);
		$vt_data['vtiger_user']	= trim($vt_acc_list[0]['vtiger_user']);
		$vt_data['vtiger_key']	= trim($vt_acc_list[0]['vtiger_key']);
		$vt_data['vtiger_lic'] 	= $vt_acc_list[0]['vtiger_lic'];
		
		$vt_data['module_name'] = ($vt_data['vtiger_lic']==1)?"Project":"Project";	
		//print_r($vt_data);
		
		$start = 0;
		$limit = 5;
		$page = 1;
		if(isset($operation['vis_page'])){ 
			$load_more_id = "load_more_".$operation['vis_page']+1;			
			$start = $operation['vis_page']*$limit;
			$page = $operation['vis_page']+1;		
			
		}
		
	    if($vt_acc_list!=-1){
			$qry = "SELECT * FROM    ".$vt_data['module_name']." ORDER BY createdtime DESC LIMIT $start,$limit"; 
				$vt_data['query'] = $qry;
				$vt_proj_records = $setting_object->get_vtiger('do_query',$vt_data);
				$proj_url = $vt_data['vtiger_url']."index.php?module=".$vt_data['module_name']."&view=Detail&record=";
				
				include(VIS_PATH_TEMPLATE.'vt_proj_list.php'); 
		}
	}
	function vt_curl_post($vtiger_url,$data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$vtiger_url."visionhelpdesk/vt_vision.php");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$server_output = curl_exec ($ch);
		$info = curl_getinfo($ch);// print_r($info);
		curl_close ($ch);
	}
	###vtiger
	function execute_ticket_last_activity_cron($cron_time)
	{
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting=new class_setting($database);
		$ticket=new class_ticket($database);
		$mail_object=new class_mail($database);
		$staff_object=new class_staff($database);
		$operation_hnd=new operation();
        $ticket_detail=$ticket->get_ticket('unix_timestamp() -'.VIS_TABLE_PREFIX.'ticket.modify_date <= '.$cron_time, '', 0, '', 0, VIS_LOCATION_AREA);
		list($info, $tickets)=$ticket_detail;
	 
        if($tickets!=-1) for($i=0;$i<count($tickets);$i++){
			$tickets[$i]['vis_module']='ticket';
			$tickets[$i]['vis_operation']='on_last_activity';
			$tickets[$i]['vis_match_workflow_id']=$workflow_id;
			$operation_hnd->operation_flow($tickets[$i], 0, VIS_LOCATION_AREA, $database);
			$staff_object->apply_task_automation($tickets[$i], 0, VIS_LOCATION_AREA, $database);
		}
		$setting->update_cron_time();
		
	}
	
	///drive attachments
	function drive_search($operation){
	global $vis_language;
	$database=new class_database();
	include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
	$object=new class_setting($database);
	$filter='integration_type=42 AND is_enabled=1';
	list($gcal_info, $gcal_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
	$gcal_details = $gcal_details[0]; 
	$filter='integration_type=49';
	list($dropbox_info, $dropbox_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); // echo '<pre>';print_r($dropbox_details);
	$dropbox_details = $dropbox_details[0]; 
	 include(VIS_PATH_TEMPLATE.'attach_drive.php');
    return true;
	 }
	 
	#for mobile app  
    function send_notification($ticket_id,$ticket_type,$access)
    {
      //device id 0 for android mobile,3 for iphone
      //ticket type 1 for new ticket,2 for client reply
      global $vis_language;
      $database = new class_database();
     
      $loc_ticket_type = "";
      $event_id = 0;
      if($ticket_type==1){
            $event_id  = 1;
            $loc_ticket_type  = "New ticket";
      }
      if($ticket_type==2){
            $event_id  = 2; 
            $loc_ticket_type  = "Client reply";
      }
      include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
      $object = new class_staff($database);
      $devices = $object->get_devicelist();
      
      $query	=   "SELECT  * FROM `".VIS_TABLE_PREFIX."ticket` WHERE  `ticket_id` = ".$ticket_id;
	  
      $result =   mysql_query($query);
      $ticket_result = mysql_fetch_array($result);
      	  

      $clnt_id=$ticket_result['client_id'];
      $client_notify_query = "SELECT  * FROM ".VIS_TABLE_PREFIX."client WHERE  client_id = ".$clnt_id;
      $result_client=$database->query_exec($client_notify_query );
      $result_client_notify = $database->fetch_result_array($result_client);
      $fname = $result_client_notify[0]['first_name'];
      $lname = $result_client_notify[0]['last_name'];
      $fullname=$fname." ".$lname;          
      $body = array();
      $body['aps']['ticket_id'] = $ticket_result['ticket_id'];
      $body['aps']['ticket_hash'] = $ticket_result['ticket_hash'];
      $body['aps']['department_id'] = $ticket_result['department_id'];
      $body['aps']['client_id'] = $ticket_result['client_id'];
    
      $body['aps']['alert'] = $loc_ticket_type;
      $body['aps']['badge'] = 1;
      $body['aps']['link_url'] = " ";
      $body['aps']['sound'] = "default";
	  
      for($i=0;$i<count($devices);$i++)
	  {
      
      $staff_id  = $devices[$i]["staff_id"];
      list($departmentaccess,$domainaccess) = $object->get_staffacessdepartments($devices[$i]["staff_id"]);

     if($departmentaccess ==0 || in_array($access, $domainaccess)) 
              {
				  if($devices[$i]["device_type"]==3)
                  {
                   $this->send_apns($devices[$i]["api_key"],$body);
                  }

				if($devices[$i]["device_type"]==0 && $devices[$i]["api_key"]!="")
				{
					// API access key from Google API's Console

					define( 'API_ACCESS_KEY', 'AIzaSyDhNfDCH6BbV3VECzdzeAnDfIki-_0ROGA' );//thevisionworld2gmail.com

					$registrationIds = array($devices[$i]["api_key"]);//Changed Line
					$ticket_id       = $ticket_result['ticket_id'];
					$hash            = $ticket_result['ticket_hash'];
					$department_id   = $ticket_result['department_id'];
					$client_id       = $ticket_result['client_id'];
				
    				$msg = array
					(
						'message' 	=> $ticket_result,
						'event'	    => $event_id,
						'client_id'  => $client_id,
						'department_id'	=> $department_id,
						'ticket_id'	=> $ticket_id,
						'hash'	=> $hash,
						'fullname'	=> $fullname,
						'subtitle'	=> 'This is a subtitle. subtitle',
						'tickerText'	=> 'Ticker text here...Ticker text here...Ticker text here',
						'vibrate'	=> 1,
						'sound'	=> 1,
						'largeIcon'	=> 'large_icon',
						'smallIcon'	=> 'small_icon'
					);
					   
					$fields = array
					( 
					'registration_ids' 	=> $registrationIds,  
					'data'		=> $msg 
					);
					$headers = array
					(
					'Authorization: key=' . API_ACCESS_KEY,
					'Content-Type: application/json'
					);

					$ch = curl_init();
					curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
					curl_setopt( $ch,CURLOPT_POST, true );
					curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
					curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
					curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
					curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
					$result = curl_exec($ch );
					curl_close( $ch );
					echo $result;
		  		}
         }
    
      }
  }
		#For mobile app
		function send_apns($deviceToken,$body)
		{
				//Setup stream (connect to Apple Push Server)
				$ctx = stream_context_create();
				stream_context_set_option($ctx, 'ssl', 'passphrase', 'vision');
				stream_context_set_option($ctx, 'ssl', 'local_cert', VIS_PATH_PLUGINS.'iphone/ckProd.pem');
				$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
				stream_set_blocking ($fp, 0); 
				if (!$fp) {
				// echo "Failed to connect (stream_socket_client): $err $errstrn";
				} 
				else 
				{
					// Keep push alive (waiting for delivery) for 90 days
					$apple_expiry = time() + (90 * 24 * 60 * 60); 
					$apple_identifier = 1;

					$payload = json_encode($body);
					// Enhanced Notification
					$msg = pack("C", 1) . pack("N", $apple_identifier) . pack("N", $apple_expiry) . pack("n", 32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",  strlen($payload)) . $payload; 
					// SEND PUSH
					fwrite($fp, $msg);
					fclose($fp);
				}
		}
		
		#for mobile app 
		function get_ticket_category($operation)
		{  
			$database=new class_database(); 
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
			$object=new class_ticket($database);        
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php'); 
			$setting_object=new class_setting($database);        
			$dept_access = "";        
			if(isset($operation['vis_department_id']))           
			$dept_access = ' and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'];        
			$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1'.$dept_access ,VIS_STAFF_ID, VIS_LOCATION_AREA); 
			if($department_details!=-1){ 
			$filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:''; 
			if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) { if($filter!='') $filter.=' and '; $filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))'; } if($filter!='') $filter.=' and '; 
			$filter.='is_enabled=1'; 
			$department_details=$setting_object->get_ticket_category_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
			
			$database->database_disconnect(); echo get_xml($department_details[1], 'category'); return true; }   

		}
	  
	 
     #for mobile app
	 function get_ticket_subcategory($operation) 
	 {
		$database=new class_database(); 
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
		$object=new class_ticket($database);        
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php'); 
		$setting_object=new class_setting($database);        
		$dept_access = "";        
		if(isset($operation['vis_department_id']))           
		$dept_access = ' and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'];        
		$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1'.$dept_access ,VIS_STAFF_ID, VIS_LOCATION_AREA); 
		if($department_details!=-1){ 
		$filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:''; 
		$temp=$filter;
		$filter=VIS_TABLE_PREFIX.'ticket_subcategory.'.$temp;      
		if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id'])) { if($filter!='') 
			$filter.=' and '; $filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))'; } if($filter!='') $filter.=' and '; 
		
		$filter.='avis_ticket_subcategory.is_enabled=1';
		$department_details=$setting_object->get_ticket_subcategory_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
		
		$database->database_disconnect(); echo get_xml($department_details[1], 'subcategory'); return true; }
		}
	 
		 #for mobile app
		 function get_location_data($operation)
		 {       
			$database=new class_database(); 
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
			$object=new class_ticket($database);        
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php'); 
			$setting_object=new class_setting($database);        
			$dept_access = "";        
			if(isset($operation['vis_department_id']))           
			$dept_access = ' and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'];        
			$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1'.$dept_access ,VIS_STAFF_ID, VIS_LOCATION_AREA); 
			if($department_details!=-1)
			{ 
				$filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:''; 
				if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id']))
					{
					if($filter!='') $filter.=' and '; $filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))';//Previous
					} 
					if($filter!='') $filter.=' and ';$filter.='is_enabled=1';  
				
			$department_details=$setting_object->get_location_category("",$filter); 
				
				$database->database_disconnect();
				echo get_xml($department_details, 'location');
				return true;
			}   
		 }
	
		 #for mobile app
		 function get_ticket_item($operation)
		 {
			$database=new class_database(); 
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
			$object=new class_ticket($database);        
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php'); 
			$setting_object=new class_setting($database);        
			$dept_access = "";        
			if(isset($operation['vis_department_id']))           
			$dept_access = ' and '.VIS_TABLE_PREFIX.'department.department_id='.$operation['vis_department_id'];        
			$department_details=$object->get_department(VIS_TABLE_PREFIX.'department.is_enabled=1'.$dept_access ,VIS_STAFF_ID, VIS_LOCATION_AREA); 
			if($department_details!=-1){ 
			$filter=(isset($operation['vis_filter']) && $operation['vis_filter']!='')?$operation['vis_filter']:''; 
			$temp=$filter;
			
			$filter=VIS_TABLE_PREFIX.'ticket_item.'.$temp;      
			if(isset($operation['vis_department_id']) && is_numeric($operation['vis_department_id']))
				{ 
				//if($filter!='') 
				//$filter.=' and ';
			   // $filter.='(department_access=0 or find_in_set('.$operation['vis_department_id'].', department_access))'; 
				}
				if($filter!='')
					$filter.=' and '; 
			
			$filter.=VIS_TABLE_PREFIX.'ticket_item.is_enabled=1';
			$department_details=$setting_object->get_ticket_item_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
			
			$database->database_disconnect(); echo get_xml($department_details[1], 'item');
			return true;
			}
		}
	 
	    #For category hide or show in mobile app
		function get_domain_setting($operation) 
		{
			$database=new class_database(); 
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php'); 
			$object=new class_ticket($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php'); 
			$setting_object=new class_setting($database);
			$dept_access = "";
			if(isset($operation['vis_domain_id'])) 
			$module_setting1=$setting_object->get_module_setting('domain_id='.$operation['vis_domain_id'].' and module_id=2', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$database->database_disconnect();
			echo get_xml($module_setting1, 'domainsetting');
		    return true;

		}
		
		#For mobile app
		function get_branding($operation) 
		{
			   if(!defined('VIS_BRAND_FREE') || VIS_BRAND_FREE!='VALID') 
				{ 
					echo get_xml("1", 'brand');
					return true;
				}
				else
				{
					echo get_xml("0", 'brand');
					return false;
				}
		}
	
	// Function is created to add/attach the CI to ticket (Added by Sachin E.)
	function get_allassets($operation){
		global $vis_language;
		$database=new class_database(); 
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'cmdb.php');
        $cmdb_object=new class_cmdb($database);
		$filter = '';
		$data= isset($operation['vis_action']) && $operation['vis_action']!='' ? parse_form_array($operation['vis_action']) : $operation;
		$filter .= " ".VIS_TABLE_PREFIX."itil_cmdb_assets.ci_type_id=".$data['vis_ci_type'];
		$assets_details=$cmdb_object->get_assets($filter, '', '', '', VIS_CLIENT_ID, 1);
		if($assets_details!=-1){
			$list_data='';
			$list_data .= '<div id="ci_list" class="form-group">';
			$list_data .= '<label class="col-sm-2 control-label">'.$vis_language['TXTCISELECT'].'</label>';
			$list_data .= '<div class="col-sm-8">';
			$list_data .= '<select class="form-control input-sm selectpicker" name="vis_asset_id" id="vis_asset_id">';
			$list_data .= '<option value="-1">'.$vis_language['TXTSELECT'].'</option>';
			if($assets_details!= -1){
				for($i=0;$i<count($assets_details);$i++){
					$list_data .= "<option value='".$assets_details[$i]['assets_id']."'>".$assets_details[$i]['name'].'</option>';
				}
			}
			$list_data .= '</select>';
			$list_data .= '</div>';
			$list_data .= '</div>';
			echo json_encode( array('list'=> $list_data));
		}else{
			echo $assets_details;
		}
	}
	
	function lock_onreplyticket($operation){ 
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
		$already_lock=$ticket_object->get_ticket_lock($operation['vis_ticket_id'],'', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(!empty($already_lock) && $already_lock != -1 && $operation['vis_action'] == 'lock'){ return true; }else{
        $ticket_lock = $ticket_object->lock_ticket($operation['vis_ticket_id'], $operation['vis_action'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($ticket_lock){
            $lock_icon_class = $title = $lock_status = "";
            if($operation['vis_action'] == 'lock'){
                $lock_icon_class = "vh-lock";
                $lock_status = 0;
                $title = $vis_language['TXTLOCKED'];
				
            } else {
                $lock_icon_class =  "vh-unlock";
                $lock_status = 1;
                $title = $vis_language['TXTUNLOCKED'];
            }
        }
		return true;
				}
    }
	
	/********************* [ xero api - details] **************************/
	function get_xero_details($operation) {	
		global $vis_language;
		$database=new class_database();
		$operation['type']='profile';
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=56 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($xero_info, $xero_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA); 
 		require_once('../plugins/xero/lib/XeroOAuth.php');
		include '../plugins/xero/tests/testRunner.php';
		define ( 'BASE_PATH','../plugins/xero/');
		define ( "XRO_APP_TYPE", "Private" );
		define ( "OAUTH_CALLBACK", "oob" );
		$useragent =  '"'.$xero_details[0]['user_name'].'"';
		$signatures = array (
		'consumer_key' => $xero_details[0]['admin_user'],
		'shared_secret' => $xero_details[0]['admin_password'],
		// API versions
		'core_version' => '2.0',
		'payroll_version' => '1.0',
		'file_version' => '1.0' 
		);
	 	if (XRO_APP_TYPE == "Private") {
			$signatures ['rsa_private_key'] =	BASE_PATH.'certs/privatekey.pem';
			$signatures ['rsa_public_key'] 	= 	BASE_PATH.'certs/publickey.cer';
		}
		$XeroOAuth = new XeroOAuth ( array_merge ( array (
				'application_type' => XRO_APP_TYPE,
				'oauth_callback' => OAUTH_CALLBACK,
				'user_agent' => $useragent 
		), $signatures ) );
		$initialCheck = $XeroOAuth->diagnostics ();
		$checkErrors = count ( $initialCheck );
		if ($checkErrors > 0) {
			foreach ( $initialCheck as $check ) {
				echo 'Error: ' . $check . PHP_EOL;
			}
		} else {
		$session = persistSession ( array (
					'oauth_token' => $XeroOAuth->config ['consumer_key'],
					'oauth_token_secret' => $XeroOAuth->config ['shared_secret'],
					'oauth_session_handle' => '' 
		) );
			$oauthSession = retrieveSession ();
		}
			
		if (isset ( $oauthSession ['oauth_token'] )) {
			$XeroOAuth->config ['access_token'] = $oauthSession ['oauth_token'];
				$XeroOAuth->config ['access_token_secret'] = $oauthSession ['oauth_token_secret'];
		}
		 $response = $XeroOAuth->request('GET', $XeroOAuth->url('Contacts', 'core'), array('Where' => 'EmailAddress == "'.$operation['vis_client_email'].'"' ));
	 
		if ($XeroOAuth->response['code'] == 200) {
			   $xero_result1 = $xero_result = array();
               $contacts = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
			   $xero_result1 = $contacts->Contacts[0]->Contact;
			   $xero_result1= json_encode($xero_result1);
			   $xero_result= json_decode($xero_result1,TRUE); 
			   $operation['contact_name_xero'] = $xero_result['Name'];
		}
		include(VIS_PATH_TEMPLATE.'xero_client_details.php'); 
        return true;
    }
	/********************* [ xero api - get response] **************************/
	function xero_client_profile($operation) {	
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$object=new class_setting($database);
		$filter='integration_type=56 AND is_enabled=1 AND domain_id='.$operation['vis_domain'];
        list($xero_info, $xero_details)=$object->get_integration_setting($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
 		require_once('../plugins/xero/lib/XeroOAuth.php');
		include '../plugins/xero/tests/testRunner.php';
		define ( 'BASE_PATH','../plugins/xero/');
		define ( "XRO_APP_TYPE", "Private" );
		define ( "OAUTH_CALLBACK", "oob" );
		$useragent =  '"'.$xero_details[0]['user_name'].'"';
		$signatures = array (
		'consumer_key' => $xero_details[0]['admin_user'],
		'shared_secret' => $xero_details[0]['admin_password'],
		// API versions
		'core_version' => '2.0',
		'payroll_version' => '1.0',
		'file_version' => '1.0' 
		);
	 	if (XRO_APP_TYPE == "Private") {
			$signatures ['rsa_private_key'] =	BASE_PATH.'certs/privatekey.pem';
			$signatures ['rsa_public_key'] 	= 	BASE_PATH.'certs/publickey.cer';
		}
		$XeroOAuth = new XeroOAuth ( array_merge ( array (
				'application_type' => XRO_APP_TYPE,
				'oauth_callback' => OAUTH_CALLBACK,
				'user_agent' => $useragent 
		), $signatures ) );
		$initialCheck = $XeroOAuth->diagnostics ();
		$checkErrors = count ( $initialCheck );
		if ($checkErrors > 0) {
			foreach ( $initialCheck as $check ) {
				echo 'Error: ' . $check . PHP_EOL;
			}
		} else {
		$session = persistSession ( array (
					'oauth_token' => $XeroOAuth->config ['consumer_key'],
					'oauth_token_secret' => $XeroOAuth->config ['shared_secret'],
					'oauth_session_handle' => '' 
		) );
			$oauthSession = retrieveSession ();
		}			
		if (isset ( $oauthSession ['oauth_token'] )) {
			$XeroOAuth->config ['access_token'] = $oauthSession ['oauth_token'];
				$XeroOAuth->config ['access_token_secret'] = $oauthSession ['oauth_token_secret'];
		}		
		if($operation['type']=='profile'){
		  	$response = $XeroOAuth->request('GET', $XeroOAuth->url('Contacts', 'core'), array('Where' => 'EmailAddress == "'.$operation['vis_email'].'"'));
			if ($XeroOAuth->response['code'] == 200) {			
			   $arr_xero_result1 = $xero_result = array();
               $contacts = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
			   $arr_xero_result1 = $contacts->Contacts[0]->Contact;
			   $arr_xero_result1= json_encode($arr_xero_result1);
			   $xero_result= json_decode($arr_xero_result1,TRUE);  
			}
		}
		elseif(($operation['type']=='activity' && $operation['contact_name_xero']!='') || ($operation['type']=='pdf')){
			$array_invoice1 = $xero_result  = array();
			$response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoices', 'core'), array('Where' => 'Contact.Name.Contains("'.$operation['contact_name_xero'].'")'));
				if ($XeroOAuth->response['code'] == 200) {
				   $accounts = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
				   $array_invoice1= json_encode($accounts->Invoices[0]);
				   $xero_result= json_decode($array_invoice1,TRUE); 
			    } 
				if($operation['type']=='pdf'){
					$response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoices', 'core'), array('Where' => 'InvoiceNumber.Contains("'.$operation['vis_invoice'].'")'));
					if ($XeroOAuth->response['code'] == 200) {
					$accounts = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
					$response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoice/'.$accounts->Invoices[0]->Invoice->InvoiceID, 'core'), array(), "", 'pdf');
					$myFile = $accounts->Invoices[0]->Invoice->InvoiceID.".pdf";
					$fh = fopen($myFile, 'w') or die("can't open file");
					fwrite($fh, $XeroOAuth->response['response']);
					fclose($fh);
					$operation['type']=='activity';
					}   
				}
		}
		include(VIS_PATH_TEMPLATE.'xero_client_profile.php'); 
		return true;
    }
	function check_customdata($operation)
	{
		global $vis_language;
		$database=new class_database();
	include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
		$ticket_object=new class_ticket($database);
		$location=$operation['location'];
		//==
		//$check_custom=$ticket_object->check_custom_data($data, 2, $data['vis_service_item_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($location == 4)
        {
			$parentid=$operation['vis_survey'];
		}
		else if($location==-1)
		{
			$parentid=$operation['vis_service_item_id'];
			$check_custom=$ticket_object->check_custom_data($operation, 2, $parentid, VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
		else if($location==12)
		{
			$parentid=$operation['vis_group_id'];
		}
		else
		{
			$parentid=$operation['vis_ticket_id'];
		}
		$check_custom=$ticket_object->check_custom_data($operation, $location, $parentid, VIS_STAFF_ID, VIS_LOCATION_AREA);
		$customerrormessage=' ('.$check_custom[1].')';
		if($check_custom!=1 && $check_custom[0]==0) $check_custom='0'; else $check_custom='1';
echo json_encode(array(
				    'res' => $check_custom,
					'msg' => '<div class="vis_error_message">'.$vis_language['MSGINFOMISS'].''.$customerrormessage.'</div>'
				));
		
	}
}
?>
