<?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 billing {
    var $error;
    function get_invoices($operation) {
        global $vis_language;
           $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client=new class_client($database);
          if(VIS_LOCATION_AREA==1 && VIS_CLIENT_ID!=0 && VIS_CLIENT_ID!=-1) $clientfilter=VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
		else $clientfilter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
        list($client_info, $client_details)=$client->get_client($clientfilter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $client_details=$client_details[0];
         $is_manager=$client_details['is_manager'];
        if(VIS_LOCATION_AREA == 1 && (VIS_ACCESS_BILLING!=1 || VIS_MODULE_ACCESS_BILLING!=1 || VIS_HEAD_MENU_BILLING!=1)) //If contact dont have billing access
        {
            if(!defined('IS_WHMCS')) 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;
        }
        if(VIS_LOCATION_AREA==1 && VIS_CLIENT_ID!=0 && VIS_CLIENT_ID!=-1){ 
			if( $is_manager==0)
			$filter=VIS_TABLE_PREFIX.'invoice.client_id='.VIS_CLIENT_ID.' or '.VIS_TABLE_PREFIX.'client.parent_id='.VIS_CLIENT_ID;
			else 
			{if($operation['vis_status']==0)$filter=VIS_TABLE_PREFIX.'invoice.client_id='.VIS_CLIENT_ID.' or '.VIS_TABLE_PREFIX.'client.parent_id='.VIS_CLIENT_ID;
				else $filter=VIS_TABLE_PREFIX.'client.domain_id='.$client_details['domain_id'].' and '.VIS_TABLE_PREFIX.'client.group_id='.$client_details['group_id']; }
			}
        elseif(VIS_LOCATION_AREA!=1) {
            if(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id'])) $filter=('ticket_id='.$operation['vis_ticket_id']);
            if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id'])) $filter='('.(($filter != '')? $filter . ' and ' : '').VIS_TABLE_PREFIX.'invoice.client_id='.$operation['vis_client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$operation['vis_client_id'].')';
            if(isset($operation['vis_filter']) && $operation['vis_filter']!=''){
                $filter=$operation['vis_filter']; $filterSet = $operation['vis_filter'];
            }
            else if(isset($operation['vis_action']) && $operation['vis_action'] != ""){
                $action=explode("/", $operation['vis_action']);                
                if(isset($action[4]) && is_numeric($action[4])) {
                    $filter=' avis_client.client_id='.$action[4];
                    if($action[3]=='Unpaid') $filter.=' and invoice_status=0 ';
                    if($action[3]=='Overdue') $filter.=' and invoice_status=0 and due_date<unix_timestamp() ';
                    else if($action[3]=='New') $filter.=' and invoice_status=0 and due_date>unix_timestamp() ';
                    else if($action[3]=="Todays due") $filter.=' and invoice_status=0 and due_date>=1426896000 and due_date<=unix_timestamp()+86400) ';
                    else if($action[3]=="Todays paid") $filter.=' and invoice_status=1 and paid_date>=1426896000 and paid_date<=(1426896000+86400) ';
                }
            }
            
        }
        else return false;
        if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))
        {
			$operation['vis_invoice'] = 1;
			$clientId = $operation['vis_client_id'];
		}
      
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $billing=new class_billing($database);
        $staff=new class_staff($database);
        list($view_info, $view_details)=$staff->get_ticket_view(VIS_STAFF_ID, VIS_LOCATION_AREA);
        $title=(isset($operation['vis_title']) && $operation['vis_title']!='')?$operation['vis_title']:$vis_language['TXTINVOICES'];   
        if($title == '1')
        {
			$title = stripslashes($vis_language['TXTTODAYSDUE']);
		}
		elseif($title == '2')
        {
			$title = stripslashes($vis_language['TXTTODAYSPAID']);
		}
		else
		{
			$title = $title;
		} 
        if(VIS_LOCATION_AREA==1) $view_info['page_count']=10;
        $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
        $limit=($page*$view_info['page_count']).','.$view_info['page_count']; 	
        if($operation['vis_transaction']==1)
        $filter.=' and '.VIS_TABLE_PREFIX.'client.email='.'"'.$operation['vis_email_id'].'"';
        if(isset($operation['vis_invoice_search']) && $operation['vis_invoice_search']!='')
        {
			if($filter!='')
			$filter.=' and invoice_hash like "%'.$operation['vis_invoice_search'].'%"';
			else
			$filter.=' invoice_hash like "%'.$operation['vis_invoice_search'].'%"';
		}
       
      
		
        if($client_details['parent_id']!=0)
        $filter=VIS_TABLE_PREFIX.'invoice.client_id='.$client_details['parent_id'].' or '.VIS_TABLE_PREFIX.'client.parent_id='.$client_details['parent_id'];
      
        $invoices=$billing->get_invoice($filter, VIS_STAFF_ID, VIS_LOCATION_AREA, $limit,$is_manager);
        $invoice_count=($invoices!=-1)?count($invoices):0;
        $invoices_details_total=$billing->get_invoice($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($invoices_details_total!=-1)
        {
			$invoice_info['count']=count($invoices_details_total);	
		}
		else
		{
			$invoice_info['count']=0;
		}
		$view_info['page_count']=($invoice_info['count']==0)?0:ceil($invoice_info['count']/$view_info['page_count']); 
        $invoice_info['page']=$page;	
        if(VIS_LOCATION_AREA==0)
            echo get_xml($invoices, 'invoice');
        elseif(VIS_LOCATION_AREA==1) {
            global $vis_language;
            $header_title=$vis_language['TXTINVOICE'];
			 $breadcrumb['Home'] = 'index.php'; 
			 $breadcrumb[$vis_language['TXTINVOICE']] = ''; 
            $vis_title = $vis_language['TXTINVOICE'];
			 $vis_count = $invoice_info['count'];
            if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])){
				if($operation['vis_change']==1){
					include(VIS_PATH_TEMPLATE.'invoice_list.php');
				}
				else {				
					include(VIS_PATH_TEMPLATE.'header.php');
					include(VIS_PATH_TEMPLATE.'view_invoice.php');
					include(VIS_PATH_TEMPLATE.'footer.php');
				}				
			} else {
				include(VIS_PATH_TEMPLATE.'header.php');
				include(VIS_PATH_TEMPLATE.'view_invoice.php');
				include(VIS_PATH_TEMPLATE.'footer.php');
			}
        }
         elseif(VIS_LOCATION_AREA==2) {         
			if(isset($operation['vis_org_operation']) && $operation['vis_org_operation']=='ticket_details'){
				 include(VIS_PATH_TEMPLATE.'ticket_invoice_list.php');
			}
			else  include(VIS_PATH_TEMPLATE.'invoice_list.php');
		}
        else
            include(VIS_PATH_TEMPLATE.'invoice_list.php');
        
        $database->database_disconnect();
        return true;
    }

    function add_invoice($operation) {
        global $vis_language, $request_data;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $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.'billing.php');
        $billing_object=new class_billing($database);
        $invoice_info['vis_form_title']=$vis_language['TXTADDINVOICE'];
        $invoice_info['vis_opeartion']='create_invoice';
        $invoice_info['ticket_id']=(isset($operation['vis_ticket_id']) && is_numeric($operation['vis_ticket_id']))?$operation['vis_ticket_id']:0;
        $invoice_info['client_id']=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?$operation['vis_client_id']:0;
        $time=isset($request_data['vis_ticket_time_'][$invoice_info['ticket_id']])?$request_data['vis_ticket_time_'][$invoice_info['ticket_id']]:0;
        if($time!=0 && $invoice_info['ticket_id']!=0) {
            $amount=$object->get_bill_setting($invoice_info['ticket_id'], $time, VIS_STAFF_ID, VIS_LOCATION_AREA);
            $invoice_details[0]['amount']=$amount;
            $invoice_details[0]['tax']=$invoice_info['total']=$invoice_info['tax']='0.00';
            $invoice_details[0]['description']=$vis_language['MSGINVDESC1'].' '.(ceil($time/60)).' Min \n'.$vis_language['MSGINVDESC2'].' '.$amount;
        }
        else {
            $amount='0.00';
            $invoice_details[0]['amount']=$amount;
            $invoice_details[0]['tax']=$invoice_info['total']=$invoice_info['tax']='0.00';
            $invoice_details[0]['description']='';
        }

        list($clinf, $client)=$object->get_client('client_id='.$invoice_info['client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$domain_details=$ticket_object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$client[0]['domain_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
		$currency=$domain_details[0]['currency'];
        if($client==-1) return false;
        else $client=$client[0];
        if($client['parent_id']!=0){
            $credit=$object->get_client_credit('client_id='.$client['parent_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            $client['credit']=$credit['credit'];
        }
        $invoice_count=($invoices!=-1)?count($invoices):0;
        $time_track_details = $ticket_object->get_time_track_details('ticket_id='.$invoice_info['ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA); 
        $operation['vis_domain'] = $client['domain_id'];
        $tax_details=$billing_object->get_tax_setting($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $tax_details = $tax_details[0];
        list($tax_total,$tax_list)=$billing_object->get_tax('is_enabled=1 and domain_id='.$client['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,'');
        $database->database_disconnect();

        include(VIS_PATH_TEMPLATE.'invoice_new.php');
        return true;
    }

    function get_transactions($operation) {
        global $vis_language;
        if(!isset($operation['vis_client_id']) || !is_numeric($operation['vis_client_id'])) {
            echo $vis_language['MSGCLIENDIDMISS'];
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $transactions=$object->get_transactions('client_id='.$operation['vis_client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==0) echo get_xml($transactions, 'transaction');
        else return false;
        return true;
    }

    function get_transactions_list($operation) {
        global $vis_language;
        $filter=(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))?(VIS_TABLE_PREFIX.'balance.client_id='.$operation['vis_client_id']):'';
        if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))
        {
			$operation['vis_transaction'] = 1;
			$clientId = $operation['vis_client_id'];
		}
        $database=new class_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']; 
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $transactions=$object->get_transactions($filter, VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
        $transaction_count=($transactions!=-1)?count($transactions):0;
        $transactions_details_total=$object->get_transactions($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);   	
		if($transactions_details_total!=-1)
        {
			$transactions_total=count($transactions_details_total);
			$transaction_info['count']=$transactions_total;
		}
		else
		{
			$transaction_info['count']=0;
		}	
		$view_info['page_count']=($transaction_info['count']==0)?0:ceil($transaction_info['count']/$view_info['page_count']);
		$transaction_info['page']=$page;	
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'transactions.php');
        return true;
    }

    function create_balance($operation) {
        global $vis_language;
        if(isset($operation['vis_action'])) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
        $message='';
        if(!isset($data['vis_balance']) || trim($data['vis_balance'])=='' || !is_numeric($data['vis_balance'])) {
            echo (VIS_LOCATION_AREA==0)?'invalid amount':'<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
            return false;
        }
								else if(isset($data['vis_balance']) && is_numeric($data['vis_balance']) && $data['vis_balance'] <=0 && $data['vis_balance']!=0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVCRED'].'"); </script>';
            return false;
        }
        else if(!isset($data['vis_ticket']) || trim($data['vis_ticket'])=='' || !is_numeric($data['vis_ticket'])) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVCRED'].'"); </script>';
            return false;
        }
								else if(isset($data['vis_ticket']) && is_numeric($data['vis_ticket']) && $data['vis_ticket'] <=0 && $data['vis_ticket']!=0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVCRED'].'"); </script>';
            return false;
        }
        else if(!is_numeric($data['vis_client_id']) || $data['vis_client_id']==0) {
            echo (VIS_LOCATION_AREA==0)?$vis_language['MSGCLIENDIDMISS']:'<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCLIENDIDMISS'].'"); </script>';
            return false;
        }
        else if(!isset($data['vis_type']) && $data['vis_balance'] > $data['vis_available_credit'])
        {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGNOTSUFFICIENTCREDIT'].'"); </script>';
            return false;		
		}
		else if(isset($data['vis_remaining_bal']) && $data['vis_balance'] > $data['vis_remaining_bal'])
		{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGNOMORECREDITTHANTOTAL'].'"); </script>';
            return false;	
		}
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
         if($data['vis_balance']!=0 || $data['vis_ticket']!=0)
        {
			$ret=$object->add_balance($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
			if(isset($data['vis_invoice_id']) && is_numeric($data['vis_invoice_id'])) {
				$ret=$object->pay_invoice(array('vis_invoice_id'=>$data['vis_invoice_id'], 'vis_client_id'=>$data['vis_client_id'], 'vis_balance'=>$data['vis_balance'], 'vis_details'=>$data['vis_details'], 'payment_type' => 1,'manual_add_payment' => 1), VIS_STAFF_ID, VIS_LOCATION_AREA);
			}
		}
        if(VIS_LOCATION_AREA==0) {
            echo ($ret)?'success':'error';
        }
        else {
            if(!$ret) {
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
                return false;
            }
            else
            {
				if(isset($data['vis_invoice_id']) && $data['vis_invoice_id']!=0)
				{
					echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle");$("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$data["vis_invoice_id"].'"});</script>'; 
				}
				else
				{
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#short_summary").visExecution("load_area",{"vis_module":"client", "vis_operation":"display_short_summary", "vis_client_id": "'.$data['vis_client_id'].'"});$(".modal").modal("toggle");</script>';
				}
			}
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$setting_object=new class_setting($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
			$client_object=new class_client($database);
			$client_res=$client_object->get_client_list('client_id='.$data['vis_client_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
        }
        $database->database_disconnect();
        return true;
    }

    function add_balance($operation) {
        global $vis_language;
        $invoice['amount']='0.00';
        $invoice['details']='';
        $invoice['vis_invoice_id']=0;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $cl_object=new class_client($database);
        list($clinfo, $client)=$cl_object->get_client('client_id='.$operation['vis_client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($client!=-1) {
            $client=$client[0];
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$sett_obj=new class_setting($database);
			list($dpinf, $domain)=$sett_obj->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$client['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$domain=$domain[0];
	    }
        else return false;
        if(isset($operation['vis_invoice_id']) && is_numeric($operation['vis_invoice_id'])) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
            $object=new class_billing($database);
            $invoice_det=$object->get_invoice('invoice_id='.$operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            if($invoice_det!=-1) {
                $invoice['vis_invoice_id']=$operation['vis_invoice_id'];
                $invoice['available_credit'] = $invoice_det[0]['credit'];		
				$invoice['amount']=(($invoice_det[0]['balance'])>$invoice_det[0]['credit'])?$invoice_det[0]['credit']:($invoice_det[0]['balance']);
                $invoice['details']=$vis_language['MSGBALFORINV'].$invoice_det[0]['invoice_hash'];
            }
            $database->database_disconnect();
        }
        include(VIS_PATH_TEMPLATE.'balance_form.php');
        return true;
    }

    function edit_invoice($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_invoice_id']) && is_numeric($operation['vis_invoice_id'])) $invoice_id=$operation['vis_invoice_id'];
        else {            
                $spliter=(strstr($operation['vis_action'], '/'))?'/':',';
                $action=explode($spliter, $operation['vis_action']);
                if(isset($action[4]) && $action[4]!='' && is_numeric($action[4])) {
                    $invoice_id=$operation['vis_invoice_id']=$action[4];
                }
                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.'setting.php');
        $objectSetting=new class_setting($database);
        list($etemplate_info, $etemplates)=$objectSetting->get_etemplate('is_enabled=1 and default_id = 9 and language=1 ', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);        
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $filter = 'domain_id='.VIS_DOMAIN;
        $paymentMethod = $object->get_gateway_method_details($filter);
        $filter='invoice_id='.$invoice_id;
        if(VIS_LOCATION_AREA==1) {
            if(VIS_CLIENT_ID==0 || VIS_CLIENT_ID==-1) return false;
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client=new class_client($database);
            $clientfilter=VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
            list($client_info, $client_details)=$client->get_client($clientfilter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $client_details=$client_details[0];
            $is_manager=$client_details['is_manager'];
            if($client_details['parent_id']!=0 && VIS_ACCESS_BILLING==1)
                $filter='('.VIS_TABLE_PREFIX.'invoice.client_id='.$client_details['parent_id'].' or '.VIS_TABLE_PREFIX.'client.parent_id='.$client_details['parent_id'].') and '.$filter;
            else{ if($is_manager!=1) $filter='('.VIS_TABLE_PREFIX.'invoice.client_id='.VIS_CLIENT_ID.' or '.VIS_TABLE_PREFIX.'client.parent_id='.VIS_CLIENT_ID.') and '.$filter;
				else  $filter='('.VIS_TABLE_PREFIX.'client.domain_id='.$client_details['domain_id'].' and '.VIS_TABLE_PREFIX.'client.group_id='.$client_details['group_id'].') and '.$filter;}
            if(isset($operation['vis_gateway']) && $operation['vis_gateway'] == 2) $gateway = 'authorize.net';
            else if((isset($operation['vis_gateway']) && $operation['vis_gateway'] == 3) || (isset($operation['stripeToken']) && $operation['stripeToken']!='')) $gateway = 'stripe';
            else $gateway = 'paypal_email';
            if(count($paymentMethod)==1 && !isset($operation['vis_gateway']) && $paymentMethod[0]['gateway_name']=='stripe') $gateway='stripe';
            $billing_info=$object->get_domain_setting('domain_id='.VIS_DOMAIN, $gateway, VIS_CLIENT_ID, VIS_LOCATION_AREA);
        }
        $invoice_info=$object->get_invoice($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($invoice_info==-1){
            if(VIS_LOCATION_AREA == 1)
            {
                if(!defined('IS_WHMCS')) 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;
            }
        }
        
        $invoice_details=$object->get_details($invoice_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $taxIdsArr =array();
        for($i=0;$i<count($invoice_details);$i++){
        $taxIds =array();
        $invtax_mapdetails=$object->get_tax_mapping_details($invoice_details[$i]['invoice_detail_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        for($j=0;$j<count($invtax_mapdetails);$j++){
			$taxIds[] = $invtax_mapdetails[$j]['tax_id'];
		}
        $invoice_details[$i]['selected_tax']=$taxIds;
		}
        $invoice_info=$invoice_info[0];
		$transaction_info=$object->get_invoice_transactions('invoice_id='.$invoice_id.' and client_id='.$invoice_info['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
		$domain_details=$object->get_domain_details('module_id=5 and domain_id='.VIS_DOMAIN, VIS_STAFF_ID, VIS_LOCATION_AREA);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $cl_object=new class_client($database);
        list($clinfo, $client)=$cl_object->get_client('client_id='.$invoice_info['client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($client!=-1) $client=$client[0];
		list($dpinf, $domain)=$objectSetting->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$client['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if($domain!=-1) $domain=$domain[0];
		$dom['vis_domain'] = $client['domain_id'];
        $tax_details=$object->get_tax_setting($dom, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $tax_details = $tax_details[0];
        list($tax_total,$tax_list)=$object->get_tax('is_enabled=1 and domain_id='.$client['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,'');
	    if(isset($operation['vis_invoice_id']) && isset($operation['vis_gateway']))
        {		
            $authorize_net_data = "";
            if( $operation['vis_gateway'] == 2 ) // authorize.net gateway
            {
                require_once(VIS_PATH_PLUGINS . 'gatway/authorize_net/authorize_net.php');
                $api_login_id = $billing_info['field_name'];	// YOUR_API_LOGIN_ID
                $transaction_key = $billing_info['field_value']; // YOUR_TRANSACTION_KEY
                $amount = $invoice_info['total'];
                $fp_timestamp = time();
                $fp_sequence = "123" . time(); // Enter an invoice or other unique number.
                $fingerprint = AuthorizeNetSIM_Form::getFingerprint($api_login_id, $transaction_key, $amount, $fp_sequence, $fp_timestamp);
            }
            include(VIS_PATH_TEMPLATE.'gateway.php');
            return true;
        }else{
            if ($_POST && VIS_LOCATION_AREA==1) {
                require_once(VIS_PATH_PLUGINS . 'gatway/stripe/lib/Stripe.php');
                $totalamount=$invoice_info['total']*100;
                Stripe::setApiKey($billing_info['field_name']);
                $error = '';
                $success = '';
                try {                        
                    if(!isset($_POST['stripeToken'])) throw new Exception("The Stripe Token was not generated correctly");
                    $charge = Stripe_Charge::create(array("amount" => $totalamount, "currency" => VIS_DOMAIN_CURRENCY, "card" => $_POST['stripeToken'], "description" => $vis_language['MSGBALFORINV'].$invoice_info['invoice_hash']));
                    if ($charge->paid == true) {
                        $this->pay_invoice($operation);   
                    }else{
                        $error=$vis_language['MSGPAYMENTFAIL'];
                    }
                }  
                catch (Exception $e) {
                    $error = $e->getMessage();
                }
            }
        }
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==1) {
            $header_title=$vis_language['TXTINVOICE'];
			 $breadcrumb['Home'] = 'index.php'; 
			 $breadcrumb[$vis_language['TXTINVOICE']] = '?/billing/invoices'; 
			 $breadcrumb['#'.$invoice_info['invoice_hash']] = '';
			 $vis_title = $vis_language['TXTINVOICE'];
            include(VIS_PATH_TEMPLATE.'header.php');
            include(VIS_PATH_TEMPLATE.'invoice_details.php');
            include(VIS_PATH_TEMPLATE.'footer.php');
        }
        else {
            $invoice_info['count']=($invoice_details==-1)?0:count($invoice_details);
            include(VIS_PATH_TEMPLATE.'invoice_edit.php');
        }
        return true;
    }

    function update_invoice($operation) {
        global $vis_language;
        $operation['vis_current_operation']='client_details'; 
        $operation['vis_current_module']='client'; 
        $data=parse_form_array($operation['vis_action']);
        if(!is_numeric($data['vis_invoice_id']) || $data['vis_invoice_id']==0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVMISS'].'"); </script>';
            return false;
        }
        if(!is_numeric($data['vis_client_id']) || $data['vis_client_id']==0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCLIENDIDMISS'].'"); </script>';
            return false;
        }
        for($i=1;$i<$data['vis_desc_tot_count'];$i++) {
        if($data['vis_amount'.$i] !='' && !is_numeric($data['vis_amount'.$i])) {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
			return false;			
		}
		elseif((trim($data['vis_amount'.$i]=='') || trim($data['vis_invoice'.$i]=='')) || (trim($data['vis_amount'.$i]=='') && trim($data['vis_invoice'.$i]=='')))
		{
			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.'billing.php');
        $object=new class_billing($database);
        $ret=$object->update_invoice($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
        $filter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
        list($client_info, $client_details)=$object->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $client_details=$client_details[0];
        $client_name = $client_details['first_name']." ".$client_details['last_name'];
        $database->database_disconnect();
        if(!$ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        else if(isset($operation['vis_org_operation']) && $operation['vis_org_operation']=='ticket_details'){
			echo '<script>$(".modal").modal("hide");$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_operations",{"vis_module":"billing", "vis_operation":"get_invoices", "vis_ticket_id":'.$data['vis_ticket_id'].'});set_active_tab("invoices");</script>';
		}
        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_workpanel_div").visExecution("load_area",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$data["vis_invoice_id"].'"});';
        return true;
    }

    function create_invoice($operation) { 
	
        global $vis_language, $operation_hnd;
        if(isset($operation['vis_action'])) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
        $total_amount=0;
        for($i=0; $i <$data['vis_desc_count'] ;$i++)
        {
			$total_amount=$total_amount+$data['vis_amount'.$i];
			if(isset($data['vis_amount'.$i]) && !is_numeric($data['vis_amount'.$i])) {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
				return false;
			}
		}
        for($i=0; $i <$data['vis_desc_count'] ;$i++)
        {
			if(isset($data['vis_amount'.$i]) && !is_numeric($data['vis_amount'.$i])) {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
				return false;
			}
		}
        if(!is_numeric($data['vis_client_id']) || $data['vis_client_id']==0) {
            echo (VIS_LOCATION_AREA==0)?$vis_language['MSGCLIENDIDMISS']:'<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCLIENDIDMISS'].'"); </script>';
            return false;
        }
        if(!isset($data['vis_amount']) || trim($data['vis_amount'])=='') $amount=0;
        if(!isset($data['vis_ticket_id']) || !is_numeric($data['vis_ticket_id'])) $data['vis_ticket_id']=0;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $ret=$object->add_invoice($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        
        
        if($ret){
			    $operation['invoice_id']= $ret;
			    $invoice=$object->get_invoice('invoice_id='.$ret, VIS_STAFF_ID, VIS_LOCATION_AREA);
				$details=$object->get_details($ret, VIS_STAFF_ID, VIS_LOCATION_AREA);
				$operation['description']='<table width="100%"><tr><th align="left">'.$vis_language['TXTDATE'].'</th><th align="left">'.$vis_language['TXTDETAILS'].'</th><th align="left">'.$vis_language['TXTAMOUNT'].'</th></tr>';
				if($details!=-1) for($i=0;$i<count($details);$i++) {
					$operation['description'].='<tr><td width="200">'.format_date($details[$i]['entry_date']).'</td><td>'.$details[$i]['description'].'</td><td>'.$details[$i]['amount'].'</td></tr>';
				}
				$operation['description'].='</table>';
				include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
				$setting=new class_setting($database);
				list($dominfo, $domain)=$setting->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.VIS_DOMAIN, '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$currenty_symbol=array('USD'=>'$', 'AUD'=>'$', 'BRL'=>'R$', 'CAD'=>'$', 'CZK'=>'KÄ?', 'DKK'=>'kr', 'EUR'=>'â‚¬', 'HKD'=>'$', 'HUF'=>'Ft', 'ILS'=>'â‚ª', 'JPY'=>'Â¥', 'MYR'=>'RM', 'MXN'=>'$', 'NOK'=>'kr',
		'NZD'=> '$', 'PHP'=>'â‚±', 'PLN'=>'zÅ‚', 'GBP'=>'Â£', 'SGD'=>'$', 'SEK'=>'kr', 'CHF'=>'CHF', 'TWD' =>'NT$', 'THB' => 'à¸¿', 'TRY'=>'');
				$operation['username'] = $invoice[0]['first_name'].' '.$invoice[0]['last_name']; 
				$operation['invoice_hash'] = $invoice[0]['invoice_hash'];
				$operation['invoice_subtotal'] = $invoice[0]['subtotal'];
				$operation['invoice_amount'] =$invoice[0]['total'];
				$operation['invoice_date'] = format_date($invoice[0]['entry_date']);
				$operation['client_balance'] = $invoice[0]['credit'];
				$operation['currency'] =   $domain[0]['currency'];
				$operation['currency_symbol'] =  $currenty_symbol[$domain[0]['currency']];
				$operation['useremail'] =  $invoice[0]['user_name'];
				$operation['invoice_duedate'] = format_date($invoice[0]['due_date']);
				$operation['from_email']= $domain[0]['default_email'];
				$operation_hnd->operation_flow($operation, VIS_STAFF_ID, VIS_LOCATION_AREA, $database);
		}
				
		if(isset($operation['vis_org_operation']) && $operation['vis_org_operation']=='ticket_details')
			$unpaid_invoice_cnt=$object->get_unpaid_invoice_count('('.VIS_TABLE_PREFIX.'invoice.client_id='.$data['vis_client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$data['vis_client_id'].') and invoice_status=0 and ticket_id='.$data['vis_ticket_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(VIS_LOCATION_AREA==0) {
            echo $ret?'success':'error';
        }
        else {
            if(!$ret) {
                echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
                return false;
            }
            else if(isset($operation['vis_org_operation']) && $operation['vis_org_operation']=='ticket_details'){
				echo '<script>$(".modal").modal("hide");$("#vis_details_list_'.$data['vis_ticket_id'].'").visExecution("load_operations",{"vis_module":"billing", "vis_operation":"get_invoices", "vis_ticket_id":'.$data['vis_ticket_id'].'});$("#invoices").show();set_active_tab("invoices"); $("#vis_unpaid_invoice_count").text('.$unpaid_invoice_cnt['cnt'].'); </script>';
			}
			else {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");javascript:active_invoice_tab();$(".modal").modal("toggle");$("#short_summary").visExecution("load_area",{"vis_module":"client", "vis_operation":"display_short_summary", "vis_client_id": "'.$data['vis_client_id'].'"});</script>';	
			}
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
			$client_object=new class_client($database);
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
			$setting_object=new class_setting($database);
			$client_res=$client_object->get_client_list('client_id='.$operation['vis_client_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
			$name=((isset($client_res[0]['first_name']) && $client_res[0]['first_name']!='') || (isset($client_res[0]['last_name']) && $client_res[0]['last_name']!=''))?$client_res[0]['first_name']." ".$client_res[0]['last_name']:"";
			$email=(isset($client_res[0]['email']) && $client_res[0]['email']!='')? "( ".$client_res[0]['email']." ) ":"";
			$activity_log=$setting_object->add_staff_activity_log("Added invoice of amount ".$total_amount." to client ".$name.$email, VIS_STAFF_ID,11,VIS_LOCATION_AREA);
			$database->database_disconnect();
			
        }
        return $ret;
    }

    function quick_view($operation) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $setting_object=new class_ticket($database);
        $domains=$setting_object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $domain=(isset($operation['vis_domain_id']) && is_numeric($operation['vis_domain_id']))?$operation['vis_domain_id']:$domains[0]['domain_id'];
        $object=new class_billing($database);
        $invoice=$object->get_invoice_counts('domain_id='.$domain, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $income=$object->get_income_counts('domain_id='.$domain, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $orders=$object->get_orders( VIS_TABLE_PREFIX . 'order.entry_date!="" and FROM_UNIXTIME( '.  VIS_TABLE_PREFIX . 'order.entry_date, "%Y")='.date("Y"), VIS_STAFF_ID, VIS_LOCATION_AREA, '');
        $transaction=$object->get_transactions('entry_date!="" and WEEKOFYEAR(from_unixtime(entry_date))=WEEKOFYEAR(NOW()) and FROM_UNIXTIME(entry_date, "%Y")='.date("Y"), VIS_STAFF_ID, VIS_LOCATION_AREA, '');
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'billing_quickview.php');
        return true;
    }

    function get_delete_invoice($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELETEINVOICE'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			$vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';
			$message_info['vis_event'] = "$(this).visExecution('submit_form', {'vis_module':'billing', 'vis_operation':'delete_invoice', 'vis_form':'vis_invoice_list_form','vis_page':'".$vis_page."','vis_org_operation':(($('#invoice_listing').length)?'invoice_details':(($('#short_summary').length)?'client_details':'ticket_details'))})";
		}
		else
		{
			$message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'billing', 'vis_operation':'delete_invoice', 'vis_invoice_id':".$operation['vis_invoice_id'].",'vis_client_id':".$operation['vis_client_id'].",'vis_ticket_id':".$operation['vis_ticket_id'].", 'vis_org_operation':(($('#invoice_listing').length)?'invoice_details':(($('#short_summary').length)?'client_details':'ticket_details'))});";
        }
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_invoice($operation) {
        global $vis_language;
        $database = new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
		$objectClient=new class_client($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
		$object = new class_billing($database);
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			 $options=parse_form_array($operation['vis_action']);
			 if($options['vis_client_id']!='' && $options['vis_client_id']!=0 && $options['vis_ticket_id']==0)
			 {
				 $operation['vis_client_id'] = $options['vis_client_id'];
				 $operation['vis_org_operation']='client_details';
			 }
			 elseif($options['vis_ticket_id']!=0 && $options['vis_client_id']!=0 && $options['vis_client_id']!='' && $options['vis_ticket_id']!='')
			 {
				 $operation['vis_client_id'] = $options['vis_client_id'];
				 $operation['vis_ticket_id'] = $options['vis_ticket_id'];
				 $operation['vis_org_operation']='ticket_details';
			 }
			 else
			 {
		
			 }
			 foreach($options as $data=>$value) if(preg_match('/vis_global_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
			 $invoiceIds = implode(",",$list_chk);
			 $result = $object->delete_invoice('', VIS_STAFF_ID, VIS_LOCATION_AREA,$invoiceIds);
		}
		else
		{
			$operation['vis_current_operation']='client_details'; 
			$operation['vis_current_module']='client'; 
			$filter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
			
			list($client_info, $client_details)=$objectClient->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			$client_details=$client_details[0];
			$client_name = $client_details['first_name']." ".$client_details['last_name'];
			
			$filter='('.VIS_TABLE_PREFIX.'invoice.client_id='.$operation['vis_client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$operation['vis_client_id'].')';
			$invoices=$object->get_invoice($filter, VIS_STAFF_ID, VIS_LOCATION_AREA,'');
			$no_invoice=count($invoices);
			$result = $object->delete_invoice($operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,'');
		}
		$database->database_disconnect();
        if($result){
			if(isset($operation['vis_org_operation']) && $operation['vis_org_operation']=='client_details')
			{
				if($no_invoice==1)
				{
					echo '<script>$("li#invoice").css("display","none");	</script>';
					echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#summary").addClass("active");$("#vis_details_list").visExecution("load_operations",{"vis_module":"client", "vis_operation":"get_summary", "vis_action":"details", "vis_client_id":'.$operation['vis_client_id'].'});</script>';
			    }
			    else
			    {
					echo '<script>$("#vis_global_msg_div").visInterface("load_global_message","' .$vis_language['MSGSUCCOPRT'].'");$("#vis_details_list").visExecution("load_operations",{"vis_module":"billing", "vis_operation":"get_invoices", "vis_client_id":"'.$operation['vis_client_id'].'"});</script>';
				}
			}
			else if(isset($operation['vis_org_operation']) && $operation['vis_org_operation']=='ticket_details')	
			{	
				echo '<script>$("#vis_global_msg_div").visInterface("load_global_message","' .$vis_language['MSGSUCCOPRT'].'");$("#vis_details_list_'.$operation['vis_ticket_id'].'").visExecution("load_operations", {"vis_module":"billing", "vis_operation":"get_invoices", "vis_ticket_id":"'.$operation['vis_ticket_id'].'", "vis_client_id":"'.$operation['vis_client_id'].'"});</script>';
			}
			else
			{
				$operation['vis_client_id'] = $operation['vis_invoice_id'] = $operation['vis_ticket_id'] = '';
				echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_module","'.$vis_language['TXTINVOICES'].'",{"vis_module":"billing", "vis_operation":"get_invoices", "vis_client_id":""});</script>';
			}
		}
        else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); $("#vis_note_delete_form").dialog("close"); </script>';
        return $result;
    }

    function send_invoice($operation) {
        global $vis_language;
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $mail=new class_mail($database);
        $billing=new class_billing($database);
        $setting=new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			 $options=parse_form_array($operation['vis_action']);
			 foreach($options as $data=>$value) if(preg_match('/vis_global_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
			 foreach($list_chk as $invoiceId)
			 {
				$invoice=$billing->get_invoice('invoice_id='.$invoiceId, VIS_STAFF_ID, VIS_LOCATION_AREA);
				$details=$billing->get_details($invoiceId, VIS_STAFF_ID, VIS_LOCATION_AREA);
				$description='<table width="100%"><tr><th align="left">'.$vis_language['TXTDATE'].'</th><th align="left">'.$vis_language['TXTDETAILS'].'</th><th align="left">'.$vis_language['TXTAMOUNT'].'</th></tr>';
				if($details!=-1) for($i=0;$i<count($details);$i++) {
					$description.='<tr><td width="200">'.format_date($details[$i]['entry_date']).'</td><td>'.$details[$i]['description'].'</td><td>'.$details[$i]['amount'].'</td></tr>';
				}
				$description.='</table>';
				$emsetting=$setting->get_settings('title="vis_etemplate_map" and domain_id='.$invoice[0]['domain_id'], $userid, $user);
				$template_map_a=($emsetting==-1)?'1,2,3,4,5,6,9,10,11,12,18,17,19':$emsetting[0]['content'];
				$template_map=explode(',', $template_map_a);
				list($client_info, $client_details)=$client_object->get_client(VIS_TABLE_PREFIX.'client.client_id='.$invoice[0]['client_id'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($template_map[6]!=0){
					list($tmpinfo, $template)=$setting->get_etemplate('is_enabled=1 and (default_id='.$template_map[6].' or parent_id= '.$template_map[6].' or etemplate_id='.$template_map[6].') and language='.$client_details[0]['language'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					if(empty($template) || $template==-1)
					{
						list($tmpinfo, $template)=$setting->get_etemplate('is_enabled=1 and (default_id='.$template_map[6].' or parent_id= '.$template_map[6].' or etemplate_id='.$template_map[6].') and language=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
					}
				} else $template=-1;
				list($dominfo, $domain)=$setting->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$invoice[0]['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				if($template==-1 || $domain==-1) {
					if(VIS_LOCATION_AREA==2) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
					return false;
				}
				$subject=$template[0]['subject'];
				$body=$template[0]['content'];
			    $invoiceLink = $domain[0]['domain_url'].'/index.php?/billing/edit-invoice/'.$invoice[0]['invoice_hash'].'/'.$invoice[0]['invoice_id'];
				$currenty_symbol=array('USD'=>'$', 'AUD'=>'$', 'BRL'=>'R$', 'CAD'=>'$', 'CZK'=>'KÄ?', 'DKK'=>'kr', 'EUR'=>'â‚¬', 'HKD'=>'$', 'HUF'=>'Ft', 'ILS'=>'â‚ª', 'JPY'=>'Â¥', 'MYR'=>'RM', 'MXN'=>'$', 'NOK'=>'kr',
		'NZD'=> '$', 'PHP'=>'â‚±', 'PLN'=>'zÅ‚', 'GBP'=>'Â£', 'SGD'=>'$', 'SEK'=>'kr', 'CHF'=>'CHF', 'TWD' =>'NT$', 'THB' => 'à¸¿', 'TRY'=>'');
				$pattarns=array('/{username}/', '/{invoice_hash}/', '/{invoice_subtotal}/', '/{invoice_amount}/','/{invoice_date}/','/{client_balance}/', '/{description}/', '/{currency}/', '/{currency_symbol}/', '/{useremail}/', '/{password}/', '/{invoice_duedate}/','/{invoice_link}/');
                $replace=array($invoice[0]['first_name'].' '.$invoice[0]['last_name'], $invoice[0]['invoice_hash'], $invoice[0]['subtotal'], $invoice[0]['total'], format_date($invoice[0]['entry_date']), $invoice[0]['credit'], $description, $domain[0]['currency'], $currenty_symbol[$domain[0]['currency']], $invoice[0]['user_name'], base64_decode($invoice[0]['authentication']),format_date($invoice[0]['due_date']),$invoiceLink);
				$body=preg_replace($pattarns,$replace,$body);
				$result=$mail->send_mail(0, $invoice[0]['domain_id'], $domain[0]['domain_name'].'<'.$domain[0]['default_email'].'>', $invoice[0]['email'], $subject, $body, '', '', '', array());
				 
			 }
		}
		else
		{
			$invoice=$billing->get_invoice('invoice_id='.$operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			$details=$billing->get_details($operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
			$description='<table width="100%"><tr><th align="left">'.$vis_language['TXTDATE'].'</th><th align="left">'.$vis_language['TXTDETAILS'].'</th><th align="left">'.$vis_language['TXTAMOUNT'].'</th></tr>';
			if($details!=-1) for($i=0;$i<count($details);$i++) {
				$description.='<tr><td width="200">'.format_date($details[$i]['entry_date']).'</td><td>'.$details[$i]['description'].'</td><td>'.$details[$i]['amount'].'</td></tr>';
			}
			$description.='</table>';
			$emsetting=$setting->get_settings('title="vis_etemplate_map" and domain_id='.$invoice[0]['domain_id'], $userid, $user);
			$template_map_a=($emsetting==-1)?'1,2,3,4,5,6,9,10,11,12,18,17,19':$emsetting[0]['content'];
			$template_map=explode(',', $template_map_a);
			list($client_info, $client_details)=$client_object->get_client(VIS_TABLE_PREFIX.'client.client_id='.$invoice[0]['client_id'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($template_map[6]!=0){
				list($tmpinfo, $template)=$setting->get_etemplate('is_enabled=1 and (default_id='.$template_map[6].' or parent_id= '.$template_map[6].' or etemplate_id='.$template_map[6].') and language='.$client_details[0]['language'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				if(empty($template) || $template==-1)
				{
					list($tmpinfo, $template)=$setting->get_etemplate('is_enabled=1 and (default_id='.$template_map[6].' or parent_id= '.$template_map[6].' or etemplate_id='.$template_map[6].') and language=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
				}
			} else $template=-1;
			list($dominfo, $domain)=$setting->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$invoice[0]['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
			if($template==-1 || $domain==-1) {
				if(VIS_LOCATION_AREA==2) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
				return false;
			}
			$invoiceLink = $domain[0]['domain_url'].'/index.php?/billing/edit-invoice/'.$invoice[0]['invoice_hash'].'/'.$invoice[0]['invoice_id'];
			$subject=$template[0]['subject'];
			$body=$template[0]['content'];
			$currenty_symbol=array('USD'=>'$', 'AUD'=>'$', 'BRL'=>'R$', 'CAD'=>'$', 'CZK'=>'KÄ?', 'DKK'=>'kr', 'EUR'=>'â‚¬', 'HKD'=>'$', 'HUF'=>'Ft', 'ILS'=>'â‚ª', 'JPY'=>'Â¥', 'MYR'=>'RM', 'MXN'=>'$', 'NOK'=>'kr',
	'NZD'=> '$', 'PHP'=>'â‚±', 'PLN'=>'zÅ‚', 'GBP'=>'Â£', 'SGD'=>'$', 'SEK'=>'kr', 'CHF'=>'CHF', 'TWD' =>'NT$', 'THB' => 'à¸¿', 'TRY'=>'');
			$pattarns=array('/{username}/', '/{invoice_hash}/', '/{invoice_subtotal}/', '/{invoice_amount}/','/{invoice_date}/','/{client_balance}/', '/{description}/', '/{currency}/', '/{currency_symbol}/', '/{useremail}/', '/{password}/', '/{invoice_duedate}/','/{invoice_link}/');
            $replace=array($invoice[0]['first_name'].' '.$invoice[0]['last_name'], $invoice[0]['invoice_hash'], $invoice[0]['subtotal'], $invoice[0]['total'], format_date($invoice[0]['entry_date']), $invoice[0]['credit'], $description, $domain[0]['currency'], $currenty_symbol[$domain[0]['currency']], $invoice[0]['user_name'], base64_decode($invoice[0]['authentication']),format_date($invoice[0]['due_date']),$invoiceLink);
			$body=preg_replace($pattarns,$replace,$body);
			$result=$mail->send_mail(0, $invoice[0]['domain_id'],  $domain[0]['domain_name'].'<'.$domain[0]['default_email'].'>', $invoice[0]['email'], $subject, $body, '', '', '', array());
		}
		if(VIS_LOCATION_AREA==2) {
            if($result) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");
$("input[type=checkbox]:checked").prop("checked",false);</script>';
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        }
        return $result;
    }

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

    function edit_transaction($operation) {
        global $vis_language;
        if(isset($operation['vis_transaction_id']) && is_numeric($operation['vis_transaction_id'])) $invoice_id=$operation['vis_transaction_id'];
        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.'billing.php');
        $object=new class_billing($database);
        $transaction_info=$object->get_transactions('balance_id='.$invoice_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($transaction_info!=-1) $transaction_info=$transaction_info[0];
        include(VIS_PATH_TEMPLATE.'transaction_edit.php');
        return true;
    }

    function update_balance($operation) {
        global $vis_language;
        $operation['vis_current_operation']='client_details'; 
        $operation['vis_current_module']='client'; 
        if(isset($operation['vis_action'])) $data=parse_form_array($operation['vis_action']);
        else $data=$operation;
        $message='';
        if(!isset($data['vis_balance']) || trim($data['vis_balance'])=='' || !is_numeric($data['vis_balance'])) {
            echo (VIS_LOCATION_AREA==0)?'invalid amount':'<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVLAIDAMT'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
        $filter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
        list($client_info, $client_details)=$object->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $client_details=$client_details[0];
        $client_name = $client_details['first_name']." ".$client_details['last_name'];
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $ret=$object->update_balance($data, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==0) {
            echo ($ret)?'success':'error';
        }
        else {
            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").visExecution("load_operations",{"vis_module":"billing", "vis_operation":"get_transactions_list", "vis_client_id":"'.$client_details['client_id'].'", "vis_headerd":true}); $(".modal").modal("toggle");</script>';
        }
        return true;
    }

    function get_delete_transaction($operation) {
        global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELTRANSACTION'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			$vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';
			$message_info['vis_event'] = "$(this).visExecution('submit_form', {'vis_module':'billing', 'vis_operation':'delete_transaction', 'vis_form':'vis_transaction_list_form','vis_page':'".$vis_page."','vis_org_operation':(($('#short_summary').length)?'client_details':'transaction')})";
		}
		else
		{        
			$message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'billing', 'vis_operation':'delete_transaction', 'vis_transaction_id':".$operation['vis_transaction_id'].", 'vis_client_id':".$operation['vis_client_id'].",'vis_invoice_id':".$operation['vis_invoice_id'].",'vis_org_operation':(($('#short_summary').length)?'client_details':'transaction')});";
		}
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
    }

    function delete_transaction($operation) {
        global $vis_language;
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object = new class_billing($database);
        
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			 $options=parse_form_array($operation['vis_action']);
			 foreach($options as $data=>$value) if(preg_match('/vis_global_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
			 $transIds = implode(",",$list_chk);
			 $result = $object->delete_transaction('', VIS_STAFF_ID, VIS_LOCATION_AREA,$transIds);
			 $operation['vis_client_id'] = $options['vis_client_id'];
        }
        else
        {
			$filter=VIS_TABLE_PREFIX.'balance.client_id='.$operation['vis_client_id'];
			$transactions=$object->get_transactions($filter, VIS_STAFF_ID, VIS_LOCATION_AREA,'');
			$num_transactions=count($transactions);
			$result = $object->delete_transaction($operation['vis_transaction_id'], VIS_STAFF_ID, VIS_LOCATION_AREA,'');
		}
		$database->database_disconnect();
        if($result) 
        {
			if(isset($operation['vis_invoice_id']) && is_numeric($operation['vis_invoice_id']) && $operation['vis_invoice_id'] !=0 )
			{
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$operation["vis_invoice_id"].'"});</script>';
			}
			else if(isset($operation['vis_org_operation']) && $operation['vis_org_operation'] == 'client_details')
			{
				if($num_transactions==1)
				{
					echo '<script>$("li#transaction").css("display","none");	</script>';
					echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#summary").addClass("active");$("#vis_details_list").visExecution("load_operations",{"vis_module":"client", "vis_operation":"get_summary", "vis_action":"details", "vis_client_id":'.$operation['vis_client_id'].'});</script>';
			    }
			    else
			    {
					echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_details_list").visExecution("load_operations",{"vis_module":"billing", "vis_operation":"get_transactions_list", "vis_client_id":"'.$operation['vis_client_id'].'", "vis_headerd":true}); </script>';
				}
			}
			else
			{
				$operation['vis_client_id'] = $operation['vis_transaction_id']= "";
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_module","Transactions",{"vis_module":"billing", "vis_operation":"get_transactions_list","vis_client_id":"" }); </script>';
			}
		}
        else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); $("#vis_ticket_transaction_form").dialog("close"); </script>';
        return $result;
    }

    function pay_invoice($operation) {
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $bill_object=new class_billing($database);
        if(!isset($operation['vis_invoice_id'])) {
            $spliter=(strstr($operation['vis_action'], '/'))?'/':',';
            $action=explode($spliter, $operation['vis_action']);
            if(isset($action[3]) && $action[3]!='' && is_numeric($action[3])) {
                $operation['vis_invoice_id']=$action[3];
            }
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client=new class_client($database);
        $clientfilter=VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
        list($client_info, $client_details)=$client->get_client($clientfilter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $client_details=$client_details[0];
        if($client_details['parent_id']!=0 && VIS_ACCESS_BILLING==1) $invoice=$bill_object->get_invoice(VIS_TABLE_PREFIX.'invoice.client_id='.$client_details['parent_id'].' and invoice_id='.$operation['vis_invoice_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
        else $invoice=$bill_object->get_invoice(VIS_TABLE_PREFIX.'invoice.client_id='.VIS_CLIENT_ID.' and invoice_id='.$operation['vis_invoice_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
        if($invoice==-1) return false;
        $database->database_disconnect();
        if(isset($operation['x_invoice_num'])) // authorize.net
            return $this->process_auth_net_txn($invoice[0]);
        else if(isset($operation['stripeToken']) && $operation['stripeToken']!='')
            return $this->process_stripe_txn($invoice[0]);
        else
            return $this->payment_gateway($invoice[0], 1); // paypal
    }
      
    function payment_gateway($invoice, $gateway_id) {
        global $vis_language;
        if($gateway_id==0) {
            $environment="sandbox";
            require_once(VIS_PATH_PLUGINS.'gatway/class_paypal.php');

            //Check if we just returned inside the iframe.  If so, store payflow response and redirect parent window with javascript.
            /*if (isset($_POST['RESULT']) || isset($_GET['RESULT']) ) {
                $_SESSION['vis_paypalresponse']=array_merge($_GET, $_POST);
                echo '<script type="text/javascript">window.top.location.href = "'.script_url().'";</script>';
                exit(0);
           }*/

            //Check whether we stored a server response.  If so, print it out.
            //if(!empty($_SESSION['vis_paypalresponse'])) {
                $response= array_merge($_GET, $_POST);
                //unset($_SESSION['vis_paypalresponse']);
                $success=(isset($response['RESULT']) && $response['RESULT']==0);
                if($success) {
                    echo "<span style='font-family:sans-serif;font-weight:bold;'>Transaction approved! Thank you for your order.</span>";
                    $database = new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
                    $bill_object=new class_billing($database);
                    $invoice_details['vis_balance']=$response['AMT'];
                    $invoice_details['vis_client_id']=VIS_CLIENT_ID;
                    $invoice_details['vis_details']=$response['PNREF'];
                    $invoice_details['vis_invoice_id']=$invoice['invoice_id'];
                    $invoice_details['vis_invoice_hash']=$invoice['invoice_hash'];
                    $invoice_details['payment_type']=1;
                    $bill_object->add_balance($invoice_details, VIS_CLIENT_ID, VIS_LOCATION_AREA);
                    $invoice=$bill_object->pay_invoice(array('vis_invoice_id'=>$invoice['invoice_id'], 'vis_client_id'=>VIS_CLIENT_ID, 'vis_balance'=>$response['AMT'], 'payment_type' => 1), VIS_CLIENT_ID, VIS_LOCATION_AREA);
                    $bill_object->update_gateway_log( 1, $invoice_details['vis_invoice_hash'] );
                    $database->database_disconnect();
                    header('Location: index.php?vis_module=billing&vis_operation=get_invoices');
                    exit;
                    //return $this->get_invoices($invoice);
                }
                //else echo "<span style='font-family:sans-serif;'>Transaction failed! Please try again with another payment method.</span>";
                //echo "<pre>(server response follows)\n";
                //echo "</pre>";
                //return $this->get_invoices($invoice);
            //}

            //Build the Secure Token request
            $request = array(
                "PARTNER" => "PayPal",
                "VENDOR" => 'FJA3LXKAN3S3U', // "meetajayahire", //"palexanderpayflowtest",
                "USER" => 'FJA3LXKAN3S3U', // "meetajayahire", //"palexanderpayflowtestapionly",
                "PWD" => 'q1w2e3r4t5', //"q1w2e3r4t5y6Z", //"demopass123",
                "TRXTYPE" => "A",

                "AMT" => $invoice['total'],
                "CURRENCY" => "USD",
                "CREATESECURETOKEN" => "Y",
                "SECURETOKENID" => uniqid('VisSecTokenID-'), //Should be unique, never used before
                "RETURNURL" => script_url().'?vis_module=billing&vis_operation=pay_invoice&vis_invoice_id='.$invoice['invoice_id'],
                "CANCELURL" => script_url().'?vis_module=billing&vis_operation=pay_invoice&vis_invoice_id='.$invoice['invoice_id'],
                "ERRORURL" => script_url().'?vis_module=billing&vis_operation=pay_invoice&vis_invoice_id='.$invoice['invoice_id'],

                // In practice you'd collect billing and shipping information with your own form,
                // then request a secure token and display the payment iframe.
                // --> See page 7 of https://cms.paypal.com/cms_content/US/en_US/files/developer/Embedded_Checkout_Design_Guide.pdf
                // This example uses hardcoded values for simplicity.

                "BILLTOFIRSTNAME" => $invoice['first_name'],
                "BILLTOLASTNAME" => $invoice['last_name'],
                "BILLTOSTREET" => $invoice['temporary_address'],
                "BILLTOCITY" => $invoice['city'],
                "BILLTOSTATE" => $invoice['state'],
                "BILLTOZIP" => $invoice['zip_code'],
                "BILLTOCOUNTRY" => $invoice['country'],

                "SHIPTOFIRSTNAME" => $invoice['first_name'],
                "SHIPTOLASTNAME" => $invoice['last_name'],
                "SHIPTOSTREET" => $invoice['temporary_address'],
                "SHIPTOCITY" => $invoice['city'],
                "SHIPTOSTATE" => $invoice['state'],
                "SHIPTOZIP" => $invoice['zip_code'],
                "SHIPTOCOUNTRY" => $invoice['country']
            );

            //Run request and get the secure token response
            $response = run_payflow_call($request);

            if ($response['RESULT'] != 0) {
                pre($response, "Payflow call failed");
                exit(0);
            } else {
                $securetoken = $response['SECURETOKEN'];
                $securetokenid = $response['SECURETOKENID'];
            }

            if($environment == "sandbox" || $environment == "pilot") $mode='TEST'; else $mode='LIVE';
            echo "  <iframe src='https://payflowlink.paypal.com?SECURETOKEN=$securetoken&SECURETOKENID=$securetokenid&MODE=$mode' width='490' height='565' border='0' frameborder='0' scrolling='no' allowtransparency='true'>\n</iframe>";
        }
        elseif($gateway_id==1) {
            if(isset($_REQUEST['payment_status']) && $_REQUEST['payment_status']=='Completed') {
                $database = new class_database();
                include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
                $bill_object=new class_billing($database);
                $invoice_details['vis_balance']=$_REQUEST['payment_gross'];
                $invoice_details['vis_client_id']=VIS_CLIENT_ID;
                $invoice_details['vis_details']=$vis_language['MSGBALFORINV']."<a href='#/billing/edit_invoice/invoices/".$invoice['invoice_id']."'>".$invoice['invoice_hash']."</a>";
                $invoice_details['vis_transaction']=$_REQUEST['txn_id'];
                $invoice_details['vis_invoice_id']=$invoice['invoice_id'];
                $invoice_details['vis_invoice_hash']=$invoice['invoice_hash'];
                 $invoice_details['payment_type']=1;
                $bill_object->add_balance($invoice_details, VIS_CLIENT_ID, VIS_LOCATION_AREA);
                $invoice=$bill_object->pay_invoice(array('vis_invoice_id'=>$invoice['invoice_id'], 'vis_client_id'=>VIS_CLIENT_ID, 'vis_balance'=>$invoice_details['vis_balance'], 'payment_type' => 1), VIS_CLIENT_ID, VIS_LOCATION_AREA);
                $bill_object->update_gateway_log( 1, $invoice_details['vis_invoice_hash'] );
                $database->database_disconnect();
            }
            elseif(isset($_REQUEST['payment_status']) && $_REQUEST['payment_status']=='Pending') {
                $request=$_POST;
                $request['cmd']='_notify-validate';
                $ch = curl_init();
                $ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
                curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // must be stting to check
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
                curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
                // In wamp like environment where the root authority certificate doesn't comes in the bundle, you need
                // to download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
                // of the certificate as shown below.
                //curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) .'/../cacert.pem');
                if( !($res = curl_exec($ch)) ) {
                    header('Location: index.php?vis_module=billing&vis_operation=get_invoices');
                    echo ("Got error " . curl_error($ch) . " when processing IPN");
                    curl_close($ch);
                    exit;
                }
                curl_close($ch);

                if (strcmp ($res, "VERIFIED") == 0) {
                    $database = new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
                    $bill_object=new class_billing($database);
                    $invoice_details['vis_balance']=$_REQUEST['payment_gross'];
                    $invoice_details['vis_client_id']=VIS_CLIENT_ID;
                    $invoice_details['vis_details']=$vis_language['MSGBALFORINV']."<a href='#/billing/edit_invoice/invoices/".$invoice['invoice_id']."'>".$invoice['invoice_hash']."</a>";
                    $invoice_details['vis_transaction']=$_REQUEST['txn_id'];
                    $invoice_details['vis_invoice_id']=$invoice['invoice_id'];
                    $invoice_details['vis_invoice_hash']=$invoice['invoice_hash'];
                    $invoice_details['payment_type']=1;
                    $bill_object->add_balance($invoice_details, VIS_CLIENT_ID, VIS_LOCATION_AREA);
                    $invoice=$bill_object->pay_invoice(array('vis_invoice_id'=>$invoice['invoice_id'], 'vis_client_id'=>VIS_CLIENT_ID, 'vis_balance'=>$invoice_details['vis_balance'], 'payment_type' => 1), VIS_CLIENT_ID, VIS_LOCATION_AREA);
                    $bill_object->update_gateway_log( 1, $invoice_details['vis_invoice_hash'] );
                    $database->database_disconnect();
                }
            }
            header('Location: index.php?vis_module=billing&vis_operation=get_invoices');
            exit;
        }
    }

    function invoice_pdf($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_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			$operation['vis_invoice_id'] = $data[4];
		}
        if(isset($operation['vis_invoice_id']) && is_numeric($operation['vis_invoice_id'])) $invoice_id=$operation['vis_invoice_id'];
        else {
             if(VIS_LOCATION_AREA == 1){
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
            } 

            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.'billing.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_billing($database);
        $tkt_object=new class_ticket($database);
        $filter='invoice_id='.$invoice_id;
        if(VIS_LOCATION_AREA==1) {
            if(VIS_CLIENT_ID==0 || VIS_CLIENT_ID==-1) return false;
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client=new class_client($database);
            $clientfilter=VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
            list($client_info, $client_details)=$client->get_client($clientfilter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $client_details=$client_details[0];
            if($client_details['parent_id']!=0 && VIS_ACCESS_BILLING==1) $filter='('.VIS_TABLE_PREFIX.'invoice.client_id='.$client_details['parent_id'].' || '.VIS_TABLE_PREFIX.'client.parent_id='.$client_details['parent_id'].') and '.$filter;
            else  $filter='('.VIS_TABLE_PREFIX.'invoice.client_id='.VIS_CLIENT_ID.' || '.VIS_TABLE_PREFIX.'client.parent_id='.VIS_CLIENT_ID.') and '.$filter;
        }
        $invoice_info=$object->get_invoice($filter, VIS_CLIENT_ID, VIS_LOCATION_AREA);
        if($invoice_info==-1) {
              if(VIS_LOCATION_AREA == 1){
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
            } 
            return false;
        } 

        $invoice_details=$object->get_details($invoice_id, VIS_CLIENT_ID, VIS_LOCATION_AREA);
        $invoice_info=$invoice_info[0];
        $domain=$tkt_object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$invoice_info['domain_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
        $domain_details=$object->get_domain_details('module_id=5 and domain_id='.$invoice_info['domain_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
        if($domain==-1) return false;
        $domain=$domain[0];
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $cl_object=new class_client($database);
        list($clinfo, $client)=$cl_object->get_client('client_id='.$invoice_info['client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($client!=-1) $client=$client[0];
        $transaction_info=$object->get_invoice_transactions('invoice_id='.$invoice_id.' and client_id='.$invoice_info['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();

        if($invoice_info==-1 || $invoice_details==-1) {
            echo $vis_language['MSGERROPRT'];
            return false;
        }
        else {
            $html=get_include_contents(VIS_PATH_TEMPLATE.'invoice_export.php', array($invoice_info, $invoice_details, count($invoice_details), $domain,$domain_details,$client,$transaction_info));
            require_once(VIS_PATH_PLUGINS.'tcpdf/config/lang/eng.php');
            require_once(VIS_PATH_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->SetTitle("Invoice ID - #".$invoice_info['invoice_hash']);
            $pdf->SetSubject($invoice_info['invoice_hash']);
            $pdf->SetKeywords('Vision helpdesk, PDF, '.$invoice_info['invoice_hash']);
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
            $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
            //$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
            $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($invoice_info['ticket_hash'].'.pdf', 'I');
        }
        return true;
    }

    function update_invoice_status($operation) {
        global $vis_language;
        $operation['vis_current_operation']='client_details'; 
        $operation['vis_current_module']='client'; 
        if(!isset($operation['vis_update_id']) || !is_numeric($operation['vis_update_id'])) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINFOMISS'].'"); </script>';
            return false;
        }
        if(!is_numeric($operation['vis_invoice_id']) || $operation['vis_invoice_id']==0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVMISS'].'"); </script>';
            return false;
        }
        if(!is_numeric($operation['vis_client_id']) || $operation['vis_client_id']==0) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGCLIENDIDMISS'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $ret=$object->update_invoice_status($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
        $filter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
        list($client_info, $client_details)=$object->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $client_details=$client_details[0];
        $client_name = $client_details['first_name']." ".$client_details['last_name'];
        $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_workpanel_div").visExecution("load_module","'.$client_name.'/'.$client_details['client_id'].'",{"vis_module":"'.$operation['vis_current_module'].'", "vis_operation":"'.$operation['vis_current_operation'].'","vis_client_name":"'.$client_name.'","vis_client_id": "'.$client_details['client_id'].'"});</\script>';
        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$operation["vis_invoice_id"].'"});</script>';
        return true;
    }

    function products_list($operation) {
        global $vis_language;
        $database=new class_database();
        if(VIS_LOCATION_AREA == 1 && (VIS_ACCESS_BILLING!=1 || VIS_HEAD_MENU_BILLING!=1 || VIS_MODULE_ACCESS_BILLING!=1))
        {
            if(!defined('IS_WHMCS')) 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;
        }
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $filter=(VIS_LOCATION_AREA==1)?('is_enabled=1 and domain_id='.VIS_DOMAIN):'';
		$page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
		$limit=($page*10).',10';
		$setting_prod_module = '';
        $product=$object->get_product($filter, VIS_STAFF_ID, VIS_LOCATION_AREA, $setting_prod_module, $limit, ' where '.$filter);
        $total_prod=$product[0]['total'];
		$page_count=($total_prod==0)?0:ceil($total_prod/10);
		$prod_page=$page;
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==1) {
			$vis_title=$vis_language['TXTPURCHASE'];	
			$vis_count = $total_prod;
			$breadcrumb['Home'] = 'index.php'; 
			$breadcrumb[$vis_language['TXTPURCHASE']] = '';
			$product=$product[1];
			$header_title=$vis_language['TXTPURCHASE'];
            if(!IS_LOGIN) return false;
            if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])){
				if($operation['vis_change']==1){
				include(VIS_PATH_TEMPLATE.'product_list.php');
			}
			else {
				include(VIS_PATH_TEMPLATE.'header.php');
				include(VIS_PATH_TEMPLATE.'view_product.php');
				include(VIS_PATH_TEMPLATE.'footer.php');	
			}				
			} else {				
				include(VIS_PATH_TEMPLATE.'header.php');
				include(VIS_PATH_TEMPLATE.'view_product.php');
				include(VIS_PATH_TEMPLATE.'footer.php');
			}
        }
        else include(VIS_PATH_TEMPLATE.'product_list.php');
        return true;
    }

    function order_product($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_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			$operation['vis_product_id'] = $data[4];
		}
        if(!(isset($operation['vis_product_id']) && is_numeric($operation['vis_product_id']))){
            if(VIS_LOCATION_AREA == 1)
        {
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
         }
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $filter='is_enabled=1 and domain_id='.VIS_DOMAIN.' and product_id='.$operation['vis_product_id'];
        $product=$object->get_product($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(VIS_LOCATION_AREA == 1) $product=$product[1];
        if($product==-1) {
            if(VIS_LOCATION_AREA == 1)
        {
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
         }
        }

        if(!IS_LOGIN) return false;
        $product=$product[0];
        $dom['vis_domain'] = VIS_DOMAIN;
        $tax_details=$object->get_tax_setting($dom, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $tax_details = $tax_details[0];
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        $filter = VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
        $client_details=$client_object->get_client($filter,'0,1',1,'',VIS_STAFF_ID,VIS_LOCATION_AREA);
        $client_details = $client_details[1];
        $invoice_info['vis_opeartion']='create_invoice';
        $invoice_info['vis_ticket_id']=0;
        $invoice_info['vis_product_id']=$operation['vis_product_id'];
        $invoice_info['vis_client_id']=($client_details[0]['parent_id']==0)?VIS_CLIENT_ID:$client_details[0]['parent_id'];
        $invoice_info['vis_amount1']=$product['amount'];
        $invoice_info['vis_taxed1']=1;
        $invoice_info['vis_invoice1']=$product['title']."\n".$product['description'];
        $invoice_info['vis_ftaxed1']=1;
        $invoice_info['vis_staxed1']=1;
        $invoice_info['vis_tax_enabled']=$tax_details['tax_enabled'];
        $invoice_info['vis_tax1_id1']=$tax_details['tax1'];
        $invoice_info['vis_tax2_id1']=$tax_details['tax2'];

        $operation['vis_invoice_id']=$object->add_invoice($invoice_info, $invoice_info['vis_client_id'], VIS_LOCATION_AREA);
        $database->database_disconnect();
        if(VIS_LOCATION_AREA == 1) header("Location: ?/billing/edit-invoice/invoice/".$operation['vis_invoice_id']);
        else return $this->edit_invoice($operation);
    }

    function get_orders($operation) {
        if(VIS_LOCATION_AREA==1 && VIS_CLIENT_ID!=0 && VIS_CLIENT_ID!=-1) $filter=VIS_TABLE_PREFIX.'order.client_id='.VIS_CLIENT_ID.' or '.VIS_TABLE_PREFIX.'client.parent_id='.VIS_CLIENT_ID;
        elseif(VIS_LOCATION_AREA!=1) {
            if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id']))$filter='('.VIS_TABLE_PREFIX.'order.client_id='.$operation['vis_client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$operation['vis_client_id'].')';
            if(isset($operation['vis_filter']) && $operation['vis_filter']!='')$filter=$operation['vis_filter'];
        }
        else return false;
        $database=new class_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);	
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $page=(isset($operation['vis_page']) && is_numeric($operation['vis_page']))?$operation['vis_page']:0;
        $limit=($page*$view_info['page_count']).','.$view_info['page_count']; 		
        $orders=$object->get_orders($filter, VIS_STAFF_ID, VIS_LOCATION_AREA, $limit);       
        $orders_details_total=$object->get_orders($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);      	
		if($orders_details_total!=-1)
        {
			$orders_total=count($orders_details_total);	
			$order_info['count']=$orders_total;
		}
		else
		{
			$order_info['count']=0;
		}		
		$view_info['page_count']=($order_info['count']==0)?0:ceil($order_info['count']/$view_info['page_count']);
		$order_info['page']=$page;	
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==0)
            echo get_xml($invoices, 'invoice');
        elseif(VIS_LOCATION_AREA==1) {
            global $vis_language;
            $header_title=$vis_language['TXTBILLING'];
            include(VIS_PATH_TEMPLATE.'header.php');
            include(VIS_PATH_TEMPLATE.'order_list.php');
            include(VIS_PATH_TEMPLATE.'footer.php');
        }
        else
            include(VIS_PATH_TEMPLATE.'order_list.php');
        return true;
    }
    function process_auth_net_txn($invoice){ 
	if(isset($_POST['x_response_code'])) {
		$database = new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
		$bill_object = new class_billing($database);
		$invoice_details['vis_balance'] = $_POST['x_amount'];
		$invoice_details['vis_client_id'] = VIS_CLIENT_ID;
		$invoice_details['vis_details'] = $_POST['x_description'];
		$invoice_details['vis_transaction'] = $_POST['x_trans_id'];
		$invoice_details['vis_invoice_id'] = $invoice['invoice_id'];
        $invoice_details['vis_invoice_hash'] = $invoice['invoice_hash'];
		$invoice_details['payment_type']=2;
		$bill_object->add_balance($invoice_details, VIS_CLIENT_ID, VIS_LOCATION_AREA);
		$invoice = $bill_object->pay_invoice( array( 'vis_invoice_id' => $invoice['invoice_id'], 'vis_client_id' => VIS_CLIENT_ID, 'vis_balance' => $invoice_details['vis_balance'], 'payment_type' => 2 ), VIS_CLIENT_ID, VIS_LOCATION_AREA );
		$bill_object->update_gateway_log( 2, $invoice_details['vis_invoice_hash'] );
		$database->database_disconnect();
		header('Location: index.php?vis_module=billing&vis_operation=get_invoices');
   		exit;
	}		
   }  
    function client_products_list($operation) {
        global $vis_language; 
        $database=new class_database();
        if(VIS_LOCATION_AREA == 1 && (VIS_ACCESS_BILLING!=1 || VIS_HEAD_MENU_BILLING!=1 || VIS_MODULE_ACCESS_BILLING!=1))
        {
            if(!defined('IS_WHMCS')) 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;
        }
        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);	        
        if(VIS_LOCATION_AREA==1) $view_info['page_count']=10;
        $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.'billing.php');
        $object=new class_billing($database);
        if(VIS_LOCATION_AREA==1 && VIS_CLIENT_ID!=0 && VIS_CLIENT_ID!=-1){
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
            $client=new class_client($database);
            $clientfilter=VIS_TABLE_PREFIX.'client.client_id='.VIS_CLIENT_ID;
            list($client_info, $client_details)=$client->get_client($clientfilter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $client_details=$client_details[0];
            if($client_details['parent_id']!=0) $filter=VIS_TABLE_PREFIX.'invoice.client_id='.$client_details['parent_id']. ' and ' .VIS_TABLE_PREFIX.'invoice.invoice_status=1';
            else $filter=VIS_TABLE_PREFIX.'invoice.client_id='.VIS_CLIENT_ID. ' and ' .VIS_TABLE_PREFIX.'invoice.invoice_status=1';
        }
        else $filter=VIS_TABLE_PREFIX.'invoice.client_id='.$operation['vis_client_id']. ' and ' .VIS_TABLE_PREFIX.'invoice.invoice_status=1';
        $client_product=$object->get_client_product_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA,$limit);
        $client_product_total=$object->get_client_product_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $product_total=($client_product_total==-1)?0:count($client_product_total);
        $client_product_count=($client_product!=-1)?count($client_product):0;
        $product_info['count']=$product_total;	
        $view_info['page_count']=($product_info['count']==0)?0:ceil($product_info['count']/$view_info['page_count']);
        $product_info['page']=$page;
        $database->database_disconnect();
        if(VIS_LOCATION_AREA==1) {
            global $vis_language;
            $header_title=$vis_language['TXTMYPRODUCTS'];			
			 $breadcrumb['Home'] = 'index.php'; 
			 $breadcrumb[$vis_language['TXTMYPRODUCTS']] = ''; 
            $vis_title = $vis_language['TXTMYPRODUCTS'];
			 $vis_count = $product_info['count'];
            if(isset($operation['vis_page']) && is_numeric($operation['vis_page'])){
				if($operation['vis_change']==1){
				include(VIS_PATH_TEMPLATE.'myproduct_list.php');
			}
			else {
				include(VIS_PATH_TEMPLATE.'header.php');
				include(VIS_PATH_TEMPLATE.'view_myproduct.php');
				include(VIS_PATH_TEMPLATE.'footer.php');	
			}
			} else {
				include(VIS_PATH_TEMPLATE.'header.php');
				include(VIS_PATH_TEMPLATE.'view_myproduct.php');
				include(VIS_PATH_TEMPLATE.'footer.php');
			}
        }else include(VIS_PATH_TEMPLATE.'client_products.php');
        return true;
    }
	function get_delete_invoice_item($operation)
	{
		global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELINVOICEITEM'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
		$vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';									
        $message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'billing', 'vis_operation':'delete_invoice_item', 'vis_transaction_id':".$operation['vis_transaction_id'].",'vis_invoice_id':".$operation['vis_invoice_id'].",'vis_client_id':".$operation['vis_client_id'].",'vis_page':'".$vis_page."'})";
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
	}
	function delete_invoice_item($operation)
	{
		global $vis_language;
        if(!isset($operation['vis_transaction_id']) && !isset($operation['vis_invoice_id'])) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVOICEITEMNOTFOUND'].'"); </script>';
            return false;
        }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $ret=$object->delete_invoice_item($operation['vis_transaction_id'],$operation['vis_invoice_id'],$operation['vis_client_id'],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;
        }
        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$operation["vis_invoice_id"].'"});';
        return true;
	}  
	function export_invoice($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_invoice_id']) && is_numeric($operation['vis_invoice_id'])) $invoice_id=$operation['vis_invoice_id'];
        else {
             if(VIS_LOCATION_AREA == 1){
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
            } 

            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVMISS'].'"); </script>';
            return false;
        }
        if(isset($operation['vis_client_id']) && is_numeric($operation['vis_client_id'])) $client_id=$operation['vis_client_id'];
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_billing($database);
        $tkt_object=new class_ticket($database);
        $filter='invoice_id='.$invoice_id;
        if(VIS_LOCATION_AREA==1) {
            if($client_id==0 || $client_id==-1) return false;
            $filter='('.VIS_TABLE_PREFIX.'invoice.client_id='.$client_id.' || '.VIS_TABLE_PREFIX.'client.parent_id='.$client_id.') and '.$filter;
        }
        $invoice_info=$object->get_invoice($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($invoice_info==-1) {
              if(VIS_LOCATION_AREA == 1){
            if(!defined('IS_WHMCS')) include(VIS_PATH_TEMPLATE.'header.php');
            echo '<div class="vis_error_message"><br/>'.$vis_language['MSGACCSSDND'].'<br/></div>';
            include(VIS_PATH_TEMPLATE.'footer.php');
            break;
            } 
            return false;
        } 
        $invoice_details=$object->get_details($invoice_id, VIS_STAFF_ID, VIS_LOCATION_AREA);
        $invoice_info=$invoice_info[0];
        $domain=$tkt_object->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$invoice_info['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $domain_details=$object->get_domain_details('module_id=5 and domain_id='.$invoice_info['domain_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($domain==-1) return false;
        $domain=$domain[0];
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $cl_object=new class_client($database);
        list($clinfo, $client)=$cl_object->get_client('client_id='.$invoice_info['client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($client!=-1) $client=$client[0];
        $transaction_info=$object->get_invoice_transactions('invoice_id='.$invoice_id.' and client_id='.$invoice_info['client_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($invoice_info==-1 || $invoice_details==-1) {
            echo $vis_language['MSGERROPRT'];
            return false;
        }
        else {
            $html=get_include_contents(VIS_PATH_TEMPLATE.'invoice_export.php', array($invoice_info, $invoice_details, count($invoice_details), $domain,$domain_details,$client,$transaction_info));
            require_once(VIS_PATH_PLUGINS.'tcpdf/config/lang/eng.php');
            require_once(VIS_PATH_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->SetTitle("Invoice ID - #".$invoice_info['invoice_hash']);
            $pdf->SetSubject($invoice_info['invoice_hash']);
            $pdf->SetKeywords('Vision helpdesk, PDF, '.$invoice_info['invoice_hash']);
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
            $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
            //$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
            $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($invoice_info['ticket_hash'].'.pdf', 'I');
        }
        return true;
    } 
    function send_mail_for_invoice($operation) {
        global $vis_language;
        if(isset($operation['vis_email_template']) && $operation['vis_email_template'] == 0)
        {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSELECTEMAILTEMPLATE'].'");</script>';
			return false;
		}
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $mail=new class_mail($database);
        $billing=new class_billing($database);
        $setting=new class_setting($database);
        $client_object=new class_client($database);
        $invoice=$billing->get_invoice('invoice_id='.$operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $details=$billing->get_details($operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        $description='<table width="100%"><tr><th align="left">'.$vis_language['TXTDATE'].'</th><th align="left">'.$vis_language['TXTDETAILS'].'</th><th align="left">'.$vis_language['TXTAMOUNT'].'</th></tr>';
        if($details!=-1) for($i=0;$i<count($details);$i++) {
            $description.='<tr><td width="200">'.format_date($details[$i]['entry_date']).'</td><td>'.$details[$i]['description'].'</td><td>'.$details[$i]['amount'].'</td></tr>';
        }
        $description.='</table>';
        $emsetting=$setting->get_settings('title="vis_etemplate_map" and domain_id='.$invoice[0]['domain_id'], $userid, $user);
        list($client_info, $client_details)=$client_object->get_client(VIS_TABLE_PREFIX.'client.client_id='.$invoice[0]['client_id'], '', '', '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		list($tmpinfo, $template)=$setting->get_etemplate('is_enabled=1 and (default_id='.$operation['vis_email_template'].' or parent_id= '.$operation['vis_email_template'].' or etemplate_id='.$operation['vis_email_template'].') and language='.$client_details[0]['language'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		if(empty($template) || $template==-1)
		{
			list($tmpinfo, $template)=$setting->get_etemplate('is_enabled=1 and (default_id='.$operation['vis_email_template'].' or parent_id= '.$operation['vis_email_template'].' or etemplate_id='.$operation['vis_email_template'].') and language=1', '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
        list($dominfo, $domain)=$setting->get_domain(VIS_TABLE_PREFIX.'domain.domain_id='.$invoice[0]['domain_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($template==-1 || $domain==-1) {
            if(VIS_LOCATION_AREA==2) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        $invoiceLink = $domain[0]['domain_url'].'/index.php?/billing/edit-invoice/'.$invoice[0]['invoice_hash'].'/'.$invoice[0]['invoice_id'];
        $subject=$template[0]['subject'];
        $body=$template[0]['content'];
        $currenty_symbol=array('USD'=>'$', 'AUD'=>'$', 'BRL'=>'R$', 'CAD'=>'$', 'CZK'=>'KÄ?', 'DKK'=>'kr', 'EUR'=>'â‚¬', 'HKD'=>'$', 'HUF'=>'Ft', 'ILS'=>'â‚ª', 'JPY'=>'Â¥', 'MYR'=>'RM', 'MXN'=>'$', 'NOK'=>'kr',
'NZD'=> '$', 'PHP'=>'â‚±', 'PLN'=>'zÅ‚', 'GBP'=>'Â£', 'SGD'=>'$', 'SEK'=>'kr', 'CHF'=>'CHF', 'TWD' =>'NT$', 'THB' => 'à¸¿', 'TRY'=>'');
        $pattarns=array('/{username}/', '/{invoice_hash}/', '/{invoice_subtotal}/', '/{invoice_amount}/','/{invoice_date}/','/{client_balance}/', '/{description}/', '/{currency}/', '/{currency_symbol}/', '/{useremail}/', '/{password}/', '/{invoice_duedate}/','/{invoice_link}/');
        $replace=array($invoice[0]['first_name'].' '.$invoice[0]['last_name'], $invoice[0]['invoice_hash'], $invoice[0]['subtotal'], $invoice[0]['total'], format_date($invoice[0]['entry_date']), $invoice[0]['credit'], $description, $domain[0]['currency'], $currenty_symbol[$domain[0]['currency']], $invoice[0]['user_name'], base64_decode($invoice[0]['authentication']),format_date($invoice[0]['due_date']),$invoiceLink);
        $body=preg_replace($pattarns,$replace,$body);
        $result=$mail->send_mail(0, $invoice[0]['domain_id'],  $domain[0]['domain_name'].'<'.$domain[0]['default_email'].'>', $invoice[0]['email'], $subject, $body, '', '', '', array());
        if(VIS_LOCATION_AREA==2) {
            if($result) echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");</script>';
            else echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
        }
        return $result;
    }
    function get_remove_credit($operation) {
        global $vis_language;
        $invoice['amount']='0.00';
        $invoice['details']='';
        $invoice['vis_invoice_id']=0;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $cl_object=new class_client($database);
        list($clinfo, $client)=$cl_object->get_client('client_id='.$operation['vis_client_id'], '', 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($client!=-1) {
            $client=$client[0];
        }
        else return false;
        if(isset($operation['vis_invoice_id']) && is_numeric($operation['vis_invoice_id'])) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
            $object=new class_billing($database);
            $invoice_det=$object->get_invoice('invoice_id='.$operation['vis_invoice_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
            if($invoice_det!=-1) {
                $invoice['vis_invoice_id']=$operation['vis_invoice_id'];
                $invoice['available_credit'] = $invoice_det[0]['credit'];	
                $invoice['remove_credit'] = $invoice_det[0]['invoiceCredit'];	
            }
            $database->database_disconnect();
        }
        else return false;
        include(VIS_PATH_TEMPLATE.'remove_credit.php');
        return true;
    }  
    function remove_credit($operation)
    {
		global $vis_language;
		$data=parse_form_array($operation['vis_action']);
		if(isset($data['remove_credit']) && !is_numeric($data['remove_credit']))
        {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGNUMCREDITVAL'].'");</script>';
			return false;
		}
		if(isset($data['remove_credit']) && ($data['remove_credit'] > $data['vis_credit_applied']))
        {
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGGREATERCREDITREMOVE'].'");</script>';
			return false;
		}
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $res=$object->remove_credit($data,VIS_STAFF_ID, VIS_LOCATION_AREA);
        $database->database_disconnect();
        if($res)
		{
			echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$(".modal").modal("toggle");$("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$data["vis_invoice_id"].'"});</script>'; 
		}
		else
		{
			echo '<script>$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'");$(".modal").modal("toggle");</script>';
		}
	}
	function get_delete_order($operation)
	{
		global $vis_language;
        $message_info['vis_form_title']=$vis_language['TXTDELORDER'];
        $message_info['vis_message']=$vis_language['MSGSURE'];
		$vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';									
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			$vis_page=(isset($operation['vis_page']))?$operation['vis_page']:'';
			$message_info['vis_event'] = "$(this).visExecution('submit_form', {'vis_module':'billing', 'vis_operation':'delete_order', 'vis_form':'vis_order_list_form','vis_page':'".$vis_page."'})";
		}
		else
        {
			$message_info['vis_event']="$(this).visExecution('load_operations', {'vis_module':'billing', 'vis_operation':'delete_order', 'vis_order_id':".$operation['vis_order_id'].",'vis_page':'".$vis_page."'})";
		}
        include(VIS_PATH_TEMPLATE.'confirm_delete.php');
        return true;
	}
	function delete_order($operation)
	{
		global $vis_language;
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
		$object=new class_billing($database);
		if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			 $options=parse_form_array($operation['vis_action']);
			 foreach($options as $data=>$value) if(preg_match('/vis_global_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
			 $orderIds = implode(",",$list_chk);
			 $ret=$object->delete_order('','',VIS_STAFF_ID,VIS_LOCATION_AREA,$orderIds);
        }
        else
        {
			if(!isset($operation['vis_order_id']) || $operation['vis_order_id'] == '') {
				echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
				return false;
			}
			$ret=$object->delete_order($operation['vis_order_id'],'',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;
        }
        echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'");$("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"get_orders"});</script>';
        return true;
	}  
    function get_update_order($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $order=$object->get_order($operation['vis_order_id']);
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'update_order.php');
        return true;
    } 
    function update_order($operation)
    {
		global $vis_language;
		$data = parse_form_array($operation['vis_action']);
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $object->update_order($operation['vis_order_id'],$data);
        $database->database_disconnect();
        echo '<script>$(".modal").modal("toggle");$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"get_orders"});</script>';
        return true;
	}
	function get_add_payment($operation) {
        $invoiceId = $operation['vis_invoice_id'];
        $clientId = $operation['vis_client_id'];
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
		$objectClient=new class_client($database);
		$filter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
		list($client_info, $client_details)=$objectClient->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
		$client_details=$client_details[0];
        $filter = 'domain_id='.$client_details['domain_id'];
        $gatewayDetails = $object->get_gateway_method_details($filter);
        include(VIS_PATH_TEMPLATE.'add_payment.php');
        return true;
    } 
    function add_payment($operation)
    {
		global $vis_language;
		$data = parse_form_array($operation['vis_action']);
		if(trim($data['vis_transaction_id'])=='' || trim($data['vis_amt'])=='')
		{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGREQFLDSEMTY'].'"); </script>';
            return false;
		}
		elseif(!is_numeric($data['vis_amt']))
		{
			echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGINVAMT'].'"); </script>';
            return false;
		}
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $object->add_payment($data);
        $database->database_disconnect();
        echo '<script>$(".modal").modal("toggle");$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#vis_workpanel_div").visExecution("load_operations",{"vis_module":"billing","vis_operation":"edit_invoice", "vis_invoice_id" : "'.$data["vis_invoice_id"].'"});</script>';
        return true;
	}
	function get_update_product_status($operation) {
        global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $filter = VIS_TABLE_PREFIX.'invoice.invoice_id = '.$operation['vis_invoice_id'];
        $client_product=$object->get_client_product_list($filter, VIS_STAFF_ID, VIS_LOCATION_AREA,'');
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'update_product_status.php');
        return true;
    } 
    function update_product_status($operation)
    {
		global $vis_language;
		$data = parse_form_array($operation['vis_action']);
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        $object->update_product_status($operation['vis_invoice_id'],$data);
        $database->database_disconnect();
        echo '<script>$(".modal").modal("toggle");$("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGSUCCOPRT'].'"); $("#product").addClass("active");$("#vis_details_list").visExecution("load_operations",{"vis_module":"billing", "vis_operation":"client_products_list", "vis_client_id":'.$data['vis_client_id'].',"vis_product":1});</script>';
        return true;
	}
    function checkout_product($operation) {
        global $vis_language;
        if(VIS_LOCATION_AREA == 1 && VIS_ACCESS_BILLING!=1)
        {
            if(!defined('IS_WHMCS')) 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;
         }
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $object=new class_billing($database);
        if(isset($operation['vis_action']) && $operation['vis_action']!='')
        {
			$data = explode('/',$operation['vis_action']);
			$operation['vis_product_id'] = $data[4];
		}
        $filter='is_enabled=1 and domain_id='.VIS_DOMAIN.' and product_id='.$operation['vis_product_id'];
        $product=$object->get_product($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($product==-1) {
            if(VIS_LOCATION_AREA == 1)
            {
                if(!defined('IS_WHMCS')) 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;
             }
        }		
		$header_title=$vis_language['TXTPURCHASE'];
		if(VIS_LOCATION_AREA == 1)
		{
			$vis_title=$vis_language['TXTPURCHASE'];	
			$breadcrumb['Home'] = 'index.php'; 
			if((IS_LOGIN==0 && VIS_DEFAULT_HOME_MODULE != $operation['vis_module']) || (IS_LOGIN==1 && VIS_DEFAULT_HOME_MODULE_AFTER_LOGIN != $operation['vis_module'])) $breadcrumb[$vis_language['TXTPURCHASE']] = '?/billing/products-list';
			$breadcrumb[$vis_language['TXTCHECKOUT']] = '';
		}
        if(!IS_LOGIN) return false;        
        $product=$product[1][0];
        $database->database_disconnect();
        include(VIS_PATH_TEMPLATE.'header.php');
        include(VIS_PATH_TEMPLATE.'checkout.php');
        include(VIS_PATH_TEMPLATE.'footer.php');
        return true;
    }
    function manage_credit($operation)
    {
	    global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $billing_object=new class_billing($database);
        if($operation['credit_type'] == 1){$title = $vis_language['TXTTKTBAl']; $amtcolum=$vis_language['TXTTICKETCOUNT'];
				}else{ $title = $vis_language['TXTCASHBAL']; $amtcolum=$vis_language['TXTAMOUNT'];}
        $filter = ' ticket_balance = '.$operation['credit_type'].' and client_id='.$operation['vis_client_id'] ;
        $credit_details=$billing_object->get_credit_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);
        include(VIS_PATH_TEMPLATE.'manage_credit.php');
        return true;
	}
	function delete_credits($operation)
	{
		global $vis_language;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $billing_object=new class_billing($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.'setting.php');
		$setting_object=new class_setting($database);
			if($operation['vis_credit_type']==1)
			{
				$amtcolum=$vis_language['TXTTICKETCOUNT'];
			}else{
				$amtcolum=$vis_language['TXTAMOUNT'];
			}
       
        $creditDetails=$billing_object->get_credit_details('credit_id='.$operation['credit_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
       
        $result = $billing_object->delete_credits('credit_id='.$operation['credit_id'], VIS_STAFF_ID, VIS_LOCATION_AREA);
        if($result)
        { 
			 $client_res=$client_object->get_client_list(VIS_TABLE_PREFIX.'client.client_id='.$creditDetails[0]['client_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
			 $name=((isset($client_res[0]['first_name']) && $client_res[0]['first_name']!='') || (isset($client_res[0]['last_name']) && $client_res[0]['last_name']!=''))?$client_res[0]['first_name']." ".$client_res[0]['last_name']:"";
			
			 $email=(isset($client_res[0]['email']) && $client_res[0]['email']!='')? "( ".$client_res[0]['email']." ) ":"";
			 $activity_log=$setting_object->add_staff_activity_log("Deleted credit of amount ".$creditDetails[0]['amount']." of client ".$name.$email, VIS_STAFF_ID,11,VIS_LOCATION_AREA);
				$client_resbal=$client_object->get_client_credit_and_balance('client_id='.$creditDetails[0]['client_id'],VIS_STAFF_ID, VIS_LOCATION_AREA);
			 
				
				if(strstr($creditDetails[0]['amount'],'-')){
					$creditDetails[0]['amount']=0;
				}else{
					$creditDetails[0]['amount']=$creditDetails[0]['amount'];
				}
				
				if($operation['vis_credit_type']==1){
					$creditDetails[0]['amount']=($client_resbal[0]['balance']>$creditDetails[0]['amount'])?$creditDetails[0]['amount']:$client_resbal[0]['balance'];
				}else{
					$creditDetails[0]['amount']=($client_resbal[0]['credit']>$creditDetails[0]['amount'])?$creditDetails[0]['amount']:$client_resbal[0]['credit'];
				}
				
			$billingResult = $billing_object->update_client_credit_balance('client_id='.$creditDetails[0]['client_id'],$operation['vis_credit_type'],$creditDetails[0]['amount']);
			
			
		     $filter = ' ticket_balance = '.$operation['vis_credit_type'].' and client_id='.$operation['vis_client_id'] ;
             $credit_details=$billing_object->get_credit_details($filter, VIS_STAFF_ID, VIS_LOCATION_AREA);	
             if($credit_details != -1) include(VIS_PATH_TEMPLATE.'manage_credit_table.php');
             else echo -1;
             
		}
       
	}
    
    function process_stripe_txn($invoice){ 
        global $vis_language;
        $database = new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'billing.php');
        $bill_object = new class_billing($database);
        $invoice_details['vis_balance'] = $_POST['amount']/100;
        $invoice_details['vis_client_id'] = VIS_CLIENT_ID;
        $invoice_details['vis_details'] = '';
        $invoice_details['vis_invoice_id'] = $invoice['invoice_id'];
        $invoice_details['invoice_hash']=$invoice['invoice_hash'];
        $bill_object->add_balance($invoice_details, VIS_CLIENT_ID, VIS_LOCATION_AREA);
        $invoice = $bill_object->pay_invoice( array( 'vis_invoice_id' => $invoice['invoice_id'], 'vis_client_id' => VIS_CLIENT_ID, 'vis_balance' => $invoice['total'], 'payment_type' => 3 ), VIS_CLIENT_ID, VIS_LOCATION_AREA );
        $bill_object->update_gateway_log( 3, $invoice_details['invoice_hash'] );
        $database->database_disconnect();
        header('Location: index.php?vis_module=billing&vis_operation=get_invoices');
        exit;
   }
   function update_mass_invoice_status($operation) {
        global $vis_language;
        $operation['vis_current_operation']='client_details'; 
        $operation['vis_current_module']='client'; 
        if(!isset($operation['vis_update_id']) || !is_numeric($operation['vis_update_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.'billing.php');
        $object=new class_billing($database);
        if(isset($operation['vis_action']) && $operation['vis_action'] !='')
        {
			 $options=parse_form_array($operation['vis_action']);
			 foreach($options as $data=>$value) if(preg_match('/vis_global_mass_chk_[0-9]/', $data)) $list_chk[]=$value;
			 for($i=0;$i<count($list_chk);$i++){
			 $operation['vis_invoice_id'] = $list_chk[$i];
			 $ret=$object->update_invoice_status($operation, VIS_STAFF_ID, VIS_LOCATION_AREA);
			 }
		}
		$unpaid_invoice_cnt=$object->get_unpaid_invoice_count('('.VIS_TABLE_PREFIX.'invoice.client_id='.$operation['vis_client_id'].' or '. VIS_TABLE_PREFIX.'client.parent_id='.$operation['vis_client_id'].') and invoice_status=0 ', VIS_STAFF_ID, VIS_LOCATION_AREA);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
        $filter=VIS_TABLE_PREFIX.'client.client_id='.$operation['vis_client_id'];
        list($client_info, $client_details)=$object->get_client($filter, 1, 0, '', VIS_STAFF_ID, VIS_LOCATION_AREA);
        $client_details=$client_details[0];
        $client_name = $client_details['first_name']." ".$client_details['last_name'];
        $database->database_disconnect();
        if(!$ret) {
            echo '<script> $("#vis_global_msg_div").visInterface("load_global_message", "'.$vis_language['MSGERROPRT'].'"); </script>';
            return false;
        }
        else 
        if($operation['vis_client_id']!='')
		echo '<script>javascript:active_invoice_tab();$("#vis_unpaid_invoice_count").text('.$unpaid_invoice_cnt['cnt'].');</script>';
	    else
		echo '<script>$("#vis_workpanel_div").visExecution("load_module","Billing",{"vis_module":"billing", "vis_operation":"get_invoices"});</script>';
        return true;
    }
}
?>
