<?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 = $app->lng('conf_format_dateshort');

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(isset($_GET['action']) && $_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;
		
		$tmp = $app->db->queryOneRecord("SELECT * FROM client WHERE 1 ORDER BY company_name,contact_name LIMIT 0,1");
		
		if($app->tform->errorMessage == '') {
			$record = array();
			
			$invoice_client_settings = $app->db->queryOneRecord("SELECT * FROM invoice_client_settings WHERE client_id = ".intval($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);
			}
			
			$app->tform->formDef['tabs']['address']['fields']['country']['default'] = strtoupper($tmp['country']);
			
            $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 = ".intval($_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'];
				$_POST['country'] = strtoupper($lastinvoice['country']);
				unset($lastinvoice);
			}
			
			$client = $app->db->queryOneRecord("SELECT * FROM client WHERE client_id = ".intval($_POST['client_id']));
			if($client['country'] != '') $_POST['country'] = strtoupper($client['country']);
			
			$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(isset($_GET['action']) && $_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'];
			$tmp_record = $app->tform->getHTML($app->tform->encode($tmp,$this->active_tab),$this->active_tab,'EDIT');
			$record['country'] = $tmp_record['country'];
			unset($tmp_record);
			
			$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']);
		
		// 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'));
		
		
		switch ($_REQUEST['list']) {
			case 'proforma':
				$app->tpl->setVar("cancel_url", 'billing/proforma_list.php');
				$app->tpl->setVar("form_hint", $app->lng('proforma_invoice_txt'));
				$app->tpl->setVar("btn_save_finalize_txt", $app->lng('btn_save_finalize_proforma_txt'));
				break;
			case 'refund':
				$app->tpl->setVar("cancel_url", 'billing/refund_list.php');
				$app->tpl->setVar("form_hint", $app->lng('refund_txt'));
				$app->tpl->setVar("btn_save_finalize_txt", $app->lng('btn_save_finalize_refund_txt'));
				break;
			case 'reminder':
				$app->tpl->setVar("cancel_url", 'billing/reminder_list.php');
				$app->tpl->setVar("form_hint", $app->lng('reminder_txt'));
				$app->tpl->setVar("btn_save_finalize_txt", $app->lng('btn_save_finalize_reminder_txt'));
				break;
			case 'invoice_draft':
				$app->tpl->setVar("cancel_url", 'billing/invoice_draft_list.php');
				$app->tpl->setVar("form_hint", $app->lng('invoice_draft_txt'));
				break;
			default:
				$app->tpl->setVar("cancel_url", 'billing/invoice_list.php');
		}
		$app->tpl->setVar("list", $_REQUEST['list']);

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

		//* ensure that we return to the correct list
		if($_REQUEST["next_tab"] == '') {
			if($this->dataRecord['invoice_type'] == 'refund') $_SESSION["s"]["form"]["return_to_url"] = 'refund_list.php';
			if($this->dataRecord['invoice_type'] == 'reminder') $_SESSION["s"]["form"]["return_to_url"] = 'reminder_list.php';
			if($this->dataRecord['invoice_type'] == 'proforma') $_SESSION["s"]["form"]["return_to_url"] = 'proforma_list.php';
			if($this->dataRecord['invoice_type'] == 'invoice' && $this->dataRecord['invoice_number'] == '') $_SESSION["s"]["form"]["return_to_url"] = 'invoice_draft_list.php';
		}	
	}
	
    function onBeforeUpdate() {
        global $app,$conf;
        
        $invoice = $app->tform->getDataRecord($this->id);
        
        if(!$invoice['payment_date'] || $invoice['payment_date'] == '0000-00-00' && $this->dataRecord['status_paid'] == 'y' && $invoice['status_paid'] != 'y') {
            $this->dataRecord['payment_date'] = date($app->lng('conf_format_dateshort'));
        }
        
        parent::onBeforeUpdate();
    }

	function onAfterUpdate() {
		global $app,$conf;
		
		$invoice = $app->tform->getDataRecord($this->id);
		
		if(isset($_GET['action']) && $_GET['action'] == 'finalize_invoice') {
		
			// 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'];
			// Don't finalize if invoice amount == 0
			if($invoice_amount == 0){
				$app->error($app->lng('error_total_equals_zero_txt'));
			}
			
			// Get the company record
			$company = $app->db->queryOneRecord("SELECT * FROM invoice_company WHERE invoice_company_id = ".$invoice['invoice_company_id']);
			
			// Assign an invoice number
			$app->uses('billing_functions');
			$invoice['invoice_number'] = $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 = ".$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');
			
			$invoice_filename = $app->billing_functions->get_invoice_filename($pdf->invoice['invoice_number'], $invoice['reminder_step']);
			
			if(is_file($invoice_filename)) unlink($invoice_filename);
			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);
			
		}
        
        if($invoice['invoice_type'] == 'reminder') {
            // set status of matching invoice
            $app->db->query("UPDATE invoice SET status_paid = '" . $app->db->quote($invoice['status_paid']) . "', status_refunded = '" . $app->db->quote($invoice['status_refunded']) . "' WHERE invoice_number = '" . $app->db->quote($invoice['invoice_number']) . "'");
        } else {
            $app->db->query("UPDATE invoice SET status_paid = '" . $app->db->quote($invoice['status_paid']) . "', status_refunded = '" . $app->db->quote($invoice['status_refunded']) . "' WHERE invoice_number = '" . $app->db->quote($invoice['invoice_number']) . "' AND invoice_type = 'reminder'");
        }
		
		//* 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'] == 'reminder') $_SESSION["s"]["form"]["return_to_url"] = 'reminder_list.php';
			if($invoice['invoice_type'] == 'proforma') $_SESSION["s"]["form"]["return_to_url"] = 'proforma_list.php';
			if($invoice['invoice_type'] == 'invoice' && $invoice['invoice_number'] == '') $_SESSION["s"]["form"]["return_to_url"] = 'invoice_draft_list.php';
		}
	}

}

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

?>