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

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

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

$app->uses('tpl');

$app->tpl->newTemplate('form.tpl.htm');
$app->tpl->setInclude('content_tpl', 'templates/send_invoice_reminder.htm');
$msg = '';
$error = '';
$page_back_link = 'billing/send_invoice_reminder.php';

// Export the language file
if(isset($_GET['action']) && $_GET['action'] == 'send') {
	
	$email_template_id = intval($_POST['email_template_id']);
	if($email_template_id == 0) $error .= $app->lng('No Email template selected.').'<br />';
	if(count($_POST['invoice_id']) == 0) $error .= $app->lng('No pending invoices selcted.').'<br />';
	
	if($error == '' && is_array($_POST['invoice_id'])) {
		//* Get the email template
		$email_template = $app->db->queryOneRecord("SELECT * FROM invoice_message_template WHERE invoice_message_template_id = $email_template_id");
		
		//* Send the reminders by email.
		$app->uses('functions');
		foreach($_POST['invoice_id'] as $invoice_id) {
			$invoice_id = intval($invoice_id);
			//* Get the invoice, client and company
			$sql = "SELECT invoice_company.email as company_email,invoice.invoice_number,invoice.idhash,client.email as client_email,invoice.invoice_number,client.contact_name,client.company_name
					FROM invoice_company,invoice,client 
					WHERE invoice_company.invoice_company_id = invoice.invoice_company_id AND client.client_id = invoice.client_id AND invoice_id = $invoice_id";
			$rec = $app->db->queryOneRecord($sql);
			
			//* Replace placeholders {INVOICE_NUMBER}, {CONTACT_NAME}, {COMPANY_NAME}
			$email_message = $email_template['message'];
			$email_message = str_replace('{INVOICE_NUMBER}',$rec['invoice_number'],$email_message);
			$email_message = str_replace('{CONTACT_NAME}',$rec['contact_name'],$email_message);
			$email_message = str_replace('{COMPANY_NAME}',$rec['company_name'],$email_message);
			
			$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
			
			if(isset($invoice_settings['invoice_pay_link']) && $invoice_settings['invoice_pay_link'] != '') {
				$invoice_pay_link = $invoice_settings['invoice_pay_link'].$rec['idhash'];
			} else {
				$ispconfig_url = $app->functions->get_ispconfig_url();
				$invoice_pay_link = $ispconfig_url.'/billing/payments/pay.php?id='.$rec['idhash'];
			}
			$text_message = str_replace('{INVOICE_PAY_LINK}',$invoice_pay_link,$text_message);
			
			//* Send email
			if($rec['client_email'] != '') {
				$app->functions->mail($rec['client_email'], $email_template['subject'], $email_message, $rec['company_email']);
				$msg .= 'Sent reminder for invoice '.$rec['invoice_number'].' to '.$rec['client_email'].'<br />';
			} else {
				$error .= 'No email address pecified for '.$rec['invoice_number'].' client '.$rec['contact_name'].' :: '.$rec['company_name'].'<br />';
			}
			
			
		}
	}
} else {
	
	//* Get all payment terms
	$payment_terms = array();
	$tmp_payment_terms = $app->db->queryAllRecords("SELECT invoice_payment_term_id AS id,due_days FROM invoice_payment_term");
	foreach($tmp_payment_terms as $tmp) {
		$key = $tmp['id'];
		$payment_terms[$key] = $tmp['due_days'];
	}
	unset($tmp_payment_terms);
	unset($tmp);
	unset($key);
	
	//* Select all unpaid invoices
	$sql = "SELECT * FROM client, invoice WHERE client.client_id = invoice.client_id AND invoice.status_printed = 'y' AND invoice.status_paid = 'n'";
	$invoices = $app->db->queryAllRecords($sql);
	$now_tstamp = time();
	$invoices_overdue = array();
	if(is_array($invoices)) {
		foreach($invoices as $invoice) {
			//* Check if onvoice is overdue
			$invoice_date_parts = explode('-',$invoice['invoice_date']);
			$payment_terms_id = $invoice['payment_terms'];
			$due_date_tstamp = mktime(0, 0, 0, $invoice_date_parts[1]  , (int)$invoice_date_parts[2]+$payment_terms[$payment_terms_id], (int)$invoice_date_parts[0]);

			if($due_date_tstamp < $now_tstamp) {
				$invoices_overdue[] = array(	'invoice_date' => $invoice['invoice_date'],
											'due_date' => date('Y-m-d',$due_date_tstamp),
											'invoice_number' => $invoice['invoice_number'],
											'invoice_id' => $invoice['invoice_id'],
											'contact_name' => $invoice['contact_name'],
											'company_name' => $invoice['company_name']
											);
			}
		}
	}
	
	$app->tpl->setLoop('invoices',$invoices_overdue);
	if(count($invoices_overdue) > 0) {
		$app->tpl->setVar('show_list',1);
	} else {
		$msg .= $app->lng('No invoices are overdue.');
		$page_back_link = 'billing/invoice_list.php';
	}
	
	//* Insert reminder email template list
	$sql = "SELECT invoice_message_template_id, template_name FROM invoice_message_template WHERE template_type = 'reminder'";
	$records = $app->db->queryAllRecords($sql);
	$email_template_select = "<option value='0'>- Select template -</option>";
	if(is_array($records)) {
		foreach( $records as $rec) {
			//$selected = ($ip["ip_address"] == $this->dataRecord["ip_address"])?'SELECTED':'';
			$email_template_select .= "<option value='$rec[invoice_message_template_id]'>$rec[template_name]</option>\r\n";
		}
	}
	$app->tpl->setVar("email_template_id",$email_template_select);
	unset($rec);
	unset($records);

}


$app->tpl->setVar('page_back_link',$page_back_link);
$app->tpl->setVar('msg',$msg);
$app->tpl->setVar('error',$error);

//* load language file 
$lng_file = 'lib/lang/'.$_SESSION['s']['language'].'_send_invoice_reminder.lng';
include($lng_file);
$app->tpl->setVar($wb);

$app->tpl_defaults();
$app->tpl->pparse();


?>