<?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');

$action = (isset($_POST['action']) && $_POST['action'] != '')?$_POST['action']:'show';
$invoice_id = intval($_REQUEST['id']);
$email_template_id_send = intval($_REQUEST['email_template_id_send']);
$email_template_id_reminder = intval($_REQUEST['email_template_id_reminder']);
$error_msg = '';
$notify_msg = '';

if($invoice_id == 0) die('Invalid invoice ID');

//* Show the action select page
if($action == 'show') {
	//* Loading classes
	$app->uses('tpl');

	$app->tpl->newTemplate('form.tpl.htm');
	$app->tpl->setInclude('content_tpl', 'templates/invoice_action.htm');
	
	//* load language file 
	$lng_file = 'lib/lang/'.$_SESSION['s']['language'].'_invoice_action.lng';
	include_once($lng_file);
	$app->tpl->setVar($wb);
	
	//* Get the invoice record
	$invoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE invoice_id = ".intval($invoice_id));
	
	//* Insert send email template list
	$sql = "SELECT invoice_message_template_id, template_name FROM invoice_message_template WHERE template_type = 'invoice'";
	$records = $app->db->queryAllRecords($sql);
	$email_template_select = "<option value='0'>- ".$wb['no_email_template_txt']." -</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("send_email_template",$email_template_select);
	unset($rec);
	unset($records);
	
	//* 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'>- ".$wb['no_email_template_txt']." -</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("reminder_email_template",$email_template_select);
	unset($rec);
	unset($records);

	
	$app->tpl->setVar('id',$invoice_id);
	$app->tpl->setVar('invoice_type',$invoice['invoice_type']);
	
	$app->tpl_defaults();
	$app->tpl->pparse();
	
} elseif ($action == 'duplicate') {
	
	//* Duplicate the invoice itself
	$invoice = $app->db->queryOneRecord('SELECT * FROM invoice WHERE invoice_id = '.$invoice_id);
	if(is_array($invoice)) {
		unset($invoice['invoice_id']);
		$invoice['invoice_number'] = '';
		$invoice['status_printed'] = 'n';
		$invoice['status_sent'] = 'n';
		$invoice['status_paid'] = 'n';
		$invoice['invoice_date'] = date('Y-m-d');
		$sql = _get_sql_insert('invoice',$invoice);
		$app->db->query($sql);
		$new_invoice_id = $app->db->insertID();
	
		//* Add duplicates for all records of the old invoice to the new invoice
		$invoice_items = $app->db->queryAllRecords('SELECT * FROM invoice_item WHERE invoice_id = '.$invoice_id);
		if(is_array($invoice_items)) {
			foreach($invoice_items as $invoice_item) {
				unset($invoice_item['invoice_item_id']);
				$invoice_item['invoice_id'] = $new_invoice_id;
				$sql = _get_sql_insert('invoice_item',$invoice_item);
				$app->db->query($sql);
			}
		}
		
		//* go to the newly created invoice
		echo 'HEADER_REDIRECT:billing/invoice_edit.php?id='.$new_invoice_id;
		exit;
	}
	
} elseif ($action == 'proforma_to_invoice') {
	
	//* Duplicate the proforma invoice and save copy as invoice
	$invoice = $app->db->queryOneRecord('SELECT * FROM invoice WHERE invoice_id = '.$invoice_id);
	if(is_array($invoice)) {
		unset($invoice['invoice_id']);
		$invoice['invoice_type'] = 'invoice';
		$invoice['invoice_number'] = '';
		$invoice['status_printed'] = 'n';
		$invoice['status_sent'] = 'n';
		$invoice['status_paid'] = 'n';
		$invoice['invoice_date'] = date('Y-m-d');
		$sql = _get_sql_insert('invoice',$invoice);
		$app->db->query($sql);
		$new_invoice_id = $app->db->insertID();
	
		//* Add duplicates for all records of the old invoice to the new invoice
		$invoice_items = $app->db->queryAllRecords('SELECT * FROM invoice_item WHERE invoice_id = '.$invoice_id);
		if(is_array($invoice_items)) {
			foreach($invoice_items as $invoice_item) {
				unset($invoice_item['invoice_item_id']);
				$invoice_item['invoice_id'] = $new_invoice_id;
				$sql = _get_sql_insert('invoice_item',$invoice_item);
				$app->db->query($sql);
			}
		}
		
		//* go to the newly created invoice
		echo 'HEADER_REDIRECT:billing/invoice_edit.php?id='.$new_invoice_id;
		exit;
	}
	
} elseif ($action == 'send') {
	
	$invoice = $app->db->queryOneRecord('SELECT * FROM invoice WHERE invoice_id = '.$invoice_id);
	$client_id = $invoice['client_id'];

	//* go to the message sending form
	echo 'HEADER_REDIRECT:billing/invoice_message_edit.php?action=loadtemplate&type=invoice&client_id='.$client_id.'&invoice_id='.$invoice_id.'&message_template_id='.$email_template_id_send;
	exit;

} elseif ($action == 'reminder') {
	
	$invoice = $app->db->queryOneRecord('SELECT * FROM invoice WHERE invoice_id = '.$invoice_id);
	$client_id = $invoice['client_id'];
	
	//* go to the message sending form
	echo 'HEADER_REDIRECT:billing/invoice_message_edit.php?action=loadtemplate&type=reminder&client_id='.$client_id.'&invoice_id='.$invoice_id.'&message_template_id='.$email_template_id_reminder;
	exit;

} elseif ($action == 'refund') {
	
	//* Create a refund based on the invoice
	$invoice = $app->db->queryOneRecord('SELECT * FROM invoice WHERE invoice_id = '.$invoice_id);
	if(is_array($invoice)) {
		unset($invoice['invoice_id']);
		$invoice['invoice_number'] = '';
		$invoice['invoice_type'] = 'refund';
		$invoice['invoice_amount'] = $invoice['invoice_amount'] * -1;
		$invoice['status_printed'] = 'n';
		$invoice['status_sent'] = 'n';
		$invoice['status_paid'] = 'n';
		$invoice['invoice_date'] = date('Y-m-d');
		$sql = _get_sql_insert('invoice',$invoice);
		$app->db->query($sql);
		$new_invoice_id = $app->db->insertID();
	
		//* Add duplicates for all records of the old invoice to the new credit memo and invert the price
		$invoice_items = $app->db->queryAllRecords('SELECT * FROM invoice_item WHERE invoice_id = '.$invoice_id);
		if(is_array($invoice_items)) {
			foreach($invoice_items as $invoice_item) {
				unset($invoice_item['invoice_item_id']);
				$invoice_item['invoice_id'] = $new_invoice_id;
				$invoice_item['price'] = $invoice_item['price'] * -1;
				$sql = _get_sql_insert('invoice_item',$invoice_item);
				$app->db->query($sql);
			}
		}
		
		//* go to the newly created invoice
		echo 'HEADER_REDIRECT:billing/invoice_edit.php?id='.$new_invoice_id;
		exit;
	}
	
	
} else {
	$error_msg = $app->lng('Unknown action');
	$app->error($error_msg);
}

// Helper function to create sql insert statements based on a array
function _get_sql_insert($table_name,$fields) {
	global $app;
	
	$key_string = '';
	$value_string = '';
	
	foreach($fields as $key => $val) {
		$key_string .= $key.',';
		$value_string .= "'".$app->db->quote($val)."',";
	}
	
	$key_string = substr($key_string,0,-1);
	$value_string = substr($value_string,0,-1);
	
	$sql = 'INSERT INTO '.$table_name.' ('.$key_string.') VALUES ('.$value_string.')';
	
	return $sql;
}


?>