<?

/*/
	© 2001-2004 by Locke Enterprises (iLocke.com) - All rights reserved.
	License:  Authorized for use on the Windshields To Go USA website(s).
	File:  settings.phi  [v0.9]  -- need an EditSettings() and a SaveSettings() before 1.0
	Purpose:  Export a way to load db values and keep them in a memory array.
	Created:  6/21/2001 - Nathan
	Modification History:
		· 7/1/2004 - Nathan - reworked to use the new NDB
		· 7/7/2004 - Nathan - installed on the AGH affiliate website(s)
		· 11/20/2004 - Nathan - added the ignore features
		· mm/dd/yyyy - [name] - [comment]
/*/


	/// GLOBAL prerequisite...
	if( !@isset($g_INCLUDED["GLOBAL.phi"]) ) exit("<pre>\n\nERROR(0a) GLOBAL requirement check failure.\n\n</pre>");
	if( !@isset($g_oNDB) ) exit("<pre>\n\nERROR(0b) NDB requirement check failure.\n\n</pre>");
	

//-------------------------------------------------------------------------
// GetSettings:  Load in settings as an associative array by name/value from the specified refID/type.
// Note:  When getting 'ref' settings, this first loads in the 'model' setting names and then uses GetSetting() to individually retrieve each; allowing the auto-insert benefit.
//-------------------------------------------------------------------------
function & GetSettings( $refID=null, $type=null, $IgnoreArray=null, $subRefID=null ) {

	global $g_Config, $g_oNDB;

	/// some pseudo-polymorphic handling...
	if( isset($refID) && !isset($type) ) $type = "ref";
	if( !isset($type) ) $type = "master";
	//echo "$refID:$type:$IgnoreArray:$subRefID<br>";

	/// determine any values to be ignored...
	$rIgnores = array();
	if( isset($IgnoreArray) && $IgnoreArray!=null ) {
		if( is_array($IgnoreArray) ) $rIgnores = $IgnoreArray;
	}

	/* REF retrieval; run from master names*/
	if( $type=="ref" ) {
		if( $g_Config->Debugging ) echo "REF retrieval<br>\n";
		$rNames = $g_oNDB->getColumn("SELECT name FROM settings WHERE type='model'");  // all master settings...
		/// straight processing where the settings are just loaded in without ignores...
		if( count($rIgnores) < 1 ) {
			for( $i=0; $i<count($rNames); $i++ ) {
				$rArray[$rNames[$i]] =& GetSetting( $rNames[$i], $refID );  // (ref'd in case it is a large text value like a web page)
			}
		/// processing to handle ignoring of certain fields; as a ref-type only condition, $IgnoreArray specifies this...
		} else {
			for( $i=0; $i<count($rNames); $i++ ) {
				$bFound = false;
				for( $j=0; $j<count($rIgnores); $j++ ) {
					if( $rIgnores[$j] == $rNames[$i] ) {
						$bFound = true;
						break;  // from for($j)
					}
				}
				if( $bFound ) continue;  // next for($i)
				$rArray[$rNames[$i]] =& GetSetting( $rNames[$i], $refID );  // (ref'd in case it is a large text value like a web page)
			}
		}
		if( $g_Config->Debugging ) printArray($rArray);
		return $rArray;
	}
	
	/* REGULAR / MASTER retrieval */

	/// establish our search condition...
	if( $g_Config->Debugging ) echo "REGULAR retrieval<br>\n";
	$where = "";
	if( isset($type) ) $where .= ($where!=""?" AND ":"")."type='".$type."'";
	if( isset($refID) ) $where .= ($where!=""?" AND ":"")."refID='".$refID."'";
	if( isset($subRefID) ) $where .= ($where!=""?" AND ":"")."subRefID='".$subRefID."'";
	if( $where!="" ) $where = " WHERE ".$where;

	/// get the settings...
	$rArray = array();
	$SQL = "SELECT * FROM settings ".$where." ";  // echo $SQL;
	$oNRS = new nRS($SQL);
	while( $rData = $oNRS->read() ) {
		if( count($rIgnores) > 0 ) {
			$bFound = false;
			for( $i=0; $i<count($rIgnores); $i++ ) {
				if( $rIgnores[$i] == $rData['name'] ) {
					$bFound = true;
					break;  // from for($i)
				}
			}
			if( $bFound ) continue;  // next while($rData)
		}
		if( $rData['valueType']=="numeric" ) {
			$rArray[$rData['name']] = $rData['valueNum'];
		} elseif( $rData['valueType']=="bool" ) {
			$rArray[$rData['name']] = $rData['valueBool']=="Y";
		} else {
			$rArray[$rData['name']] = $rData['valueText'];
		}
	}
	
	/// all done; return the assoc array...
	return $rArray;

} // GetSettings()


//-------------------------------------------------------------------------
// GetSetting:  Retrieves the specified setting. Automatically inserts a new one from a default if one is not present. (&ref to help minimize memory footprint)
// Example [master]:  $m_StoreEmail = GetSetting("w2g_orderEmail"/*name*/, 0/*refID*/, "orders@windshieldstogo.com"/*default*/, 'master'/*type*/);
// Example [ref]:  
// Example [model]:  
//-------------------------------------------------------------------------
function & GetSetting( $name, $refID=null, $defaultValue=null, $type=null, $subrefID=null, $bInsertDefault=true ) {

	global $g_Config, $g_oNDB;

	/// smart prototyping for alternate calling conventions...
	if( isset($refID) && !isset($type) ) $type = "ref";
	
	/// establish our search parameters...
	$where = "name=".$g_oNDB->escape($name);
	if( isset($type) ) $where .= " AND type=".$g_oNDB->escape($type);
	if( isset($refID) ) $where .= " AND refID='".$refID."'";
	if( isset($subRefID) ) $where .= " AND subRefID='".$subRefID."'";
	if( $where != "" ) $where = " WHERE ".$where;
	
	/// get the first matching item... (should only be one)
	$SQL = "SELECT name, valueType, valueNum, valueText, valueBool FROM settings ".$where;
	$rData = $g_oNDB->getRow($SQL,"[ERROR]");
	if( $g_Config->Debugging ) printArray($rData);
	
	/// return the value if we can...
	if( isset($rData) && is_array($rData) && isset($rData[0]) && $rData[0]!="[ERROR]" ) {
		if( $rData['valueType']=='numeric' ) {
			if( $g_Config->Debugging ) echo "NUMERIC";
			$fieldValue = $rData['valueNum'];
		} elseif( $rData['valueType']=='bool' ) {
			if( $g_Config->Debugging ) echo "BOOL";
			$fieldValue = $rData['valueBool']=="Y" ? true : false;
		} else {
			if( $g_Config->Debugging ) echo "TEXT(".$rData['valueText'].")<br>";
			$fieldValue = $rData['valueText'];
		}
		if( $g_Config->Debugging ) { /*DumpInfo($rData,"debug!");*/ echo "Returning(1) a value!<br>\n"; }
		return $fieldValue;
	}

	/// we need to insert a new default based on the model when the item was not found...
	if( !$bInsertDefault || (isset($type) && trim($type)!="ref") ) {
		if( $g_Config->Debugging ) echo "cannot insert - returning null<br>";
		return null;  // no value found
	}
	$SQL = "SELECT * FROM settings WHERE name=".$g_oNDB->escape($name)." AND type='model' AND refID=1 AND subRefID=0";  // echo "<p>$SQL</p>";
	if( $g_Config->Debugging ) echo "insert new ref default -- from:<br>".$SQL."<br><br>\n";
	$rLookup = $g_oNDB->getRow($SQL);
	if( $g_Config->Debugging ) { echo $SQL."<br>"; printArray($rLookup); }
	if( @!is_array($rLookup) ) return null;
	if( $rLookup[0]=="[ERROR]" ) return null;
	//if( $g_Config->Debugging ) { echo $SQL; DumpInfo($rLookup,"rLookup - model"); }
	$SQL = "INSERT INTO settings SET name=".$g_oNDB->escape($rLookup['name']).", type='ref', refID='".intval($refID)."', subRefID='".intval($subrefID)."', ";
	$SQL .= "description=".$g_oNDB->escape($rLookup['description']).", valueType='".$rLookup['valueType']."', ";
	$SQL .= "isEditable='".$rLookup['isEditable']."', isVisible='".$rLookup['isVisible']."', ";
	if( isset($defaultValue) ) {  // init to the value specified
		if( $rLookup['valueType']=='numeric' ) $SQL .= "valueNum='".$defaultValue."', ";
		else $SQL .= "valueNum='".$rLookup['valueNum']."', ";
		if( $rLookup['valueType']=='string' ) $SQL .= "valueText=".$g_oNDB->escape($defaultValue).", ";
		else $SQL .= "valueText='".$rLookup['valueText']."', ";
		if( $rLookup['valueType']=='bool' ) $SQL .= "valueBool='".($defaultValue ? "Y" : "N")."' ";
		else $SQL .= "valueBool='".$rLookup['valueBool']."' ";
	} else {  // just carry over model defaults...
		$SQL .= "valueNum='".$rLookup['valueNum']."', valueText='".$rLookup['valueText']."', valueBool='".$rLookup['valueBool']."'";
	}
	if( $g_Config->Debugging ) echo "<br>INSERT command:<br>".$SQL."<br><br>";
	$g_oNDB->execute($SQL);
	
	/// now return the newly inserted value...
	if( $g_Config->Debugging ) echo "\nGetting new default!<br>\n";
	
	//!!! THIS IS WHERE THE CRAPPY EMPTY NAME IS GETTING INSERTED !!! invalid variable: $subRefID ( because it is NULL? )
	return GetSetting( $name, $refID, $defaultValue, $type, $subRefID, false/*!avoid letting an error cause infinite recursion!*/ );
	
} // GetSetting()


?>