<?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 email,contact_name,company_name FROM client WHERE client_id = '.intval($this->dataRecord['client_id']));
			$company = $app->db->queryOneRecord('SELECT email 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 = $client['email'];
			$subject = $this->dataRecord['subject'];
			$text_message = $this->dataRecord['message'];
			$from = $company['email'];
			
			if($this->dataRecord['invoice_id'] > 0) {
				$invoice = $app->db->queryOneRecord('SELECT invoice_number, idhash FROM invoice WHERE invoice_id = '.intval($this->dataRecord['invoice_id']));
				$invoice_filename = ISPC_ROOT_PATH.'/invoices/'.$invoice['invoice_number'].'.pdf';
			} 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);
			
			$app->uses('functions');
			if($client['email'] != '') $app->functions->mail($to, $subject, $text_message, $from, $invoice_filename);
			
			//* 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($_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($_GET['invoice_id'] > 0 || $this->dataRecord['invoice_id'] > 0) {
					$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();

?>