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


/******************************************
* Begin Form configuration
******************************************/

$tform_def_file = "form/invoice.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');

$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
$app->tform->dateformat = $invoice_settings['date_format'];

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';
			
			//* Load settings from last invoice
			$lastinvoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE client_id = ".intval($_POST['client_id'])." ORDER BY invoice_id DESC LIMIT 0,1");
			$_POST['payment_terms'] = $lastinvoice['payment_terms'];
			$_POST['payment_gateway'] = $lastinvoice['payment_gateway'];
			unset($lastinvoice);
		}
		parent::onSubmit();
	}
	
	function onShowNew() {
		global $app;
		
		if($app->tform->errorMessage == '') {
			$record = array();
			
			$tmp = $app->db->queryOneRecord("SELECT * FROM client WHERE 1 ORDER BY company_name,contact_name LIMIT 0,1");
			
			$invoice_client_settings = $app->db->queryOneRecord("SELECT * FROM invoice_client_settings WHERE client_id = ".$tmp['client_id']);
			if(count($invoice_client_settings) > 0) {
				$app->tform->formDef['tabs']['address']['fields']['payment_terms']['default'] = $invoice_client_settings['payment_terms'];
				$app->tform->formDef['tabs']['address']['fields']['payment_gateway']['default'] = $invoice_client_settings['payment_gateway'];
				$app->tform->formDef['tabs']['address']['fields']['invoice_company_id']['default'] = $invoice_client_settings['invoice_company_id'];
			} else { 
			//* Try to load settings from last invoice
				$lastinvoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE client_id = ".intval($tmp['client_id'])." ORDER BY invoice_id DESC LIMIT 0,1");
				$app->tform->formDef['tabs']['address']['fields']['payment_terms']['default'] = $lastinvoice['payment_terms'];
				$app->tform->formDef['tabs']['address']['fields']['payment_gateway']['default'] = $lastinvoice['payment_gateway'];
				$app->tform->formDef['tabs']['address']['fields']['invoice_company_id']['default'] = $invoice_client_settings['invoice_company_id'];
				unset($lastinvoice);
			}
			
            $record = $app->tform->getHTML($record, $app->tform->formDef['tab_default'],'NEW');
			$record['company_name'] = $tmp['company_name'];
			$record['contact_name'] = $tmp['contact_name'];
			$record['street'] = $tmp['street'];
			$record['zip'] = $tmp['zip'];
			$record['city'] = $tmp['city'];
			$record['country'] = $tmp['country'];
			$record['state'] = $tmp['state'];
			$record['email'] = $tmp['email'];
			$record['vat_id'] = $tmp['vat_id'];
			if($invoice_client_settings['payment_email'] != '') $email = $invoice_client_settings['payment_email'];
		
		} elseif($_GET['action'] == 'loadtemplate') {
			$invoice_client_settings = $app->db->queryOneRecord("SELECT * FROM invoice_client_settings WHERE client_id = ".$_POST['client_id']);
			if(count($invoice_client_settings) > 0) {
				$_POST['payment_terms'] = $invoice_client_settings['payment_terms'];
				$_POST['payment_gateway'] = $invoice_client_settings['payment_gateway'];
				//$_POST['invoice_company_id'] = $invoice_client_settings['invoice_company_id'];
			} else { 
			//* Try to load settings from last invoice
				$lastinvoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE client_id = ".intval($tmp['client_id'])." ORDER BY invoice_id DESC LIMIT 0,1");
				$_POST['payment_terms'] = $lastinvoice['payment_terms'];
				$_POST['payment_gateway'] = $lastinvoice['payment_gateway'];
				//$_POST['invoice_company_id'] = $invoice_client_settings['invoice_company_id'];
				unset($lastinvoice);
			}
			
			$record = $app->tform->getHTML($app->tform->encode($_POST,$this->active_tab),$this->active_tab,'EDIT');
		} 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;
				
		// 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') {
			$tmp = $app->db->queryOneRecord("SELECT * FROM client WHERE client_id = ".intval($_POST['client_id']));
			$record['company_name'] = $tmp['company_name'];
			$record['contact_name'] = $tmp['contact_name'];
			$record['street'] = $tmp['street'];
			$record['zip'] = $tmp['zip'];
			$record['city'] = $tmp['city'];
			$record['country'] = $tmp['country'];
			$record['state'] = $tmp['state'];
			$record['email'] = $tmp['email'];
			$record['vat_id'] = $tmp['vat_id'];
			$record['error'] = '';
			$app->tpl->setVar($record);
		}
		
		$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
		$app->tpl->setVar('currency_txt',$invoice_settings['currency']);

		 // Template parsen
		$app->tpl->pparse();
	}
	
	function onAfterInsert() {
		global $app,$conf;
		
		// Set the unique hash for the invoice
		$idhash = md5(uniqid(mt_rand(), true));
		$app->db->query("UPDATE invoice SET idhash = '$idhash' WHERE invoice_id = ".$this->id);
		
	}
	

	function onAfterUpdate() {
		global $app,$conf;
		
		$invoice = $app->tform->getDataRecord($this->id);
		
		if(isset($_GET['action']) && $_GET['action'] == 'finalize_invoice') {
			// Get the company record
			$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 = ".$this->id);
			}
			
			if($invoice['idhash'] == '') {
				$idhash = md5(uniqid(mt_rand(), true));
				$app->db->query("UPDATE invoice SET idhash = '$idhash' WHERE invoice_id = ".$this->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 = ".$this->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($this->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 amount
			$tmp = $app->db->queryOneRecord("SELECT sum(quantity*price+(quantity*price*(vat/100))) as amount FROM invoice_item WHERE invoice_id = ".$this->id);
			$invoice_amount = $tmp['amount'];
			
			// Update the tstaus of the invoice
			$app->db->query("UPDATE invoice SET status_printed = 'y', invoice_amount = $invoice_amount WHERE invoice_id = ".$this->id);
			
		}
		
		//* ensure that we return to the correct list
		if($_REQUEST["next_tab"] == '') {
			if($invoice['invoice_type'] == 'refund') $_SESSION["s"]["form"]["return_to_url"] = 'refund_list.php';
			if($invoice['invoice_type'] == 'proforma') $_SESSION["s"]["form"]["return_to_url"] = 'proforma_list.php';
		}
	}

}

$page = new page_action;
$page->onLoad();

?>