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


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

$tform_def_file = "form/invoice_recurring_item.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';
		}
		parent::onSubmit();
	}

	function onShowNew() {
		global $app;
		
		if($app->tform->errorMessage == '') {
			$record = array();
            $record = $app->tform->getHTML($record, $app->tform->formDef['tab_default'],'NEW');
			
		} 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') {
					if($_POST['invoice_item_template_id'] > 0) {
						$tmp = $app->db->queryOneRecord("SELECT * FROM invoice_item_template WHERE invoice_item_template_id = ".intval($_POST['invoice_item_template_id']));
						$record['description'] = $tmp['description'];
						$record['price'] = $app->functions->currency_format($tmp['price']);
						$record['vat'] = $tmp['vat'];
						$record['recur_months'] = $tmp['recur_months'];
					} else {
						$record['description'] = '';
						$record['price'] = $app->functions->currency_format(0);
						$record['vat'] = '';
						$record['recur_months'] = 1;
					}
					$record['error'] = '';
					$app->tpl->setVar($record);
				}
				
				$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");
				$app->tpl->setVar('date_format_txt',$invoice_settings['date_format']);
				$app->tpl->setVar('currency_txt',$invoice_settings['currency']);

                // Template parsen
                $app->tpl->pparse();
        }

}

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

?>