<?php
/*
Copyright (c) 2010, Till Brehm, projektfarm Gmbh
All rights reserved.
*/


/******************************************
* Begin Form configuration
******************************************/

$tform_def_file = "form/invoice_message.tform.php";

/******************************************
* End Form configuration
******************************************/

require_once('../../lib/config.inc.php');
require_once('../../lib/app.inc.php');

//* Check permissions for module
$app->auth->check_module_permissions('billing');

// Loading classes
$app->uses('tpl,tform,tform_actions');
$app->load('tform_actions');

class page_action extends tform_actions {
	
	function onSubmit() {
		global $app;
		
		// If we load a template, we set a fake error message to make sure that the item does not get saved.
		if($_GET['action'] == 'loadtemplate') {
			$app->tform->errorMessage = 'nosave';
		}
		parent::onSubmit();
	}
	
	function onAfterInsert() {
		$this->onAfterUpdate();
	}
	
	function onAfterUpdate() {
		global $app;
		
		//* Send the email and set status to 'sent'
		if($_GET['action'] == 'send') {
			
			$client = $app->db->queryOneRecord('SELECT * FROM client WHERE client_id = '.intval($this->dataRecord['client_id']));
			$company = $app->db->queryOneRecord('SELECT * FROM invoice_company WHERE invoice_company_id = '.intval($this->dataRecord['invoice_company_id']));
			$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
			
			$to = trim($client['email']);
			$subject = $this->dataRecord['subject'];
			$text_message = $this->dataRecord['message'];
			$from_name = trim($company['sender_name']);
			$from = trim($company['sender_email']);
			if(!$from) $from = trim($company['email']);
			$bcc = trim($company['bcc_email']);
			
			if($this->dataRecord['invoice_id'] > 0) {
				$invoice = $app->db->queryOneRecord('SELECT invoice_number, idhash, invoice_amount, reminder_step FROM invoice WHERE invoice_id = '.intval($this->dataRecord['invoice_id']));
				$app->uses('billing_functions');
				$invoice_filename = $app->billing_functions->get_invoice_filename($invoice['invoice_number'], $invoice['reminder_step']);
                $client_settings = $app->db->queryOneRecord('SELECT * FROM invoice_client_settings WHERE client_id = '.intval($this->dataRecord['client_id']));
                if(isset($client_settings['payment_email']) && trim($client_settings['payment_email']) != '') $to = trim($client_settings['payment_email']);
			} else {
				$invoice_filename = '';
			}
			
			
			
			//* Replace placeholders {INVOICE_NUMBER}, {CONTACT_NAME}, {COMPANY_NAME}
			/*			
			$text_message = str_replace('{INVOICE_NUMBER}',$invoice['invoice_number'],$text_message);
			$text_message = str_replace('{CONTACT_NAME}',$client['contact_name'],$text_message);
			$text_message = str_replace('{COMPANY_NAME}',$client['company_name'],$text_message);
			
			$subject = str_replace('{INVOICE_NUMBER}',$invoice['invoice_number'],$subject);
			$subject = str_replace('{CONTACT_NAME}',$client['contact_name'],$subject);
			$subject = str_replace('{COMPANY_NAME}',$client['company_name'],$subject);
			*/
			if(isset($invoice_settings['invoice_pay_link']) && $invoice_settings['invoice_pay_link'] != '') {
				$invoice_pay_link = $invoice_settings['invoice_pay_link'].$invoice['idhash'];
			} else {
				$ispconfig_url = $app->functions->get_ispconfig_url();
				$invoice_pay_link = $ispconfig_url.'/billing/payments/pay.php?id='.$invoice['idhash'];
			}
			//$text_message = str_replace('{INVOICE_PAY_LINK}',$invoice_pay_link,$text_message);
			
			$trans = array( '{REMINDER_STEP}' => $invoice['reminder_step'],
                            '{INVOICE_NUMBER}' => $invoice['invoice_number'], 
							'{INVOICE_AMOUNT}' => $app->functions->currency_format($invoice['invoice_amount'], 'client'),
							'{INVOICE_CURRENCY}' => $invoice_settings['currency'],
							'{INVOICE_PAY_LINK}' => $invoice_pay_link,
							'{CONTACT_NAME}' => $client['contact_name'], 
							'{COMPANY_NAME}' => $client['company_name'], 
							'{CLIENT_CONTACT_NAME}' => $client['contact_name'], 
							'{CLIENT_COMPANY_NAME}' => $client['company_name'],
							'{CLIENT_COMPANY_ID}' => $client['company_id'],
							'{CLIENT_CUSTOMER_NO}' => $client['customer_no'],
							'{CLIENT_VAT_ID}' => $client['vat_id'],
							'{CLIENT_STREET}' => $client['street'],
							'{CLIENT_ZIP}' => $client['zip'],
							'{CLIENT_CITY}' => $client['city'],
							'{CLIENT_STATE}' => $client['state'],
							'{CLIENT_COUNTRY}' => $client['country'],
							'{CLIENT_TELEPHONE}' => $client['telephone'],
							'{CLIENT_MOBILE}' => $client['mobile'],
							'{CLIENT_FAX}' => $client['fax'],
							'{CLIENT_EMAIL}' => $to,
							'{CLIENT_INTERNET}' => $client['internet'],
							'{CLIENT_ICQ}' => $client['icq'],
							'{CLIENT_NOTES}' => $client['notes'],
							'{CLIENT_BANKACCOUNT_OWNER}' => $client['bank_account_owner'],
							'{CLIENT_BANKACCOUNT_NO}' => $client['bank_account_number'],
							'{CLIENT_BANK_CODE}' => $client['bank_code'],
							'{CLIENT_BANK_NAME}' => $client['bank_name'],
							'{CLIENT_BANKACCOUNT_IBAN}' => $client['bank_account_iban'],
							'{CLIENT_BANKACCOUNT_SWIFT}' => $client['bank_account_swift'],
							'{ISSUER_COMPANY_NAME}' => $company['company_name'],
							'{ISSUER_COMPANY_NAME_SHORT}' => $company['company_name_short'],
							'{ISSUER_CONTACT_NAME}' => $company['contact_name'],
							'{ISSUER_CEO_NAME}' => $company['ceo_name'],
							'{ISSUER_VAT_ID}' => $company['vat_id'],
							'{ISSUER_TAX_ID}' => $company['tax_id'],
							'{ISSUER_COMPANY_REGISTER}' => $company['company_register'],
							'{ISSUER_STREET}' => $company['street'],
							'{ISSUER_ZIP}' => $company['zip'],
							'{ISSUER_CITY}' => $company['city'],
							'{ISSUER_STATE}' => $company['state'],
							'{ISSUER_COUNTRY}' => $company['country'],
							'{ISSUER_TELEPHONE}' => $company['telephone'],
							'{ISSUER_FAX}' => $company['fax'],
							'{ISSUER_EMAIL}' => $from,
							'{ISSUER_INTERNET}' => $company['internet'],
							'{ISSUER_BANKACCOUNT_OWNER}' => $company['bank_account_owner'],
							'{ISSUER_BANKACCOUNT_NO}' => $company['bank_account_number'],
							'{ISSUER_BANK_CODE}' => $company['bank_code'],
							'{ISSUER_BANK_NAME}' => $company['bank_name'],
							'{ISSUER_BANKACCOUNT_IBAN}' => $company['bank_account_iban'],
							'{ISSUER_BANKACCOUNT_SWIFT}' => $company['bank_account_swift'],
							);
			$text_message = strtr($text_message, $trans);
			$subject = strtr($subject, $trans);
			
			$app->uses('functions');
			if($to != '') $app->functions->mail($to, $subject, $text_message, $from, $invoice_filename, 'application/pdf', '', '', $bcc, $from_name);
			
			//* Update message status
			$app->db->query("UPDATE invoice_message SET message_status = 'sent' WHERE invoice_message_id = ".intval($this->id));
			
			//* Update invoice status
			if($this->dataRecord['invoice_id'] > 0) {
				$app->db->query("UPDATE invoice SET status_sent = 'y' WHERE invoice_id = ".intval($this->dataRecord['invoice_id']));
			}
		}
		
	}

	function onShowNew() {
		global $app;
		
		if($app->tform->errorMessage == '') {
			$record = array();
            $record = $app->tform->getHTML($record, $app->tform->formDef['tab_default'],'NEW');
			
		} else {
			$record = $app->tform->getHTML($app->tform->encode($_POST,$this->active_tab),$this->active_tab,'EDIT');
        }

        $app->tpl->setVar($record);	
	}

	
	function onShowEnd() {
                global $app, $conf;
				
				$record = array();
				$record['message_type'] = 'other';
				
				// If we load data from a template, we overwrite some variables and remove 
				// our fake error that was set in onSubmit event
				if(isset($_GET['action']) && $_GET['action'] == 'loadtemplate') {
					if($_REQUEST['message_template_id'] > 0) {
						$tmp = $app->db->queryOneRecord("SELECT * FROM invoice_message_template WHERE invoice_message_template_id = ".intval($_REQUEST['message_template_id']));
						$record['subject'] = $tmp['subject'];
						$record['message'] = $tmp['message'];
						$record['message_type'] = $tmp['template_type'];
					} else {
						$record['subject'] = '';
						$record['message'] = '';
						$record['message_type'] = 'Other';
					}
					$record['error'] = '';
					
				}
				
				$app->tpl->setVar($record);
				
				/*
				$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
				$app->tpl->setVar('date_format_txt',$invoice_settings['date_format']);
				*/
				
				if((isset($_GET['invoice_id']) && $_GET['invoice_id'] > 0) || $this->dataRecord['invoice_id'] > 0) {
					$invoice_id = (isset($_GET['invoice_id']) && $_GET['invoice_id'] > 0)?$_GET['invoice_id']:$this->dataRecord['invoice_id'];
					$invoice = $app->db->queryOneRecord("SELECT invoice_number FROM invoice WHERE invoice_id = ".intval($invoice_id));
					$app->tpl->setVar($invoice);
				}

                // Template parsen
                $app->tpl->pparse();
        }
	

}

$page = new page_action;
$page->onLoad();

?>