$biller_id = $_GET['biller_id'];
$customer_id = $_GET['customer_id'];
$filter_by_date = $_GET['filter_by_date'];
if ( $filter_by_date =="yes" )
{
	$start_date = $_GET['start_date'];
	$end_date = $_GET['end_date'];
}
$show_only_unpaid = $_GET['show_only_unpaid'];
$show_only_real = $_GET['show_only_real'];
$get_format = $_GET['format'];
$get_file_type = $_GET['filetype'];


$biller = $SI_BILLER->getBiller($_GET['biller_id']);
$customer = customer::get($_GET['customer_id']);

#create PDF name

if ($_GET['stage'] == 2 ) {

	#echo $block_stage2;


	#get the invoice id
	$export = new export();
	$export -> format = 'pdf';
	$export -> file_type = $get_file_type;
	$export -> file_location = 'file';
	$export -> module = 'statement';
	function getData()
	{
		//echo "export - get data";
		global $smarty;
		global $siUrl;
		global $include_dir;
        
        $SI_BILLER = new SimpleInvoices_Db_Table_Biller();
        $SI_CUSTOM_FIELDS = new SimpleInvoices_Db_Table_CustomFields();
        $SI_PREFERENCES = new SimpleInvoices_Db_Table_Preferences();
        
		switch ($this->module)
		{
			case "database":
			{
                $data = SimpleInvoices_Db::performBackup();
				break;
			}
			case "statement":
			{
				$invoice = new invoice();
				$invoice->biller = $this->biller_id;
				$invoice->customer = $this->customer_id;

				if ( $this->filter_by_date =="yes" )
				{
					if ( isset($this->start_date) )
					{
						$invoice->start_date = $this->start_date;
					}
					if ( isset($this->end_date) )
					{
						$invoice->end_date = $this->end_date;
					}

					if ( isset($this->start_date) AND isset($this->end_date) )
					{
						$invoice->having = "date_between";
					}
					$having_count = '1';
				}

				if ( $this->show_only_unpaid == "yes")
				{
					if ($having_count == '1')
					{

						$invoice->having_and = "money_owed";
					    $having_count = '2';

					} else {

						$invoice->having = "money_owed";
					    $having_count = '1';

					}
				}

				if ( $this->show_only_real == "yes")
				{
					if ($having_count == '2')
					{

						$invoice->having_and2 = "real";

					} elseif ($having_count == '1') {

						$invoice->having_and = "real";

					} else {

						$invoice->having = "real";

					}
				}

				$invoice_all = $invoice->select_all('count');

				$invoices = $invoice_all->fetchAll();

				foreach ($invoices as $i => $row) {
					$statement['total'] = $statement['total'] + $row['invoice_total'];
					$statement['owing'] = $statement['owing'] + $row['owing'] ;
					$statement['paid'] = $statement['paid'] + $row['INV_PAID'];

				}

                // ToDo: THIS FILE IS MISSING!!
				$templatePath = $include_dir . "sys/templates/default/statement/index.tpl";

				$biller_details = $SI_BILLER->getBiller($this->biller_id);
				$customer_details = customer::get($this->customer_id);

				$this->file_name = "statement_".$this->biller_id."_".$this->customer_id."_".$invoice->start_date."_".$invoice->end_date;

				$smarty -> assign('biller_id', $biller_id);
				$smarty -> assign('biller_details', $biller_details);
				$smarty -> assign('customer_id', $customer_id);
				$smarty -> assign('customer_details', $customer_details);

				$smarty -> assign('show_only_unpaid', $show_only_unpaid);
				$smarty -> assign('show_only_real', $show_only_real);
				$smarty -> assign('filter_by_date', $this->filter_by_date);

				$smarty -> assign('invoices', $invoices);
				$smarty -> assign('start_date', $this->start_date);
				$smarty -> assign('end_date', $this->end_date);

				$smarty -> assign('invoices',$invoices);
				$smarty -> assign('statement',$statement);
				$data = $smarty -> fetch(".".$templatePath);

				break;
			}
            case "payment":
            {
                $customFieldLabels = $SI_CUSTOM_FIELDS->getLabels();
                
                $payment = new SimpleInvoices_Payment($this->id);
                $invoice = $payment->getInvoice();
                $biller = $invoice->getBiller();
                $logo = $biller->getLogo();
                $logo = str_replace(" ", "%20", $logo);
                $customer = $invoice->getCustomer();
                
                $smarty -> assign("payment",$payment->toArray());
                $smarty -> assign("invoice",$invoice->toArray());
                $smarty -> assign("biller",$biller->toArray());
                $smarty -> assign("logo",$logo);
                $smarty -> assign("customer",$customer->toArray());
                $smarty -> assign("invoiceType",$invoice->getType());
                $smarty -> assign("paymentType",$payment->getType());
                $smarty -> assign("preference",$invoice->getPreference());
                $smarty -> assign("customFieldLabels",$customFieldLabels);

                $smarty -> assign('pageActive', 'payment');
                $smarty -> assign('active_tab', '#money');

				$css = $siUrl."/sys/templates/invoices/default/style.css";
				$smarty -> assign('css',$css);

                $templatePath = $include_dir . "sys/templates/default/modules/payments/print.tpl";
				$data = $smarty -> fetch($templatePath);
				
                break;
            }
			case "invoice":
			{
                $SI_SYSTEM_DEFAULTS = new SimpleInvoices_Db_Table_SystemDefaults();
                
				$invoice = invoice::select($this->id);
 			    $invoice_number_of_taxes = numberOfTaxesForInvoice($this->id);
				$customer = customer::get($invoice['customer_id']);
				$biller = biller::select($invoice['biller_id']);
				$preference = $SI_PREFERENCES->getPreferenceById($invoice['preference_id']);
				$defaults = $SI_SYSTEM_DEFAULTS->fetchAll();
				$logo = getLogo($biller);
				$logo = str_replace(" ", "%20", $logo);
				$invoiceItems = invoice::getInvoiceItems($this->id);

				$spc2us_pref = str_replace(" ", "_", $invoice['index_name']);
				$this->file_name = $spc2us_pref;

				$customFieldLabels = $SI_CUSTOM_FIELDS->getLabels();
				$customFieldDisplay = $SI_CUSTOM_FIELDS->getDisplay();

				/*Set the template to the default*/
				$template = $defaults['template'];

                // Instead of appending the CSS we are going to inject it allowing
                // a cleaner hierarchy tree while allowing public directories
				$css_file = $include_dir ."/sys/templates/invoices/${template}/style.css";
                
                if (file_exists($css_file)) {
                    $css = file_get_contents($css_file);
                    if ($css) {
                        // Create the tags
                        $css = '<style type="text/css" media="all">' . $css . '</style>';
                    }
                } else {
                    $css = '';
                }

                $smarty->addTemplateDir($include_dir . "sys/templates/invoices/${template}/", 'Invoice_' . $template);
				$smarty->addPluginsDir($include_dir ."sys/templates/invoices/${template}/plugins/");

				$pageActive = "invoices";
				$smarty->assign('pageActive', $pageActive);

                if ($smarty->templateExists('file:[Invoice_' . $template . ']template.tpl')) {
					$smarty -> assign('biller',$biller);
					$smarty -> assign('customer',$customer);
					$smarty -> assign('invoice',$invoice);
					$smarty -> assign('invoice_number_of_taxes',$invoice_number_of_taxes);
					$smarty -> assign('preference',$preference);
					$smarty -> assign('logo',$logo);
					$smarty -> assign('template',$template);
					$smarty -> assign('invoiceItems',$invoiceItems);
					$smarty -> assign('css',$css);
					$smarty -> assign('customFieldLabels',$customFieldLabels);
					$smarty -> assign('customFieldDisplay',$customFieldDisplay);

					$data = $smarty->fetch('file:[Invoice_' . $template . ']template.tpl');
				}

				break;
			}

		}

		return $data;

	}
    public function payment()
    {
    
        global $config;
        global $logger;
        
        $SI_BILLER = new SimpleInvoices_Db_Table_Biller();
        $SI_PREFERENCES = new SimpleInvoices_Db_Table_Preferences();
        
        //set customer,biller and preference if not defined
        if(empty($this->customer))
        {
            $this->customer = customer::get($this->invoice['customer_id']);
        }
        if(empty($this->biller))
        {
            $this->biller = $SI_BILLER->getBiller($this->invoice['biller_id']);
        }
        if(empty($this->preference))
        {
            $this->preference = $SI_PREFERENCES->getPreferenceById($this->invoice['preference_id']);
        }

        $eway = new ewaylib($this->biller['eway_customer_id'],'REAL_TIME', false);

        //Eway only accepts amount in cents - so times 100
		$value = $this->invoice['total']*100;
		$eway_invoice_total = htmlsafe(trim($value));
        $logger->log("eway totla: " . $eway_invoice_total, Zend_Log::INFO);

        $enc = new encryption();
        $key = $config->encryption->default->key;	
        $credit_card_number = $enc->decrypt($key, $this->customer['credit_card_number']);

        $eway->setTransactionData("TotalAmount", $eway_invoice_total); //mandatory field
        $eway->setTransactionData("CustomerFirstName", $this->customer['name']);
    	$eway->setTransactionData("CustomerLastName", "");
        $eway->setTransactionData("CustomerAddress", "");
        $eway->setTransactionData("CustomerPostcode", "");
        $eway->setTransactionData("CustomerInvoiceDescription", "");
        $eway->setTransactionData("CustomerEmail", $this->customer['email']);
        $eway->setTransactionData("CustomerInvoiceRef", $this->invoice['index_name']);
        $eway->setTransactionData("CardHoldersName", $this->customer['credit_card_holder_name']); //mandatory field
        $eway->setTransactionData("CardNumber", $credit_card_number); //mandatory field
        $eway->setTransactionData("CardExpiryMonth", $this->customer['credit_card_expiry_month']); //mandatory field
        $eway->setTransactionData("CardExpiryYear", $this->customer['credit_card_expiry_year']); //mandatory field
        $eway->setTransactionData("Option1", "");
        $eway->setTransactionData("Option2", "");
        $eway->setTransactionData("Option3", "");
        $eway->setTransactionData("TrxnNumber", $this->invoice['id']);
        
        //special preferences for php Curl
        $eway->setCurlPreferences(CURLOPT_SSL_VERIFYPEER, 0);  //pass a long that is set to a zero value to stop curl from verifying the peer's certificate 
        $ewayResponseFields = $eway->doPayment();
        $this->message = $ewayResponseFields;
        $message ="";
        if($ewayResponseFields["EWAYTRXNSTATUS"]=="False"){
			$logger->log("Transaction Error: " . $ewayResponseFields["EWAYTRXNERROR"] . "<br>\n", Zend_Log::INFO);
            foreach($ewayResponseFields as $key => $value)
                $message .= "\n<br>\$ewayResponseFields[\"$key\"] = $value";
			$logger->log("Eway message: " . $message . "<br>\n", Zend_Log::INFO);
            //header("Location: trasnactionerrorpage.php");
            //exit();
            $return = 'false';		
        }else if($ewayResponseFields["EWAYTRXNSTATUS"]=="True"){


			$logger->log("Transaction Success: " . $ewayResponseFields["EWAYTRXNERROR"] . "<br>\n", Zend_Log::INFO);
            foreach($ewayResponseFields as $key => $value)
                $message .= "\n<br>\$ewayResponseFields[\"$key\"] = $value";
			$logger->log("Eway message: " . $message . "<br>\n", Zend_Log::INFO);
            //header("Location: trasnactionsuccess.php");
            //exit();
            $payment = new payment();
            $payment->ac_inv_id = $this->invoice['id'];
            #$payment->ac_inv_id = $_POST['invoice'];
            $payment->ac_amount = $this->invoice['total'];
            #$payment->ac_amount = $ewayResponseFields['EWAYRETURNAMOUNT']/100;
            #$payment->ac_amount = $_POST['mc_gross'];
            $payment->ac_notes = $message;
            $payment->ac_date = date( 'Y-m-d' );
            $payment->online_payment_id = $ewayResponseFields['EWAYTRXNNUMBER'];
            $payment->domain_id = domain_id::get($this->domain_id);

                $payment_type = new payment_type();
                $payment_type->type = "Eway";
                $payment_type->domain_id = $domain_id;

            $payment->ac_payment_type = $payment_type->select_or_insert_where();
            $logger->log('Paypal - payment_type='.$payment->ac_payment_type, Zend_Log::INFO);
            $payment->insert();
            #echo $db->lastInsertID();
            $return = 'true';		
        }

        return $return ;		
    }
$SI_SYSTEM_DEFAULTS = new SimpleInvoices_Db_Table_SystemDefaults();
$SI_CUSTOMERS = new SimpleInvoices_Db_Table_Customers();
$SI_INVOICE_TYPE = new SimpleInvoices_Db_Table_InvoiceType();
$SI_BILLER = new SimpleInvoices_Db_Table_Biller();
$SI_PREFERENCES = new SimpleInvoices_Db_Table_Preferences();
$SI_CUSTOM_FIELDS = new SimpleInvoices_Db_Table_CustomFields();

#get the invoice id
$invoice_id = $_GET['invoice'];


$invoice = getInvoice($invoice_id);
$invoice_type = $SI_INVOICE_TYPE->getInvoiceType($invoice['type_id']);
$customer = $SI_CUSTOMERS->getCustomerById($invoice['customer_id']);
$biller = $SI_BILLER->getBiller($invoice['biller_id']);
$preference = $SI_PREFERENCES->getPreferenceById($invoice['preference_id']);
$defaults = $SI_SYSTEM_DEFAULTS->fetchAll();
$invoiceItems = matrix_invoice::getInvoiceItems($invoice_id);

#Invoice Age - number of days - start
if ($invoice['owing'] > 0 ) {
    $invoice_age_days =  number_format((strtotime(date('Y-m-d')) - strtotime($invoice['calc_date'])) / (60 * 60 * 24),0);
	$invoice_age = "$invoice_age_days {$LANG['days']}";
}
else {
    $invoice_age ="";
}

	$url_for_pdf = "./pdfmaker.php?id=" . $invoice['id'];
        
	$invoice_all = $invoice->select_all();

	$invoices = $invoice_all->fetchAll();

	foreach ($invoices as $i => $row) {
		$statement['total'] = $statement['total'] + $row['invoice_total'];
		$statement['owing'] = $statement['owing'] + $row['owing'] ;
		$statement['paid'] = $statement['paid'] + $row['INV_PAID'];
		
	}
}

$sql = "select DISTINCT(custom_field3) from  " . TB_PREFIX . "invoices where custom_field3 != ''";
$cf3 = $db->query($sql);

$biller_details = $SI_BILLER->getBiller($biller_id);
$customer_details = $SI_CUSTOMERS->getCustomerById($customer_id);
$smarty -> assign('biller_id', $biller_id);
$smarty -> assign('biller_details', $biller_details);
$smarty -> assign('customer_id', $customer_id);
$smarty -> assign('customer_details', $customer_details);
$smarty -> assign('cf3', $cf3->fetchAll());
$smarty -> assign('custom_field3', $custom_field3);

$smarty -> assign('filter_by_date', $filter_by_date);


$smarty -> assign('invoices', $invoices);
$smarty -> assign('statement', $statement);
$smarty -> assign('start_date', $start_date);
$smarty -> assign('end_date', $end_date);
 /**
  * Initializes invoice data.
  * This method is equivalent to the old getInvoice()
  */
 protected function _initData()
 {
     $billers = new SimpleInvoices_Db_Table_Biller();
     $this->_data = $billers->getBiller($this->_id);
 }