<?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 VIEW Method
 *
 * This function should only return 1 record.
 *
 * @uses CORE_trigger
 * @uses CORE_static_var
 */

function CORE_database_view($VAR,$construct,$type) {
	require_once(PATH_CORE.'static_var.inc.php');

	# Some Validaiton
	if (! isset($VAR['id']))
		return;

	# If we have more than 1 entry, then return. Javascript should bring us back with 1 entry to view.
	if (count(explode(',',preg_replace('/,$/','',$VAR['id']))) > 1)
		return;

	# Set our db.
	$db = &DB();

	$result = $db->Execute(sqlSelect($db,$construct->table,implode(',',$construct->method[$type]),array('id'=>$VAR['id']),$construct->order_by));

	# 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;

	# No results:
	} elseif (! $result->RecordCount()) {
		global $C_debug;
		$C_debug->error(__FILE__,__METHOD__,'The selected record does not exist any longer, or your account is not authorized to view it');

		return;
	}

	# Get the static vars
	$static_var = new CORE_static_var;
	$arr = $static_var->update_form($construct->module,'update',$result->fields['id']);
	if (is_array($arr))
		$smart['static_var'] = $arr;

	# Run any custom validation on this result for this module
	if (isset($construct->custom_EXP)) {
		for ($ei=0; $ei<count($construct->custom_EXP); $ei++) {
			$field = $construct->custom_EXP[$ei]['field'];
			$value = $construct->custom_EXP[$ei]['value'];

			if ($result->fields[$field] == $value) {
				$smart = $result->fields;

				$result->MoveNext();
				$ei = count($construct->custom_EXP);
			}
		}

	} else {
		$smart = $result->fields;
	}

	# Define the results
	global $smarty;
	$smarty->assign('record',$smart);

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

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

	# Return the retrieved records
	return $smart;
}
?>