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

if(CRON_RUN !== true){
	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/create_recurring_invoices.htm');
	
	$linebreak = '<br />';
} else {
	$linebreak = "\n";
}
$msg = '';
$error = '';
$is_test = (@$_POST['test'] == 1)?true:false;
$finalize_invoice = (@$_POST['finalize_invoices'] == 1)?true:false;
$send_invoice = (@$_POST['send_invoices'] == 1)?true:false;
$email_template_id = intval(@$_POST['email_template_id']);

//* Internal helper function: translate text strings into client's language
function client_lng($text, $lng = 'en') {
	global $conf;
	
	if(is_file(ISPC_LIB_PATH.'/lang/'.strtolower($lng).'.lng')) {
		include(ISPC_LIB_PATH.'/lang/'.strtolower($lng).'.lng');
	} else {
		include(ISPC_LIB_PATH.'/lang/'.$conf['language'].'.lng');
	}
		
	if(is_file(ISPC_WEB_PATH.'/billing/lib/lang/'.strtolower($lng).'.lng')) {
		include(ISPC_WEB_PATH.'/billing/lib/lang/'.strtolower($lng).'.lng');
	} else {
		include(ISPC_WEB_PATH.'/billing/lib/lang/'.$conf['language'].'.lng');
	}
			
	if(is_file(ISPC_WEB_PATH.'/billing/lib/lang/'.strtolower($lng).'_invoice_pdf.lng')) {
		include(ISPC_WEB_PATH.'/billing/lib/lang/'.strtolower($lng).'_invoice_pdf.lng');
	} else {
		include(ISPC_WEB_PATH.'/billing/lib/lang/'.$conf['language'].'_invoice_pdf.lng');
	}
	
	if(isset($wb[$text])) {
		return $wb[$text];
	} else {
		return $text;
	}
}

function finalize_invoice($invoice_id) {
	global $app, $conf;
	
	$invoice_id = intval($invoice_id);
	$invoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE invoice_id = ".$invoice_id);
	$company = $app->db->queryOneRecord("SELECT * FROM invoice_company WHERE invoice_company_id = ".$invoice['invoice_company_id']);
	
	// Assign an invoice number
	$app->uses('billing_functions');
	$app->billing_functions->assign_invoice_number($invoice, $company);
	/*
	if($invoice['invoice_number'] == '') {
				
		if($invoice['invoice_type'] == 'refund') {
			$last_refund_number = $company['last_refund_number'];
			$refund_number_prefix = $company['refund_number_prefix'];
			$new_refund_number = $last_refund_number + 1;
			$invoice_number = $refund_number_prefix.str_pad($new_refund_number, 4, "0", STR_PAD_LEFT);
			$app->db->query("UPDATE invoice_company SET last_refund_number = $new_refund_number WHERE invoice_company_id = ".$invoice['invoice_company_id']);
		} elseif($invoice['invoice_type'] == 'proforma') {
			$last_proforma_number = $company['last_proforma_number'];
			$proforma_number_prefix = $company['proforma_number_prefix'];
			$new_proforma_number = $last_proforma_number + 1;
			$invoice_number = $proforma_number_prefix.str_pad($new_proforma_number, 4, "0", STR_PAD_LEFT);
			$app->db->query("UPDATE invoice_company SET last_proforma_number = $new_proforma_number WHERE invoice_company_id = ".$invoice['invoice_company_id']);
		} else {
			$last_invoice_number = $company['last_invoice_number'];
			$invoice_number_prefix = $company['invoice_number_prefix'];
			$new_invoice_number = $last_invoice_number + 1;
			$invoice_number = $invoice_number_prefix.str_pad($new_invoice_number, 4, "0", STR_PAD_LEFT);
			$app->db->query("UPDATE invoice_company SET last_invoice_number = $new_invoice_number WHERE invoice_company_id = ".$invoice['invoice_company_id']);
		}
		$app->db->query("UPDATE invoice SET invoice_number = '$invoice_number' WHERE invoice_id = ".$invoice_id);
	}
	*/
			
	if($invoice['invoice_date'] == '' or $invoice['invoice_date'] == '0000-00-00') {
		$invoice['invoice_date'] = date('Y-m-d');
		$app->db->query("UPDATE invoice SET invoice_date = '".$invoice['invoice_date']."' WHERE invoice_id = ".$invoice_id);
	}
	
	if($invoice['idhash'] == '') {
		// Set the unique hash for the invoice
		$idhash = md5(uniqid(mt_rand(), true));
		$app->db->query("UPDATE invoice SET idhash = '$idhash' WHERE invoice_id = ".$invoice_id);
	}
			
			
	// Create the PDF invoice
	$invoice_pdf_template = $company['invoice_pdf_template'];
	$pdf_invoice_classname = 'PDFInvoice_'.$invoice_pdf_template;
	if(!class_exists('PDFInvoice_'.$invoice_pdf_template)) {
		include('templates/pdf_invoice/'.$invoice_pdf_template.'/make_pdf_invoice.php');
	}
			
	$pdf=new $pdf_invoice_classname();
	$pdf->AliasNbPages();
	$pdf->createInvoice($invoice_id);

	$pdf_content = $pdf->Output('doc.pdf','S');

	$invoice_filename = $app->billing_functions->get_invoice_filename($pdf->invoice['invoice_number'], $pdf->invoice['reminder_step']);

	file_put_contents($invoice_filename,$pdf_content);
	unset($pdf);
			
	// Calculate the invoice amount
	$tmp = $app->db->queryOneRecord("SELECT sum(quantity*price+(quantity*price*(vat/100))) as amount FROM invoice_item WHERE invoice_id = ".$invoice_id);
	$invoice_amount = $tmp['amount'];
			
	// Update the status of the invoice
	$app->db->query("UPDATE invoice SET status_printed = 'y', invoice_amount = $invoice_amount WHERE invoice_id = ".$invoice_id);

} // end finalize_invoice function

function send_invoice_by_email($invoice_id, $email_template_id) {
	global $app, $conf;
	
	$invoice_id = intval($invoice_id);
	$invoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE invoice_id = ".$invoice_id);
	
	$invoice_company_id = $invoice['invoice_company_id'];
	$client_id = $invoice['client_id'];
	
	$client = $app->db->queryOneRecord('SELECT * FROM client WHERE client_id = '.$client_id);
	$invoice_client_settings = $app->db->queryOneRecord('SELECT * FROM invoice_client_settings WHERE client_id = '.$client_id);
	$company = $app->db->queryOneRecord('SELECT * FROM invoice_company WHERE invoice_company_id = '.$invoice_company_id);
	$email_template = $app->db->queryOneRecord('SELECT * FROM invoice_message_template WHERE invoice_message_template_id = '.$email_template_id);
	$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
	
	if ($invoice_client_settings['payment_email']) {
		$to = trim($invoice_client_settings['payment_email']);
	} else {
		$to = trim($client['email']);
	}
	$subject = $email_template['subject'];
	$text_message = str_replace("\r\n","\n",$email_template['message']);
	$from_name = trim($company['sender_name']);
	$from = trim($company['sender_email']);
	if(!$from) $from = trim($company['email']);
	$bcc = trim($company['bcc_email']);
			
	$invoice = $app->db->queryOneRecord('SELECT invoice_number, idhash, invoice_amount FROM invoice WHERE invoice_id = '.$invoice_id);
	$invoice_filename = ISPC_ROOT_PATH.'/invoices/'.$invoice['invoice_number'].'.pdf';
			
	//* 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( 		'{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}' => $client['email'],
							'{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}' => $company['email'],
							'{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);
	
	//* Send the email
	$disable_invoice_sending = (isset($invoice_client_settings['no_invoice_sending']))?$invoice_client_settings['no_invoice_sending']:'n';
	if($disable_invoice_sending != 'y') {
		$app->uses('functions');
		if($to != '') $app->functions->mail($to, $subject, $text_message, $from, $invoice_filename, 'application/pdf', '', '', $bcc, $from_name);
	
		//* Insert the message into the database
		$sql = "INSERT INTO `invoice_message` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `invoice_company_id`, `client_id`, `message_template_id`, `message_type`, `subject`, `message`, `invoice_id`, `message_sent_date`, `message_status`) 
		VALUES(1, 1, 'riud', 'riud', '', ".$invoice_company_id.", ".$client_id.", ".$email_template_id.", 'invoice', '".$app->db->quote($subject)."', '".$app->db->quote($text_message)."', ".$invoice_id.", '".date('Y-m-d')."', 'sent');";
		$app->db->query($sql);
		
		// Update the status of the invoice
	$app->db->query("UPDATE invoice SET status_sent = 'y' WHERE invoice_id = ".$invoice_id);
		
		return true;
	} else {
		return false;
	}
}




// Start invoice creation
if(isset($_POST['until_date']) && $_POST['until_date'] != '') {

	if($send_invoice == true && $email_template_id == 0) {
		$error .= 'No email template selected.';
	}
	
	if($error == '' && $is_test) $msg .= 'Dry run...'.$linebreak.$linebreak;
	
	// Get all recurring invoice items that have to be billed
	if(CRON_RUN !== true){
		if(function_exists('date_parse_from_format')) {
			$date_parts = date_parse_from_format($app->lng('conf_format_dateshort'),$_POST['until_date']);
			$tmp_formatted_date = $date_parts['day'].'.'.$date_parts['month'].'.'.$date_parts['year'];
		} else {
			$tmp = strtotime($_POST['until_date']);
			$tmp_formatted_date = date('d.m.Y',$tmp);
		}
								
		$parts = explode('.',$tmp_formatted_date);
	} else {
		$parts = explode('.',$_POST['until_date']);
	}
	$now = date('Y-m-d');
	$until_date = intval($parts[2]).'-'.intval($parts[1]).'-'.intval($parts[0]);
	
	if($parts[2] < 2010 or $parts[2] > 2030) $error .= 'Invalid year'.$linebreak;
	if($parts[1] < 1 or $parts[1] > 12) $error .= 'Invalid month'.$linebreak;
	if($parts[0] < 1 or $parts[1] > 31) $error .= 'Invalid day'.$linebreak;
	
	$created_invoices = array();
	
	$records = $app->db->queryAllRecords("SELECT * FROM invoice_recurring_item WHERE next_payment_date < '$until_date' AND (end_date = '0000-00-00' OR next_payment_date < end_date) AND client_id > 0 AND active = 'y' AND (price > 0 OR setup_fee > 0 OR vat > 0)");
	if(is_array($records)) {
		foreach($records as $rec) {
			$client_id = $rec['client_id'];
			$invoice_company_id = $rec['invoice_company_id'];
			
			if ($_POST['proforma_invoice'] == 1){
				$invoice_type = 'proforma';
			} else {
				$invoice_type = 'invoice';
			}
			$invoice = $app->db->queryOneRecord("SELECT invoice_id FROM invoice WHERE client_id = $client_id AND invoice_type = '".$invoice_type."' AND status_printed = 'n'");

			if($invoice['invoice_id'] > 0) {
				$invoice_id = $invoice['invoice_id'];
			} else {
				// There is no invoice draft, so we have to create one.
				// $client = $app->db->queryOneRecord("SELECT * FROM client, invoice_client_settings WHERE invoice_client_settings.client_id = client.client_id AND client.client_id = $client_id");
				$client = $app->db->queryOneRecord("SELECT client.*, invoice_client_settings.payment_email, invoice_client_settings.payment_terms,invoice_client_settings.payment_gateway, invoice_client_settings.no_invoice_sending FROM client LEFT JOIN invoice_client_settings ON invoice_client_settings.client_id = client.client_id WHERE client.client_id = $client_id");
				
				$sys_userid = $client['sys_userid'];
				$sys_groupid = $client['sys_groupid'];
				$company_name = $app->db->quote($client['company_name']);
				$contact_name = $app->db->quote($client['contact_name']);
				$street = $app->db->quote($client['street']);
				$zip = $app->db->quote($client['zip']);
				$city = $app->db->quote($client['city']);
				$state = $app->db->quote($client['state']);
				$country = $app->db->quote($client['country']);
				$email = $app->db->quote($client['email']);
				$invoice_date = date('Y-m-d');
				$vat_id = $app->db->quote($client['vat_id']);
				$idhash = md5(uniqid(mt_rand(), true));
				
				if(isset($client['invoice_company_id']) && $client['invoice_company_id'] > 0) $invoice_company_id = $client['invoice_company_id'];
				if(isset($client['payment_email']) && $client['payment_email'] != '') $email = $client['payment_email'];
				
				$payment_terms = (!empty($client['payment_terms']) && $client['payment_terms'] != 'NULL')?$client['payment_terms']:1;
				$payment_gateway = (!empty($client['payment_gateway']) && $client['payment_gateway'] != 'NULL')?$client['payment_gateway']:'none';
				$invoice_type = (isset($_POST['proforma_invoice']) && $_POST['proforma_invoice'] == 1)?'proforma':'invoice';
				
				$sql = "INSERT INTO invoice (sys_userid,sys_groupid,sys_perm_user,sys_perm_group,sys_perm_other,invoice_type,invoice_company_id,client_id,company_name,contact_name,street,zip,city,state,country,email,invoice_date,vat_id,payment_terms,payment_gateway,idhash) VALUES ('$sys_userid','$sys_groupid','riud','riud','','$invoice_type','$invoice_company_id','$client_id','$company_name','$contact_name','$street','$zip','$city','$state','$country','$email','$invoice_date','$vat_id','$payment_terms','$payment_gateway','$idhash')";
				
				if($error == '') {
					if($is_test == false) {
						$app->db->query($sql);
						$invoice_id = $app->db->insertID();
					} else {
						$invoice_id = 0;
					}
					$msg .= "Started new invoice for $company_name :: $contact_name.".$linebreak;
				}
			}
			
			// New invoice items
			$invoice_item_template_id = 0;
			$price = $app->db->quote($rec['price']);
			$vat = $app->db->quote($rec['vat']);
			$quantity = $app->db->quote($rec['quantity']);
			$description  = $app->db->quote($rec['description']);
			list($jahr,$monat,$tag) = explode('-',$rec['next_payment_date']);
			$date_from_last_tstamp = mktime(0, 0, 0, $monat-$rec['recur_months'], $tag,   $jahr);
			$date_from_tstamp = mktime(0, 0, 0, $monat, $tag, $jahr);
			$date_from_tstamp_minus_one_day = mktime(0, 0, 0, $monat, $tag-1, $jahr);
			$date_to_tstamp = mktime(0, 0, 0, $monat+$rec['recur_months'], $tag,   $jahr);
			$date_to_tstamp_minus_one_day = mktime(0, 0, 0, $monat+$rec['recur_months'], $tag-1, $jahr);
		
			// Replace strings in description
			$description = str_replace('{ITEMNAME}',$rec['name'],$description);
			if($rec['advance_payment'] == 'y') {
				$description = str_replace('{FROMDATE}',date(client_lng('conf_format_dateshort', $client['language']),$date_from_tstamp),$description);
				$description = str_replace('{TODATE}',date(client_lng('conf_format_dateshort', $client['language']),$date_to_tstamp_minus_one_day),$description);
			} else {
				$description = str_replace('{FROMDATE}',date(client_lng('conf_format_dateshort', $client['language']),$date_from_last_tstamp),$description);
				$description = str_replace('{TODATE}',date(client_lng('conf_format_dateshort', $client['language']),$date_from_tstamp_minus_one_day),$description);
			}
			
			
			// Insert setup fee into the invoice.
			if($rec['next_payment_date'] == $rec['start_date'] && $rec['setup_fee'] != 0){
				$setup_fee = $app->db->quote($rec['setup_fee']);
				$setup_fee_description = client_lng('setup_fee_txt', $client['language']).' '.$rec['name'];
				$sql = "INSERT INTO invoice_item (invoice_id,invoice_item_template_id,quantity,price,vat,description) VALUES ($invoice_id,$invoice_item_template_id,'1','$setup_fee','$vat','$setup_fee_description')";
				if($is_test == false && $error == '') $app->db->query($sql);
				//die($sql);
			}
			
		
			// Insert a new item into the invoice.
			$sql = "INSERT INTO invoice_item (invoice_id,invoice_item_template_id,quantity,price,vat,description) VALUES ($invoice_id,$invoice_item_template_id,'$quantity','$price','$vat','$description')";
			if($is_test == false && $error == '') $app->db->query($sql);
			//die($sql);
		
			// Update the next_payment_date date of the recurring item
			$sql = "UPDATE invoice_recurring_item SET next_payment_date = '".date('Y-m-d',$date_to_tstamp)."' WHERE invoice_recurring_item_id = ".$rec['invoice_recurring_item_id'];
			if($error == '') {
				if($is_test == false)  $app->db->query($sql);
				$msg .= "Added item ".$rec['name']." of type ".$rec['type']." to the invoice draft #$invoice_id.".$linebreak;
			}
		
			//* add invoice ID to the $created_invoices array, so that we can process them later
			if(!in_array($invoice_id,$created_invoices)) $created_invoices[] = $invoice_id;
		
		}
	}
	if($is_test == false) $app->db->query("UPDATE invoice_recurring_item SET next_payment_date = DATE_ADD(next_payment_date, INTERVAL recur_months MONTH) WHERE next_payment_date < '$until_date' AND (end_date = '0000-00-00' OR next_payment_date < end_date) AND client_id > 0 AND active = 'y' AND price = 0 AND setup_fee = 0 AND vat = 0");
    
    
	//*Finalize and send invoices
	if(count($created_invoices) > 0) {
		foreach($created_invoices as $invoice_id) {
			if($invoice_id > 0) {
				// Finalize the invoice
				if($error == '' && $finalize_invoice == true) {
					if($is_test == false) finalize_invoice($invoice_id);
					$msg .= "Finalized the invoice draft #$invoice_id.".$linebreak;
				}
		
				// Send invoice by email
				if($error == '' && $send_invoice == true) {
					if($is_test == false)  $returnvar = send_invoice_by_email($invoice_id, $email_template_id);
					if($returnvar == true) $msg .= "Invoice sent by email #$invoice_id.".$linebreak;
				}
			}
		}
	}
	
	if($error == '') $msg .= 'Finished.';

}


if(CRON_RUN !== true){
	$app->tpl->setVar('msg',$msg);
	$app->tpl->setVar('error',$error);

	if(isset($_POST['until_date']) && $_POST['until_date'] != '') {
		$app->tpl->setVar('until_date',$_POST['until_date']);
	} else {
		$app->tpl->setVar('until_date',date($app->lng('conf_format_dateshort')));
	}

	// Datepicker
	$date_format = $app->lng('conf_format_dateshort');
	$trans = array("d" => "dd", "m" => "mm", "Y" => "yy");
	$date_format = strtr($date_format, $trans);

	$app->tpl->setVar("date_format", $date_format);	
		
	$app->tpl->setVar("daynamesmin_su", $app->lng('daynamesmin_su'));
	$app->tpl->setVar("daynamesmin_mo", $app->lng('daynamesmin_mo'));
	$app->tpl->setVar("daynamesmin_tu", $app->lng('daynamesmin_tu'));
	$app->tpl->setVar("daynamesmin_we", $app->lng('daynamesmin_we'));
	$app->tpl->setVar("daynamesmin_th", $app->lng('daynamesmin_th'));
	$app->tpl->setVar("daynamesmin_fr", $app->lng('daynamesmin_fr'));
	$app->tpl->setVar("daynamesmin_sa", $app->lng('daynamesmin_sa'));
		
	$app->tpl->setVar("daynames_sunday", $app->lng('daynames_sunday'));
	$app->tpl->setVar("daynames_monday", $app->lng('daynames_monday'));
	$app->tpl->setVar("daynames_tuesday", $app->lng('daynames_tuesday'));
	$app->tpl->setVar("daynames_wednesday", $app->lng('daynames_wednesday'));
	$app->tpl->setVar("daynames_thursday", $app->lng('daynames_thursday'));
	$app->tpl->setVar("daynames_friday", $app->lng('daynames_friday'));
	$app->tpl->setVar("daynames_saturday", $app->lng('daynames_saturday'));
		
	$app->tpl->setVar("monthnamesshort_jan", $app->lng('monthnamesshort_jan'));
	$app->tpl->setVar("monthnamesshort_feb", $app->lng('monthnamesshort_feb'));
	$app->tpl->setVar("monthnamesshort_mar", $app->lng('monthnamesshort_mar'));
	$app->tpl->setVar("monthnamesshort_apr", $app->lng('monthnamesshort_apr'));
	$app->tpl->setVar("monthnamesshort_may", $app->lng('monthnamesshort_may'));
	$app->tpl->setVar("monthnamesshort_jun", $app->lng('monthnamesshort_jun'));
	$app->tpl->setVar("monthnamesshort_jul", $app->lng('monthnamesshort_jul'));
	$app->tpl->setVar("monthnamesshort_aug", $app->lng('monthnamesshort_aug'));
	$app->tpl->setVar("monthnamesshort_sep", $app->lng('monthnamesshort_sep'));
	$app->tpl->setVar("monthnamesshort_oct", $app->lng('monthnamesshort_oct'));
	$app->tpl->setVar("monthnamesshort_nov", $app->lng('monthnamesshort_nov'));
	$app->tpl->setVar("monthnamesshort_dec", $app->lng('monthnamesshort_dec'));		
		
	$app->tpl->setVar("datepicker_nextText", $app->lng('datepicker_nextText'));
	$app->tpl->setVar("datepicker_prevText", $app->lng('datepicker_prevText'));

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

	//* Load email templates
	$tmps = $app->db->queryAllRecords("SELECT invoice_message_template_id, template_name FROM invoice_message_template WHERE template_type = 'invoice' ORDER BY template_name");
	$email_template = '<option value="0">'.$wb['email_template_txt'].'</option>';
	if(is_array($tmps)) {
		foreach($tmps as $tmp) {
			$selected = ($tmp['invoice_message_template_id'] == $email_template_id)?'SELECTED':'';
			$email_template .= '<option value="'.$tmp['invoice_message_template_id'].'" '.$selected.'>'.$tmp['template_name'].'</option>';
		}
	}
	$app->tpl->setVar('email_template',$email_template);

	$app->tpl_defaults();
	$app->tpl->pparse();
} else {
	if($error == ''){
		echo $msg.$linebreak;
	} else {
		echo $error.$linebreak;
	}
}

?>