<?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 export {
    var $error;

     function get_attachment($operation) {
        if(isset($operation['vis_attachment']) && is_numeric($operation['vis_attachment'])) {
            $database=new class_database();
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
            $object=new class_ticket($database);
            $files=$object->get_attachment('attachment_id='.$operation['vis_attachment'], 0, VIS_LOCATION_AREA,'',$operation['get_area'],$operation['vis_client_id']);
          
            if($files[0]['parent_type'] == 1){
			  include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'selfhelp.php');
              $selfobject=new class_selfhelp($database);
              $articles=$selfobject->get_article(' article_id='.$files[0]['parent_id'], 0, VIS_LOCATION_AREA);
              $articles=$articles[1][0];
              
              $category=$selfobject->get_category(' selfhelp_id='.$articles['parent_id'], 0, VIS_LOCATION_AREA);
              $category=$category[1][0];
               
             
              if($category['display_status'] == 2 &&  VIS_LOCATION_AREA == 1 ) return false;
			  else if($category['display_status'] == 1 && IS_LOGIN ==0)return false;
              
            }
            /*if($files[0]['parent_type'] == 0){
				if($operation['operator']==1 && ($files[0]['client_id']!= VIS_CLIENT_ID))return false;
			}*/
           
            if($files==-1) return false;
            $file_path=VIS_PATH_FILES.$files[0]['content'];
            if(!file_exists($file_path)) {
                if(defined('VIS_ATTACHMENT_PATH') && file_exists(VIS_ATTACHMENT_PATH.$files[0]['content'])) $file_path=VIS_ATTACHMENT_PATH.$files[0]['content'];
            }
            $database->database_disconnect();
            header("Content-Type: ".$files[0]['file_type']);
            header('Content-Disposition: attachment; filename="'.$files[0]['file_name'].'"');
            readfile($file_path);
        }
        return true;
    }
	/*
    function advance_search($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);
        $filterid=$object->set_filter($operation, 0, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(!$filterid) echo $vis_language['MSGERROPRT'];
        else {
            $filter=$object->get_filter($filterid, VIS_STAFF_ID, VIS_LOCATION_AREA);
            list($info, $tickets)=$object->get_ticket($filter['filter'], '', 0, $sort_by, VIS_STAFF_ID, VIS_LOCATION_AREA, 1);
            $database->database_disconnect();
            if($tickets==-1) echo $vis_language['TXTNOMATCHFOUND'];
            else {
                $name=(trim($operation['vis_filter_title'])=='')?'Advance_search':$operation['vis_filter_title'];
                return $this->export_csv($tickets, $name);
            }
        }
        return true;
    }
	*/
	function advance_search($operation) {
		global $vis_language;
		global $s_filter, $s_report_type, $s_exportid , $s_email_id , $s_staff_id,$s_request_date,$s_department_id;
		
        if(isset($operation['slave_db']) && $operation['slave_db'] == 1)$database=new class_database('mysql',1);
        else $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object_client=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
		$s_filter = $operation['filter'];
		$s_report_type = $operation['report_type'];
		$s_exportid = $operation['export_id'];
		$s_email_id = $operation['staff_email'];
		$s_staff_id = $operation['staff_id'];
		$s_department_id = $operation['department_id'];
		$s_request_date = $operation['request_date'];
		
		if(isset($s_report_type) && $s_report_type!='' && $s_report_type=='14') 
{
		list($info, $tickets)=$object->get_ticket($s_filter, '', 0, $sort_by, $s_staff_id, 2, 1);}
		else  if(isset($s_report_type) && $s_report_type!='' && $s_report_type=='15') {
				$limit = '';
				list($client_info, $tickets)=$object_client->get_client($s_filter, $limit, $page, $sort_by, $s_staff_id, VIS_LOCATION_AREA);
				for($i=0;$i<count($tickets);$i++)
					unset($tickets[$i]['client_id']);
		}
		else if(isset($s_report_type) && $s_report_type!='' && $s_report_type=='97') {
				$limit 		= 	'';
				$tickets	=	$object_client->get_client_group($s_filter,$s_staff_id, VIS_LOCATION_AREA,$limit,'',$s_report_type);
		}			
		$completed_date 	= 	date('Y-m-d H:i:s'); 
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'report.php');
		$report_object=new class_report($database);	
		if($tickets==-1 || $tickets==''){
            $filename ='';	
		}
	    else {
			$filename = $operation['export_name'].'_'.rand(strtotime($completed_date),strtotime($s_request_date)); 
			/*$this->export_csv($tickets, $filename,$s_report_type);
			if(file_exists('../downloads/'.$filename.'.csv'))
			{
				$status = "completed";				
			}*/
			
if ($operation['export_type'] == 1) {
							$this->export_csv($tickets, $filename, $s_report_type,'',$s_staff_id);
							if (file_exists('../downloads/' . $filename . '.csv')) {
											$filename = $filename;
							} else {
											$filename = '';
							}
			} else if ($operation['export_type'] == 2) {
							$this->export_html($tickets, $filename, $s_report_type,'',$s_staff_id);
							
							if (file_exists('../downloads/' . $filename . '.html')) {
											$filename = $filename;
							} else {
											$filename = '';
							}
			} else if ($operation['export_type'] == 3) {
							$this->export_xlsx($tickets, $filename, $s_report_type,'',$s_staff_id);
							
							if (file_exists('../downloads/' . $filename . '.xls')) {
											$filename = $filename;
							} else {
											$filename = '';
							}
			}

			
		}
		
		
		if(isset($operation['slave_db']) && $operation['slave_db'] == 1)
		{
			$database->database_disconnect();
			$database=new class_database();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'report.php');
		    $report_object=new class_report($database);	
		}
		$result = $report_object->update_download_list($filename,$completed_date,$s_exportid);
	    if(!$result) return false;	
					include_once(VIS_PATH_FUNCTION . VIS_FUNCTION_PREFIX . 'report.php');
								$report = new report();
					$report->email_send_download($operation);
		$database->database_disconnect();
        return true;
    }
    
    function ticket_export($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($_REQUEST['Exportall']))
        {
			if($operation['vis_export_function'] == 'filter_ticket')
			{
				if(isset($operation['vis_filter_id']) && is_numeric($operation['vis_filter_id'])) $filter_id=$operation['vis_filter_id'];
				else $filter_id=1;
				$filter  = $object->get_filter($filter_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
				$filter = $filter['filter'];
				$filter .= (isset($operation['vis_draft']) && $operation['vis_draft']==1)?(' and draft_id='.VIS_STAFF_ID):' and draft_id=0';
			}
			elseif($operation['vis_export_function'] == 'filter_queue_ticket')
			{
				$filter_id=0;
				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;
				$filter  = 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';
				$filter .= (isset($operation['vis_draft']) && $operation['vis_draft']==1)?(' and draft_id='.VIS_STAFF_ID):' and draft_id=0';
			}
            list($info, $tickets)=$object->get_ticket($filter, '', 0, $sort_by, VIS_STAFF_ID, VIS_LOCATION_AREA, 1);
		}
		else
		{
			$ticketids = '';
			foreach($operation as $key=>$val) { 					
				if($key!='' && strpos($key, 'ticket_mass_chk_')!=0) {
					$ticketids .= $val.',';
				}
			}
			$ticketids=rtrim($ticketids, ',');
		}
		
		$database->database_disconnect();
		if(($tickets==-1 && isset($_REQUEST['Exportall'])) || ($ticketids=='' && !isset($_REQUEST['Exportall'])) ) echo $vis_language['TXTNOMATCHFOUND'];
		else if(isset($_REQUEST['Exportall'])) {
			$name=(trim($operation['vis_filter_title'])=='')?'Export_ticket':$operation['vis_filter_title'];
			return $this->export_csv($tickets, $name);
		}
		else {
            $name=(trim($operation['vis_filter_title'])=='')?'Export_ticket':$operation['vis_filter_title'];
			return $this->export_pdf($ticketids, $name);
        }
        return true;
    }

    function export_pdf($ticket_ids, $filename) {
        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_FUNCTION.VIS_FUNCTION_PREFIX.'ticket.php');
        $ticket_module=new ticket();
        $ticket_id=explode(',',$ticket_ids);
        $html='';
        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('Ajay Ahire');
        $pdf->SetSubject($ticket_details['subject']);
        $pdf->SetKeywords('Vision helpdesk, PDF, '.$filename);
        $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);
        for($i=0;$i<count($ticket_id);$i++){
            $custom_field_var='';
            list($ticket_info, $ticket_details)=$ticket_object->get_ticket('ticket_id='.$ticket_id[$i], 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($j=0;$j<count($post_details);$j++){
              $comment_details[$j]=(VIS_COMMENT_ACCESS==0)?-1:$ticket_object->get_post_comment($post_details[$j]['post_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);	
            }
            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.=$ticket_module->show_custom_fields($location, $ticket_details['ticket_id'], $ticket_details['department_id'], $database);
            /*$location=array(0=>3, 1=>3);
            $custom_field_var.=$ticket_module->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));
            $pdf->AddPage();
            $pdf->writeHTML($html, true, false, true, false, '');
            $pdf->lastPage();
        }
		if(count($ticket_id) > 1)
	        $pdf->SetTitle($vis_language['TXTTICKETS']);
		else
			$pdf->SetTitle($ticket_details['ticket_hash']);

        $pdf->Output($filename.'.pdf', 'I');            
        return true;
    }
    
    function export_html($report, $filename,$report_type,$config='',$staff_id='') {
		
		global $vis_language;	
		$database=new class_database();
		global $s_filter, $s_report_type, $s_exportid , $s_email_id , $s_staff_id,$s_request_date,$s_department_id; 
        if($config == 1)$database=new class_database('mysql',1);
        else $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object_client=new class_client($database);
		$fields_arr = array();
        if(is_array($report)) {
			$file = fopen('../downloads/'.$filename.'.html','w+');
			fwrite($file,'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">');
			
			if($report_type==15) //For clients only		
				$fields_arr = array('group_id', 'authentication', 'salt', 'is_verified', 'parent_id', 'domain_id', 'image_path', 'login_as', 'department_access', 'client_type', 'password_auth', 'group_type', 'description', 'display_order', 'debit', 'is_enable', 'is_enabled', 'domain', 'language_id', 'timezone', 'timezone_dst', 'theme', 'send_mail', 'group_credit', 'timezone_name', 'office_contact_num', 'mobile_number', 'birthdate', 'office_phone');
			elseif($report_type==14)//For tickets only
				$fields_arr = array('user_replied', 'status_id', 'sdue_time', 'rdue_time', 'ticket_priority', 'ticket_status', 'ticket_type', 'initials', 'salt', 'authentication', 'is_spam', 'is_banned', 'group_id', 'is_approved', 'language', 'office_name', 'parent_id', 'department_id', 'priority_id', 'type_id', 'category_id', 'subcategory_id', 'item_id', 'level_id', 'channel_id', 'client_id','domain_id');
				
				//$txt="<table style='border:1px solid;'><tr>";
				if($report['Report_title']){
					$txt="<table style='border:1px solid;'><tr><th colspan='5' style='border:1px solid !important;'>".$report['Report_title']."</th></tr><tr>";
				}else{
					$txt="<table style='border:1px solid;'><tr>"; // This is old line without if else case
				}
				 fwrite($file,$txt); 
            if(isset($report[0]) && is_array($report[0])) { 
                foreach($report[0] as $key=>$val){
					if( in_array($key, $fields_arr)) // these fields not req in csv
						continue;
							switch($key){ 
								case 'receive_date': 
									$key='ticket_entry';
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'office_name' : $key='Company name';
												   break;
								case 'office_email' : $key='Company email';
													  break;
								case 'office_address' : $key='Company address';
														break;
								case 'office_fax' : $key='Company fax';
														break;
								case 'office_website' : $key='Company website';
														break;
								case 'group_name' : $key='Organization name';
													break;
							}
						}
						$txt='<th style="border:1px solid !important;">'.strtoupper( str_replace("_", " ", $key) ).'</th>';
					fwrite($file,$txt); // replace underscore with space & uppercase title
				}
                 fwrite($file,"</tr>"); 
                for($i=0;$i<count($report);$i++) { 
                    foreach($report[$i] as $key=>$val) { 
						if( in_array($key, $fields_arr)) // these fields not req in csv
							continue;
							switch($key){ 
								case 'receive_date': 
									$val = format_datetime_rpt($val,$staff_id);	
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'gender': 
									$val= ($val == 0) ? 'Male' : 'Female';	
									break;	
								case 'is_spam': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;		
								case 'is_banned': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'is_approved': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'language': 
									$lang_data = $object_client->get_client_language($val);
									if($lang_data!=-1) $val = $lang_data['language_name'];
									else $val = '';
									break;
							}
						}elseif($report_type==14){//For tickets only
						
							$ticket_details = $report[$i];
							$due_time = $resolution_time = '';
							// due_time
							if($ticket_details['due_time'] <= 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3 && $ticket_details['sdue_time'] != 0) 
								$due_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['due_time'] > 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3) 
								$due_time = count_remain_time($ticket_details['due_time']); 
							else 
								$due_time = $vis_language['TXTUNDUE'];
								
							// resolution_time
							if($ticket_details['resolution_time'] <= 0 && $ticket_details['status_id'] != 3 && $ticket_details['rdue_time'] != 0) 
									$resolution_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['resolution_time'] > 0 && $ticket_details['status_id'] != 3) 
								$resolution_time = count_remain_time(($ticket_details['resolution_time'])); 
							elseif($ticket_details['rdue_time'] > 0 && $ticket_details['status_id'] == 3) 
								$resolution_time = count_remain_time(($ticket_details['modify_date'])-($ticket_details['creation_date']));
							else 
								$resolution_time = $vis_language['TXTUNDUE'];	
					
							switch($key){ 
								case 'creation_date': 
									//
								case 'modify_date':	
									$val = format_datetime_rpt($val,$staff_id);
									break;
								case 'due_time':
									$val = $due_time;
									break;
								case 'resolution_time': 
									$val = $resolution_time;	
									break;	
							}
						}	
						
                        if($val!='' && strpos($val, '</td>')!=0) {
							//$val = stripslashes($val);
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
                            fwrite($file,'<tr><td style="border:1px solid;">.'.$val.'</td>');
                        }
                        else
						{ 
							//$val = stripslashes($val);
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,'<td style="border:1px solid;">'.$val.'</td>');
						}
                    }
                    
                    fwrite($file,"</tr>");
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
                            if($key!='' && strpos($key, ',')!=0) {
                                fwrite($file,'"'.$key.'",');
                            }
                            else fwrite($file,$key.",");  
                        }
                        fwrite($file,"</tr>");
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						if($val!='' && strpos($val, ',')!=0) {
							//$val = stripslashes($val);
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
                            fwrite($file,'"'.$val.'",');
                        }
                        else
						{ 
							//$val = stripslashes($val);
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,$val.",");
						}
                    }
                    fwrite($file,"</table>");
                }
            }fclose($file);
        }
        else return false;
    }
    
	function export_xlsx($report, $filename,$report_type,$config='',$staff_id='') {
		global $vis_language;	
		$database=new class_database();
		global $s_filter, $s_report_type, $s_exportid , $s_email_id , $s_staff_id,$s_request_date,$s_department_id; 
        if($config == 1)$database=new class_database('mysql',1);
        else $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object_client=new class_client($database);
		$fields_arr = array();
        if(is_array($report)) {			
		    $file = fopen('../downloads/'.$filename.'.xls','w+');
			
			fwrite($file,$report['Report_title']."\n\n");
			
			if($report_type==15) //For clients only		
				$fields_arr = array('group_id', 'authentication', 'salt', 'is_verified', 'parent_id', 'domain_id', 'image_path', 'login_as', 'department_access', 'client_type', 'password_auth', 'group_type', 'description', 'display_order', 'debit', 'is_enable', 'is_enabled', 'domain', 'language_id', 'timezone', 'timezone_dst', 'theme', 'send_mail', 'group_credit', 'timezone_name', 'office_contact_num', 'mobile_number', 'birthdate', 'office_phone');
			elseif($report_type==14)//For tickets only
				$fields_arr = array('user_replied', 'status_id', 'sdue_time', 'rdue_time', 'ticket_priority', 'ticket_status', 'ticket_type', 'initials', 'salt', 'authentication', 'is_spam', 'is_banned', 'group_id', 'is_approved', 'language', 'office_name', 'parent_id', 'department_id', 'priority_id', 'type_id', 'category_id', 'subcategory_id', 'item_id', 'level_id', 'channel_id', 'client_id','domain_id');
				
            if(isset($report[0]) && is_array($report[0])) { 
                foreach($report[0] as $key=>$val){
					if( in_array($key, $fields_arr)) // these fields not req in csv
						continue;
							switch($key){ 
								case 'receive_date': 
									$key='ticket_entry';
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'office_name' : $key='Company name';
												   break;
								case 'office_email' : $key='Company email';
													  break;
								case 'office_address' : $key='Company address';
														break;
								case 'office_fax' : $key='Company fax';
														break;
								case 'office_website' : $key='Company website';
														break;
								case 'group_name' : $key='Organization name';
													break;
							}
						}	
					 fwrite($file,strtoupper( str_replace("_", " ", $key) )."\t"); // replace underscore with space & uppercase title
				}
                fwrite($file,"\n"); 
                for($i=0;$i<count($report);$i++) { 
                    foreach($report[$i] as $key=>$val) { 
						if( in_array($key, $fields_arr)) // these fields not req in csv
							continue;
							switch($key){ 
								case 'receive_date': 
									$val = format_datetime_rpt($val,$staff_id);	
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'gender': 
									$val= ($val == 0) ? 'Male' : 'Female';	
									break;	
								case 'is_spam': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;		
								case 'is_banned': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'is_approved': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'language': 
									$lang_data = $object_client->get_client_language($val);
									if($lang_data!=-1) $val = $lang_data['language_name'];
									else $val = '';
									break;
							}
						}elseif($report_type==14){//For tickets only
						
							$ticket_details = $report[$i];
							$due_time = $resolution_time = '';
							// due_time
							if($ticket_details['due_time'] <= 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3 && $ticket_details['sdue_time'] != 0) 
								$due_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['due_time'] > 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3) 
								$due_time = count_remain_time($ticket_details['due_time']); 
							else 
								$due_time = $vis_language['TXTUNDUE'];
								
							// resolution_time
							if($ticket_details['resolution_time'] <= 0 && $ticket_details['status_id'] != 3 && $ticket_details['rdue_time'] != 0) 
									$resolution_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['resolution_time'] > 0 && $ticket_details['status_id'] != 3) 
								$resolution_time = count_remain_time(($ticket_details['resolution_time']));
							elseif($ticket_details['rdue_time'] > 0 && $ticket_details['status_id'] == 3) 
								$resolution_time = count_remain_time(($ticket_details['modify_date'])-($ticket_details['creation_date']));								
							else 
								$resolution_time = $vis_language['TXTUNDUE'];	
					
							switch($key){ 
								case 'creation_date': 
									//
								case 'modify_date':	
									$val = format_datetime_rpt($val,$staff_id);
									break;
								case 'closing_time':	
									$val = format_datetime_rpt($val,$staff_id);
									break;
								case 'due_time':
									$val = $due_time;
									break;
								case 'resolution_time': 
									$val = $resolution_time;	
									break;	
							}
						}
						$val=str_replace (array("\r\n", "\n", "\r"), " ", $val);
                        if($val!='' && strpos($val, "\t")!=0) {
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,$val."\t");
                        }
                        else
						{	
							$search = "/\"/";
							if(substr($val,0,1)=='"' && (substr($val,0,-1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'"))
							{
								$val = '"'.preg_replace($search,'""',$val).'"';
							}
							else if((substr($val,0,1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'") && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',$val).'"';
							}
							else if(substr($val,0,1)=='"' && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',$val).'"';
							}
							else
							{
								$val = preg_replace($search,'""',$val);
							}
							
							//$val = stripslashes(stripslashes($val));
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,$val."\t");
						}
                    }
                    fwrite($file,"\n");
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
							$val=str_replace (array("\r\n", "\n", "\r"), " ", $val);
                            if($key!='' && strpos($key, "\t")!=0) {								
                                fwrite($file,$key."\t");
                            }
                            else fwrite($file,$key."\t");
                        }
                        fwrite($file,"\n");
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						$val=str_replace (array("\r\n", "\n", "\r"), " ", $val);
                        if($val!='' && strpos($val, "\t")!=0) {
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
                            fwrite($file,$val."\t");
                        }
                        else
						{	
							$search = "/\"/";
							if(substr($val,0,1)=='"' && (substr($val,0,-1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'"))
							{
								$val = '"'.preg_replace($search,'""',$val).'"';
							}
							else if((substr($val,0,1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'") && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',$val).'"';
							}
							else if(substr($val,0,1)=='"' && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',$val).'"';
							}
							else
							{
								$val = preg_replace($search,'""',$val);
							}
							
							//$val = stripslashes(stripslashes($val));
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,$val."\t");
						}
                    }
                    fwrite($file,"\n");
                }
            }
			fclose($file);
        }
        else return false;
    }
				
    function export_xlsx_old($report, $filename,$report_type,$config='') {
		global $vis_language;	
		$database=new class_database();
		global $s_filter, $s_report_type, $s_exportid , $s_email_id , $s_staff_id,$s_request_date,$s_department_id; 
        if($config == 1)$database=new class_database('mysql',1);
        else $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object_client=new class_client($database);
		$fields_arr = array();
        if(is_array($report)) {
		    $file = fopen('../downloads/'.$filename.'.xls','w+');
			
			if($report_type==15) //For clients only		
				$fields_arr = array('group_id', 'authentication', 'salt', 'is_verified', 'parent_id', 'domain_id', 'image_path', 'login_as', 'department_access', 'client_type', 'password_auth', 'group_type', 'description', 'display_order', 'debit', 'is_enable', 'is_enabled', 'domain', 'language_id', 'timezone', 'timezone_dst', 'theme', 'send_mail', 'group_credit', 'timezone_name', 'office_contact_num', 'mobile_number', 'birthdate', 'office_phone');
			elseif($report_type==14)//For tickets only
				$fields_arr = array('user_replied', 'status_id', 'sdue_time', 'rdue_time', 'ticket_priority', 'ticket_status', 'ticket_type', 'initials', 'salt', 'authentication', 'is_spam', 'is_banned', 'group_id', 'is_approved', 'language', 'office_name', 'parent_id', 'department_id', 'priority_id', 'type_id', 'category_id', 'subcategory_id', 'item_id', 'level_id', 'channel_id', 'client_id','domain_id');
				
            if(isset($report[0]) && is_array($report[0])) { 
                foreach($report[0] as $key=>$val){
					if( in_array($key, $fields_arr)) // these fields not req in csv
						continue;
							switch($key){ 
								case 'receive_date': 
									$key='ticket_entry';
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'office_name' : $key='Company name';
												   break;
								case 'office_email' : $key='Company email';
													  break;
								case 'office_address' : $key='Company address';
														break;
								case 'office_fax' : $key='Company fax';
														break;
								case 'office_website' : $key='Company website';
														break;
								case 'group_name' : $key='Organization name';
													break;
							}
						}	
					 fwrite($file,strtoupper( str_replace("_", " ", $key) )."\t"); // replace underscore with space & uppercase title
				}
                 fwrite($file,"\n"); 
                for($i=0;$i<count($report);$i++) { 
                    foreach($report[$i] as $key=>$val) { 
						if( in_array($key, $fields_arr)) // these fields not req in csv
							continue;
							switch($key){ 
								case 'receive_date': 
									$val = format_datetime($val);	
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'gender': 
									$val= ($val == 0) ? 'Male' : 'Female';	
									break;	
								case 'is_spam': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;		
								case 'is_banned': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'is_approved': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'language': 
									$lang_data = $object_client->get_client_language($val);
									if($lang_data!=-1) $val = $lang_data['language_name'];
									else $val = '';
									break;
							}
						}elseif($report_type==14){//For tickets only
						
							$ticket_details = $report[$i];
							$due_time = $resolution_time = '';
							// due_time
							if($ticket_details['due_time'] <= 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3 && $ticket_details['sdue_time'] != 0) 
								$due_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['due_time'] > 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3) 
								$due_time = count_remain_time($ticket_details['due_time']); 
							else 
								$due_time = $vis_language['TXTUNDUE'];
								
							// resolution_time
							if($ticket_details['resolve_time'] <= 0 && $ticket_details['status_id'] != 3 && $ticket_details['resolution_time'] != 0) 
									$resolution_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['resolve_time'] > 0 && $ticket_details['status_id'] != 3) 
								$resolution_time = count_remain_time(($ticket_details['resolve_time'])); 
							else 
								$resolution_time = $vis_language['TXTUNDUE'];	
					
							switch($key){ 
								case 'creation_date': 
									//
								case 'modify_date':	
									$val = format_datetime($val);
									break;
								case 'closing_time':	
									$val = format_datetime($val);
									break;
								case 'due_time':
									$val = $due_time;
									break;
								case 'resolution_time': 
									$val = $resolution_time;	
									break;	
							}
						}	
						$val=str_replace (array("\r\n", "\n", "\r"), " ", $val);
                        if($val!='' && strpos($val, "\t")!=0) {							 
                             fwrite($file,$val."\t");
                        }
                        else  fwrite($file,$val."\t");
                    }
                    fwrite($file,"\n");
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
							$val=str_replace (array("\r\n", "\n", "\r"), " ", $val);
                            if($key!='' && strpos($key, "\t")!=0) {								
                                fwrite($file,$key."\t");
                            }
                            else fwrite($file,$key."\t");  
                        }
                        fwrite($file,"\n");
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						$val=str_replace (array("\r\n", "\n", "\r"), " ", $val);
                        if($val!='' && strpos($val, "\t")!=0) {							 
                             fwrite($file,$val."\t");
                        }
                        else fwrite($file,$val."\t");
                    }
                    fwrite($file,"\n");
                }
            }fclose($file);
        }
        else return false;
    }
				
				
	function export_csv($report, $filename,$report_type,$config='',$staff_id='') {
		global $vis_language;			
		global $s_filter, $s_report_type, $s_exportid , $s_email_id , $s_staff_id,$s_request_date,$s_department_id; 
        if($config == 1)$database=new class_database('mysql',1);
        else $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object_client=new class_client($database);
		$fields_arr = array();
		
        if(is_array($report)) {
			$file = fopen('../downloads/'.$filename.'.csv','w+');
			if($report_type!=15)
		{	fwrite($file,$report['Report_title']."\n\n");}
			
			if($report_type==15) //For clients only		
				$fields_arr = array('group_id', 'authentication', 'salt', 'is_verified', 'parent_id', 'domain_id', 'image_path', 'login_as', 'department_access', 'client_type', 'password_auth', 'group_type', 'description', 'display_order', 'debit', 'is_enable', 'is_enabled', 'domain', 'language_id', 'timezone', 'timezone_dst', 'theme', 'send_mail', 'group_credit', 'timezone_name', 'office_contact_num', 'mobile_number', 'birthdate', 'office_phone');
			elseif($report_type==14)//For tickets only
				$fields_arr = array('user_replied', 'status_id', 'sdue_time', 'rdue_time', 'ticket_priority', 'ticket_status', 'ticket_type', 'initials', 'salt', 'authentication', 'is_spam', 'is_banned', 'group_id', 'is_approved', 'language', 'office_name', 'parent_id', 'department_id', 'priority_id', 'type_id', 'category_id', 'subcategory_id', 'item_id', 'level_id', 'channel_id', 'client_id','domain_id');
			
			$sum_of_labels = 0;
            if(isset($report[0]) && is_array($report[0])) {
				foreach($report[0] as $key=>$val){
					if( in_array($key, $fields_arr)) // these fields not req in csv
						continue;
								switch($key){ 
								case 'receive_date': 
								if($report_type==26)
									{$key='resolved_date';
								     break;}
								else
								{$key='ticket_entry';
							     break;}
							        
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'office_name' : $key='Company name';
												   break;
								case 'office_email' : $key='Company email';
													  break;
								case 'office_address' : $key='Company address';
														break;
								case 'office_fax' : $key='Company fax';
														break;
								case 'office_website' : $key='Company website';
														break;
								case 'group_name' : $key='Organization name';
													break;
							}
						}	
					fwrite($file,strtoupper( str_replace("_", " ", $key) ).','); // replace underscore with space & uppercase title					
				}
				fwrite($file,"\n");
				for($i=0;$i<count($report);$i++) {
					$m = 0;
                    foreach($report[$i] as $key=>$val) { 
						if( in_array($key, $fields_arr)) // these fields not req in csv
							continue;
							switch($key){ 
								case 'receive_date': 
									$val = format_datetime_rpt($val,$staff_id);	
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'gender': 
									$val= ($val == 0) ? 'Male' : 'Female';	
									break;	
								case 'is_spam': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;		
								case 'is_banned': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'is_approved': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'language': 
									$lang_data = $object_client->get_client_language($val);
									if($lang_data!=-1) $val = $lang_data['language_name'];
									else $val = '';
									break;
							}
						}elseif($report_type==14){//For tickets only
														$ticket_details = $report[$i];
							$due_time = $resolution_time = '';
							// due_time
							if($ticket_details['due_time'] <= 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3 && $ticket_details['sdue_time'] != 0) 
								$due_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['due_time'] > 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3) 
								$due_time = count_remain_time($ticket_details['due_time']); 
							else 
								$due_time = $vis_language['TXTUNDUE'];
								
							// resolution_time
							if($ticket_details['resolution_time'] <= 0 && $ticket_details['status_id'] != 3 && $ticket_details['rdue_time'] != 0) 
									$resolution_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['resolution_time'] > 0 && $ticket_details['status_id'] != 3) 
								$resolution_time = count_remain_time(($ticket_details['resolution_time'])); 
							elseif($ticket_details['rdue_time'] > 0 && $ticket_details['status_id'] == 3) 
								$resolution_time = count_remain_time(($ticket_details['modify_date'])-($ticket_details['creation_date']));
							else 
								$resolution_time = $vis_language['TXTUNDUE'];	
					
							switch($key){ 
								case 'creation_date': 
									//
								case 'modify_date':	
									$val = format_datetime_rpt($val,$staff_id);
									break;
								case 'closing_time':	
									$val = format_datetime_rpt($val,$staff_id);
									break;
								case 'due_time':
									$val = $due_time;
									break;
								case 'resolution_time': 
									$val = $resolution_time;	
									break;	
							}
						}
						//$val = stripslashes($val);
						if($val!='' && strpos($val, ',')!=0) {
							if(strpos($val, '"')!=0) {
								$val = str_replace('"','""',$val);
							}					
							$val = stripslashes($val);
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,'"'.$val.'",');
                        }
						else
						{	
							$search = "/\"/";
							if(substr($val,0,1)=='"' && (substr($val,0,-1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'"))
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							else if((substr($val,0,1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'") && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							else if(substr($val,0,1)=='"' && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							else
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							//$val = stripslashes(stripslashes($val));
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,$val.',');
						}											
					}
					fwrite($file,"\n");				
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
							if($key!='' && strpos($key, ',')!=0){
								fwrite($file,'"'.$key.'",');
                            }
                            else fwrite($file,$key.",");  
                        }
                        fwrite($file,"\n");
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						//$val = stripslashes($val);
						if($val!='' && strpos($val, ',')!=0){
							if(strpos($val, '"')!=0) {
								$val = str_replace('"','""',$val);
							}
							$val = stripslashes($val);
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,'"'.$val.'",');
                        }
						else
						{	
							$search = "/\"/";
							if(substr($val,0,1)=='"' && (substr($val,0,-1)!=preg_match("/^[a-zA-Z]$/",$val) || substr($val,0,-1)!="'"))
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							else if((substr($val,0,1)!=preg_match("/^[a-zA-Z]$/",$val)|| substr($val,0,-1)!="'") && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							else if(substr($val,0,1)=='"' && substr($val,0,-1)=='"')
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							else
							{
								$val = '"'.preg_replace($search,'""',trim($val)).'"';
							}
							//$val = stripslashes(stripslashes($val));
							if(strstr(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val),'??')){
								$val = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ', $val);
							}else if(strstr($val,'©')){
								$val = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $val);
							}else{
								$val = $val;
							}
							fwrite($file,$val.",");
						}
                    }
                    fwrite($file,"\n");
                }
            }
			fclose($file);
        }
        else return false;
    }
	
	function export_csv_old($report, $filename,$report_type,$config='') {
		global $vis_language;			
		global $s_filter, $s_report_type, $s_exportid , $s_email_id , $s_staff_id,$s_request_date,$s_department_id; 
        if($config == 1)$database=new class_database('mysql',1);
        else $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object_client=new class_client($database);
		$fields_arr = array();
        if(is_array($report)) {
		    $file = fopen('../downloads/'.$filename.'.csv','w+');
			
			if($report_type==15) //For clients only		
				$fields_arr = array('group_id', 'authentication', 'salt', 'is_verified', 'parent_id', 'domain_id', 'image_path', 'login_as', 'department_access', 'client_type', 'password_auth', 'group_type', 'description', 'display_order', 'debit', 'is_enable', 'is_enabled', 'domain', 'language_id', 'timezone', 'timezone_dst', 'theme', 'send_mail', 'group_credit', 'timezone_name', 'office_contact_num', 'mobile_number', 'birthdate', 'office_phone');
			elseif($report_type==14)//For tickets only
				$fields_arr = array('user_replied', 'status_id', 'sdue_time', 'rdue_time', 'ticket_priority', 'ticket_status', 'ticket_type', 'initials', 'salt', 'authentication', 'is_spam', 'is_banned', 'group_id', 'is_approved', 'language', 'office_name', 'parent_id', 'department_id', 'priority_id', 'type_id', 'category_id', 'subcategory_id', 'item_id', 'level_id', 'channel_id', 'client_id','domain_id');
				
            if(isset($report[0]) && is_array($report[0])) { 
                foreach($report[0] as $key=>$val){
					if( in_array($key, $fields_arr)) // these fields not req in csv
						continue;
								switch($key){ 
								case 'receive_date': 
								if($report_type==26)
									{$key='resolved_date';
								     break;}
								else
								{$key='ticket_entry';
							     break;}
							        
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'office_name' : $key='Company name';
												   break;
								case 'office_email' : $key='Company email';
													  break;
								case 'office_address' : $key='Company address';
														break;
								case 'office_fax' : $key='Company fax';
														break;
								case 'office_website' : $key='Company website';
														break;
								case 'group_name' : $key='Organization name';
													break;
							}
						}	
					 fwrite($file,strtoupper( str_replace("_", " ", $key) ).','); // replace underscore with space & uppercase title
				}
                 fwrite($file,"\n"); 
                for($i=0;$i<count($report);$i++) { 
                    foreach($report[$i] as $key=>$val) { 
						if( in_array($key, $fields_arr)) // these fields not req in csv
							continue;
							switch($key){ 
								case 'receive_date': 
									$val = format_datetime($val);	
									break;
							}
						if($report_type==15){//For clients only
							switch($key){ 
								case 'gender': 
									$val= ($val == 0) ? 'Male' : 'Female';	
									break;	
								case 'is_spam': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;		
								case 'is_banned': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'is_approved': 
									$val= ($val == 0) ? 'No' : 'Yes';	
									break;
								case 'language': 
									$lang_data = $object_client->get_client_language($val);
									if($lang_data!=-1) $val = $lang_data['language_name'];
									else $val = '';
									break;
							}
						}elseif($report_type==14){//For tickets only
						
							$ticket_details = $report[$i];
							$due_time = $resolution_time = '';
							// due_time
							if($ticket_details['due_time'] <= 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3 && $ticket_details['sdue_time'] != 0) 
								$due_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['due_time'] > 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3) 
								$due_time = count_remain_time($ticket_details['due_time']); 
							else 
								$due_time = $vis_language['TXTUNDUE'];
								
							// resolution_time
							if($ticket_details['resolve_time'] <= 0 && $ticket_details['status_id'] != 3 && $ticket_details['resolution_time'] != 0) 
									$resolution_time = $vis_language['TXTOVERDUE']; 
							elseif($ticket_details['resolve_time'] > 0 && $ticket_details['status_id'] != 3) 
								$resolution_time = count_remain_time(($ticket_details['resolve_time'])); 
							else 
								$resolution_time = $vis_language['TXTUNDUE'];	
					
							switch($key){ 
								case 'creation_date': 
									//
								case 'modify_date':	
									$val = format_datetime($val);
									break;
								case 'closing_time':	
									$val = format_datetime($val);
									break;
								case 'due_time':
									$val = $due_time;
									break;
								case 'resolution_time': 
									$val = $resolution_time;	
									break;	
							}
						}	
						
                        if($val!='' && strpos($val, ',')!=0) {
							 if(strpos($val, '"')!=0) {
								 $val = str_replace('"','""',$val);
							 }
                             fwrite($file,'"'.$val.'",');
                        }
                        else  fwrite($file,$val.',');
                    }
                    fwrite($file,"\n");
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
                            if($key!='' && strpos($key, ',')!=0) {
								
                               fwrite($file,'"'.$key.'",');
                            }
                            else fwrite($file,$key.",");  
                        }
                        fwrite($file,"\n");
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						
                        if($val!='' && strpos($val, ',')!=0) {
							 if(strpos($val, '"')!=0) {
								 $val = str_replace('"','""',$val);
							 }
                             fwrite($file,'"'.$val.'",');
                        }
                        else fwrite($file,$val.",");
                    }
                    fwrite($file,"\n");
                }
            }fclose($file);
        }
        else return false;
    }
    function export_depreciation_csv($report, $filename) {
        if(is_array($report)) {
            header("Content-Type: plain/text");
            header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
			global $vis_language;			
			$fields_arr = array('user_replied', 'status_id', 'sdue_time', 'rdue_time');
			
            if(isset($report[0]) && is_array($report[0])) {
                foreach($report[0] as $key=>$val){
					if( in_array($key, $fields_arr)) // these fields not req in csv
							continue; 
					echo strtoupper( str_replace("_", " ", $key) ).','; // replace underscore with space & uppercase title
				}
                echo "\n";
                for($i=0;$i<count($report);$i++) { 
					
					$ticket_details = $report[$i];
					$due_time = $resolution_time = '';
					// due_time
					if($ticket_details['due_time'] <= 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3 && $ticket_details['sdue_time'] != 0) 
						$due_time = $vis_language['TXTOVERDUE']; 
					elseif($ticket_details['due_time'] > 0 && $ticket_details['user_replied'] == 1 && $ticket_details['status_id'] != 3) 
						$due_time = count_remain_time($ticket_details['due_time']); 
					else 
						$due_time = $vis_language['TXTUNDUE'];
						
					// resolution_time
					if($ticket_details['resolution_time'] <= 0 && $ticket_details['status_id'] != 3 && $ticket_details['rdue_time'] != 0) 
							$resolution_time = $vis_language['TXTOVERDUE']; 
					elseif($ticket_details['resolution_time'] > 0 && $ticket_details['status_id'] != 3) 
						$resolution_time = count_remain_time(($ticket_details['resolution_time'])); 
					else 
						$resolution_time = $vis_language['TXTUNDUE'];					
					
                    foreach($report[$i] as $key=>$val) { 
						if( in_array($key, $fields_arr)) // these fields not req in csv
							continue;
						switch($key){ 
							case 'creation_date': 
							case 'modify_date':	$val = format_datetime($val);
												break;
							case 'due_time':	$val = $due_time;
												break;
							case 'resolution_time': $val = $resolution_time;	
													break;	
						}						
                        if($val!='' && strpos($val, ',')!=0) {
                            echo '"'.$val.'",';
                        }
                        else echo $val.",";
                    }
                    echo "\n";
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
                            if($key!='' && strpos($key, ',')!=0) {
                                echo '"'.$key.'",';
                            }
                            else echo $key.",";
                        }
                        echo "\n";
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						
                        if($val!='' && strpos($val, ',')!=0) {
                            echo '"'.$val.'",';
                        }
                        else echo $val.",";
                    }
                    echo "\n";
                }
            }
        }
        else return false;
    }
    
    function language_export_csv($report, $filename) {
        if(is_array($report)) {
            header("Content-Type: plain/text");
            header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
         
			global $vis_language;			
			
            if(isset($report[0]) && is_array($report[0])) {
                foreach($report[0] as $key=>$val){
					echo strtoupper( str_replace("_", " ", $key) ).','; // replace underscore with space & uppercase title
				}
                echo "\n";
                for($i=0;$i<count($report);$i++) { 
					$ticket_details = $report[$i];
                    foreach($report[$i] as $key=>$val) { 
                        if($val!='' && strpos($val, ',')!=0) {
                            echo '"'.$val.'",';
                        }
                        else echo $val.",";
                    }
                    echo "\n";
                }
            }
            else {
                $check=true;
                foreach($report as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
                            if($key!='' && strpos($key, ',')!=0) {
                                echo '"'.$key.'",';
                            }
                            else echo $key.",";
                        }
                        echo "\n";
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						
                        if($val!='' && strpos($val, ',')!=0) {
                            echo '"'.$val.'",';
                        }
                        else echo $val.",";
                    }
                    echo "\n";
                }
            }
        }
        else return false;
    }
	function assets_export_csv($assets, $filename,$result){
		if(is_array($assets)) {
            header("Content-Type: plain/text");
            header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
         
			global $vis_language;			
		   if(isset($assets[0]) && is_array($assets[0])) {
                foreach($assets[0] as $key=>$val){
				if($key!='assets_id'){
					echo strtoupper( str_replace("_", " ", $key) ).','; // replace underscore with space & uppercase title
					}
				}
                echo "\n";
                for($i=0;$i<count($assets);$i++) { 
				    foreach($assets[$i] as $key=>$val) { 
					if($key!='assets_id'){
					if($key=='assigned_on'  || $key=='installation_date' || $key=='expiry_date' || $key=='last_audit_date' || $key=='acquisition_date')
						echo date('m-d-Y H:i:s',$val).',';
                        elseif($val!='' && strpos($val, ',')!=0) {
                            echo '"'.$val.'",';
                        }
                        else echo strip_tags($val).",";
						}
                    }
                    echo "\n";
                }
            }
            else {
                $check=true;
                foreach($assets as $i) {
                    if($check) {
                        foreach($i as $key=>$val) {
						if($key!='assets_id'){
						    if($key!='' && strpos($key, ',')!=0) {
                                echo '"'.$key.'",';
                            }
                            else echo $key.",";
                        }
						}
                        echo "\n";
                        $check=false;
                    }
                    foreach($i as $key=>$val) {
						if($key=='assigned_on'  || $key=='installation_date' || $key=='expiry_date' || $key=='last_audit_date')
								echo date('m-d-Y H:i:s',$val).',';
                        elseif($val!='' && strpos($val, ',')!=0) {
                            echo '"'.$val.'",';
                        }
                        else echo strip_tags($val).",";
                    }
                    echo "\n";
                }
            }
        }
        else return false;
	}
}
?>
