<?php
/**
 * AgileBill - Open Billing Software
 *
 * This body of work is free software; you can redistribute it and/or
 * modify it under the terms of the Open AgileBill License
 * License as published at http://www.agileco.com/agilebill/license1-4.txt
 *
 * Originally authored by Tony Landis, AgileBill LLC
 *
 * Recent modifications by Deon George
 *
 * @author Deon George <deonATleenooksDOTnet>
 * @copyright 2009 Deon George
 * @link http://osb.leenooks.net
 *
 * @link http://www.agileco.com/
 * @copyright 2004-2008 Agileco, LLC.
 * @license http://www.agileco.com/agilebill/license1-4.txt
 * @author Tony Landis <tony@agileco.com>
 * @package AgileBill
 * @subpackage Core
 */

/**
 * The main AgileBill CORE Database ADD Method
 *
 * @uses CORE_validate
 * @uses CORE_static_var
 * @uses CORE_trigger
 */

function CORE_database_add($VAR,$construct,$type) {
	global $C_translate;

	# Temp during code rework
	if (! is_array($construct->val_error))
		$construct->val_error = array();

	# Set the field list for this method
	$arr = $construct->method[$type];

	# Define the validation class
	include_once(PATH_CORE.'validate.inc.php');
	$validate = new CORE_validate($VAR,$construct->module);
	$construct->validated = true;

	# Quick Validation to see if we have too many variables.
	foreach ($VAR as $field_name => $value)
		if (preg_match("/^{$construct->module}_/",$field_name))
			if (! in_array(preg_replace("/^{$construct->module}_/",'',$field_name),$arr))
				array_push($construct->val_error,array(
					'field'=>sprintf('%s_%s',$construct->table,$field_name),
					'field_trans'=>$field_name,
					'error'=>sprintf('WARNING: Variable passed to %s but it will be ignored.',__METHOD__),
					'method'=>sprintf('%s:%s(%s)',__FILE__,__METHOD__,__LINE__)
				));

	# Quick Validation to see if we are missing variables.
	foreach ($construct->method[$type] as $field_name) {
		$field_var = sprintf('%s_%s',$construct->module,$field_name);

		if (! array_key_exists($field_var,$VAR))
			array_push($construct->val_error,array(
				'field'=>$field_var,
				'field_trans'=>$field_name,
				'error'=>sprintf('WARNING: Variable NOT passed to %s.',__METHOD__),
				'method'=>sprintf('%s:%s(%s)',__FILE__,__METHOD__,__LINE__)
			));
	}

	# Perform each field validation
	while (list($key,$field_name) = each($arr)) {
		# Get the field value
		$field_var = sprintf('%s_%s',$construct->module,$field_name);

		# Check if this value is unique
		if (isset($construct->field[$field_name]['unique']) && isset($VAR[$field_var])) {
			if (! $validate->validate_unique($construct->table,$field_name,'record_id',$VAR[$field_var])) {
				$construct->validated = false;

				array_push($construct->val_error,array(
					'field'=>sprintf('%s_%s',$construct->module,$field_name),
					'field_trans'=>$C_translate->translate('field_'.$field_name,$construct->module,''),
					'error'=>$C_translate->translate('validate_unique','',''),
					'method'=>sprintf('%s:%s(%s)',__FILE__,__METHOD__,__LINE__)
				));
			}
		}

		# Check if the submitted value meets the specifed requirements
		if (isset($construct->field[$field_name]['validate'])) {
			if (isset($VAR[$field_var]) && ($VAR[$field_var] != '')) {
				if (! $validate->validate($field_name,$construct->field[$field_name],$VAR[$field_var],$construct->field[$field_name]['validate'])) {
					$construct->validated = false;

					array_push($construct->val_error,array(
						'field'=>sprintf('%s_%s',$construct->module,$field_name),
						'field_trans'=>$C_translate->translate('field_'.$field_name,$construct->module,''),
						'error'=>$validate->error[$field_name],
						'method'=>sprintf('%s:%s(%s)',__FILE__,__METHOD__,__LINE__)
					));
				}

			} else {
				$construct->validated = false;

				array_push($construct->val_error,array(
					'field'=>sprintf('%s_%s',$construct->module,$field_name),
					'field_trans'=>$C_translate->translate('field_'.$field_name,$construct->module,''),
					'error'=>$C_translate->translate('validate_any','',''),
					'method'=>sprintf('%s:%s(%s)',__FILE__,__METHOD__,__LINE__)
				));
			}
		}
	}

	# Get required static_vars and validate them
	require_once(PATH_CORE.'static_var.inc.php');
	$static_var = new CORE_static_var;

	$all_error = $static_var->validate_form($construct->module,$construct->val_error);

	if ($all_error != false && gettype($all_error) == 'array')
		$construct->validated = false;
	else
		$construct->validated = true;

	/* If validation has failed, skip the db insert & set the errors & original fields as Smarty objects,
	   and change the page to be loaded.*/
	if (! $construct->validated) {
		global $smarty;

		# Set the errors as a Smarty Object
		$smarty->assign('form_validation',$construct->val_error);

		# Set the page to be loaded
		if (! defined('FORCE_PAGE'))
			define('FORCE_PAGE',$VAR['_page_current']);

		# Define any triggers
		if (isset($construct->trigger[$type])) {
			include_once(PATH_CORE.'trigger.inc.php');
			$trigger = new CORE_trigger;

			$trigger->trigger($construct->trigger[$type],0,$VAR);
		}

		# Strip slashes
		global $C_vars;
		$C_vars->strip_slashes_all();

		return false;

	} else {
		# Begin the new database class
		$db = &DB();

		# Loop through the field list to create the sql queries
		$field_list = array();
		reset($arr);
		while (list($key,$field_name) = each($arr)) {
			# Get the field value
			$field_var = sprintf('%s_%s',$construct->module,$field_name);

			if (isset($VAR[$field_var])) {
				# Check if HTML allowed
				if (@$construct->field[$field_name]['html'] != 1 && ! is_array($VAR[$field_var]))
					$insert_value = htmlspecialchars($VAR[$field_var]);
				else
					$insert_value = $VAR[$field_var];

				# Perform data conversions
				if (isset($construct->field[$field_name]['convert']) && ! isset($VAR['_noconvert']))
					$insert_value = $validate->convert($field_name,$insert_value,$construct->field[$field_name]['convert']);

				# Create the sql statement
				if (! is_null($insert_value))
					$field_list[$field_name] = $insert_value;
			}
		}

		# Check and see if we have some default fields
		foreach (array('date_orig','date_last') as $field_name) {
			$field_var = sprintf('%s_%s',$construct->module,$field_name);

			if (isset($construct->field[$field_name]) && ! isset($VAR[$field_var]))
				if (isset($construct->field[$field_name]['convert']) && ! isset($VAR['_noconvert']))
					$field_list[$field_name] = $validate->convert($field_name,time(),$construct->field[$field_name]['convert']);
				else
					$field_list[$field_name] = time();
		}

		# Determine the record id
		$construct->record_id = isset($field_list['id']) ? $field_list['id'] : $db->GenID(AGILE_DB_PREFIX.$construct->table.'_id');

		# Execute the query
		$result = $db->Execute(sqlInsert($db,$construct->table,$field_list,$construct->record_id));

		# Error reporting
		if ($result === false) {
			global $C_debug;
			$C_debug->error(__FILE__,__METHOD__,$db->ErrorMsg());

			if (isset($construct->trigger[$type])) {
				include_once(PATH_CORE.'trigger.inc.php');
				$trigger = new CORE_trigger;

				$trigger->trigger($construct->trigger[$type],0,$VAR);
			}

			return false;
		}

		# Define any triggers
		if (isset($construct->trigger[$type])) {
			include_once(PATH_CORE.'trigger.inc.php');
			$trigger = new CORE_trigger;

			$trigger->trigger($construct->trigger[$type],1,$VAR);
		}

		# Insert the static vars
		$static_var->add($VAR,$construct->module,$construct->record_id);

		$_escape = '';
		if (isset($VAR['_escape']) || isset($VAR['_escape_next']))
			$_escape = '&_escape=1&_escape_next=1';

		if (! isset($VAR['_noredirect']))
			define('REDIRECT_PAGE',sprintf('?_page=%s&id=%s%s',$VAR['_page'],$construct->record_id,$_escape));

		return $construct->record_id;
	}
}
?>