<?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/create_recurring_invoices.htm');
$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']);

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 a invoice number
	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->createInvoice($invoice_id);

	$pdf_content = $pdf->Output('doc.pdf','S');
	
	$app->uses('billing_functions');
	$invoice_filename = $app->billing_functions->get_invoice_filename($pdf->invoice['invoice_number']);

	file_put_contents($invoice_filename,$pdf_content);
	unset($pdf);
			
	// Calculate the invoice amont
	$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 email,contact_name,company_name 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 email 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 = $invoice_client_settings['payment_email'];
	} else {
		$to = $client['email'];
	}
	$subject = $email_template['subject'];
	$text_message = str_replace("\r\n","\n",$email_template['message']);
	$from = $company['email'];
			
	$invoice = $app->db->queryOneRecord('SELECT invoice_number,idhash 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);
	
	//* 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($client['email'] != '') $app->functions->mail($to, $subject, $text_message, $from, $invoice_filename);
	
		//* 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...<br /><br />';
	
	// Get all recurring invoice items that have to be billed
	$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<br />';
	if($parts[1] < 1 or $parts[1] > 12) $error .= 'Invalid month<br />';
	if($parts[0] < 1 or $parts[1] > 31) $error .= 'Invalid day<br />';
	
	$created_invoices = array();
	
	$records = $app->db->queryAllRecords("SELECT * FROM invoice_recurring_item WHERE next_payment_date < '$until_date' AND client_id > 0 AND active = 'y'");
	if(is_array($records)) {
		foreach($records as $rec) {
			$client_id = $rec['client_id'];
			$invoice_company_id = $rec['invoice_company_id'];
			$invoice = $app->db->queryOneRecord("SELECT invoice_id FROM invoice WHERE client_id = $client_id AND invoice_type = 'invoice' 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.<br />";
				}
			}
			
			// 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('d.m.Y',$date_from_tstamp),$description);
				$description = str_replace('{TODATE}',date('d.m.Y',$date_to_tstamp_minus_one_day),$description);
			} else {
				$description = str_replace('{FROMDATE}',date('d.m.Y',$date_from_last_tstamp),$description);
				$description = str_replace('{TODATE}',date('d.m.Y',$date_from_tstamp_minus_one_day),$description);
			}
		
			// 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.<br />";
			}
		
			//* 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;
		
		}
	}
	
	//*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.<br />";
				}
		
				// 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 send by email #$invoice_id.<br />";
				}
			}
		}
	}
	
	if($error == '') $msg .= 'Finished.';

}



$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('d.m.Y'));
}

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

//* 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();


?>