<?php
    ///////////////////////////////////////////////// 
    //
    //CFSTPHPSTART
    // FileName: inc/dbfunctions.php
    // Purpose:  wraps php mysql database functions
    //           change of database layer to mysqli was scrapped at end of V3
    // Called by:
    // Calls:
    // 
    //CFSTPHPEND
    //
    //Property of CarFinder.com LLC - All use is forbidden.
    //
    ///////////////////////////////////////////////// 
    // 2016-11-27 - changing loggers

	// key sections and thoughts include:
	//  - additional traps may be needed for V2 functions if its better to return nulls. assume testing is required
	//  - the logging calls follow this example	$records = ms_dbV2_array_query($query,"[Error Testing functions: CFEB-102]" );
	//  - Rules of thumb, page name is redundant if every invocation has a unique CF error code CFEB-nnn.... CFEA prefix is reserved for OLD code and will need to be wiped out over time
	//  - To assign new numbers:  scan for the latest CFEB string across all files... its better to assign a whole page at a time and CFEB-999 is fine as temporary placeholder until ready to rollout.  The text should be inidicative of the problem

	// db functions mysql helpers
	function ms_db_open() {
	    dbConnectFront();
	}

	// only called here
	function ms_dbV2_query($query, $in_detailed_message, $debug = false)
	{
/*		$records_raw = mysql_query($query)
			or frontSuperErrorLogger( $in_detailed_message . "[query]"  , $query, " mysqlerrno=". mysql_errno(). ", " . mysql_error()  );
*/

		  		$records_raw = mysql_query($query)
					or frontSuperV4Logger( $PAGE['page'], 'LCAT_ERROR'  ,'LEVN_QUERY', 'LSEVYYY','[CFEB-HUH]',               $in_detailed_message . "[query]"  , $query, " mysqlerrno=" . mysql_errno(). ", " . mysql_error()  );

			//	if ($debug) var_dump($query, $records_raw, mysql_error());

	
		return $records_raw;
	}
	// should this return NULL or an empty array?
	function ms_dbV2_array_query($query, $in_detailed_message, $debug = false)
	{
/*
		$records_raw = ms_dbV2_query($query,  $in_detailed_message, $debug)
			or frontSuperErrorLogger( $in_detailed_message . "[array]"  , $query, " mysqlerrno=". mysql_errno(). ", " . mysql_error()  );
*/

		$records_raw = ms_dbV2_query($query,  $in_detailed_message, $debug)
			or frontSuperV4Logger( $PAGE['page'], 'LCAT_ERROR'  ,'LEVN_ARRAY', 'LSEVYYY','[CFEB-HUH]', $in_detailed_message . "[array]", $query, " mysqlerrno=" . mysql_errno(). ", " . mysql_error()  );

		$records = array();

		if ($records_raw)
		{
		    while($record = mysql_fetch_assoc($records_raw) )		    		
		    {
				$records[] = $record;
			}
			if ( mysql_errno() !=0)
		      frontSuperV4Logger( $PAGE['page'], 'LCAT_ERROR'  ,'LEVN_ARRAY_FETCH', 'LSEVYYY','[CFEB-HUH]', $in_detailed_message . "[array fetch]", $query, " mysqlerrno=" . mysql_errno(). ", " . mysql_error()  );
			 
			 //was frontSuperErrorLogger( $in_detailed_message . "[array fetch]"  , $query, " mysqlerrno=". mysql_errno(). ", " . mysql_error()  );

		}
		return $records;

	}

	function ms_dbV2_item_query($query, $in_detailed_message, $debug = false)
	{
 
		$records = ms_dbV2_array_query($query, $in_detailed_message, $debug);
		if ( mysql_errno() !=0)
		      frontSuperV4Logger( $PAGE['page'], 'LCAT_ERROR'  ,'LEVN_ITEM','LSEVYYY', '[CFEB-HUH]', $in_detailed_message . "[item]", $query, " mysqlerrno=" . mysql_errno(). ", " . mysql_error()  );

		//was  frontSuperErrorLogger( $in_detailed_message . "[item]"  , $query, " mysqlerrno=". mysql_errno(). ", " . mysql_error()  );

		return (is_array($records)) ? $records[0] : false;
	}

  
	function buildwhere($clauses) 
	{
		return (count($clauses) > 0) ? " WHERE ".implode(' AND ', $clauses). " " : "";
	}

/*

//
// DATABASE FUNCTIONS - using mysqli vs the deprecated mysql calls
// typical calling pattern is 	: globals.php calls db_open
//                            	: call db_create_param if needed to build safe parameters
//								: call db_array_query to get results as an array
//								: call db_item_query to get a single row of results - like for getting the count
//

function db_open() {
global $dbHost, $dbUser, $dbPass, $db;	// defined in dbconfig.php

	return new MySQLi($dbHost, $dbUser, $dbPass, $db);
}

function db_create_param($types, $value, $value2 = null) {

	$param = array();
	$param['types'] = $types;
	$param['value'] = $value;
	if (isset($value2)) $param['value2'] = $value2;
	if (isset($value3)) $param['value3'] = $value3;
	if (isset($value4)) $param['value4'] = $value4;
	if (isset($value5)) $param['value5'] = $value5;
	if (isset($value6)) $param['value6'] = $value6;
	if (isset($value7)) $param['value7'] = $value7;
	if (isset($value8)) $param['value8'] = $value8;

	return $param;
	// return array('types'=>$types, 'value'=>$value, 'value2'=>$value2, 'value3'=>$value3);
}

function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();
    $fields[0] = $stmt;
    $count = 1;
    while($field = mysqli_fetch_field($data)){
        $fields[$count] = &$out[$field->name];
        $count++;
    }
    call_user_func_array('mysqli_stmt_bind_result', $fields);
}

function db_array_query($db, $query, $param = null, $direct = false, $debug = false) {
	$records = array();
	if ($sql = $db->prepare($query)) {
		// $params format: array( 'types'=>'ss', 'value'=>$city, 'value2'=>$state')
		if (isset($param) && isset($param['types'])) {
			switch(strlen($param['types'])) {
				case 1:
					$sql->bind_param($param['types'], $param['value']);
					if ($debug) var_dump("1 param ", $param['types'], $param['value']);
					break;
				case 2:
					$sql->bind_param($param['types'], $param['value'], $param['value2']);
					if ($debug) var_dump("2 params ", $param['types'], $param['value'], $param['value2']);
					break;
			}
		}
		$sql->execute();
		if ($debug) var_dump($sql->error, $db->error);
		stmt_bind_assoc($sql, $result);
		$copy = create_function('$a','return $a;');
		while($sql->fetch()) {
			if ($direct) {
				$records = $result;
			} else {
				$records[] = array_map($copy, $result);
			}
		}
		$sql->free_result();
		$sql->close();
		return $records;
	}
	if ($debug) var_dump($query, $sql, $param, $db->error);

	// LOG EACH QUERY - optionally wrap in $debug
	frontEndLoggerFullQuery($_SERVER['REMOTE_ADDR'] , $query);
}

function db_item_query($db, $query, $param = null, $debug = false) {
	$a = db_array_query($db, $query, $param, false, $debug);
	$i = $a[0];

	return $i;
}
*/

/*

function ms_db_query($query, $debug = false) {
	$records_raw = mysql_query($query);
	if ($debug) var_dump($query, $records_raw, mysql_error());
	return $records_raw;
}

function ms_db_array_query($query, $debug = false) 
{
	$records_raw = ms_db_query($query, $debug);

	$records = array();
    while ($record = mysql_fetch_assoc($records_raw)) 
    {
		$records[] = $record;
	}
	return $records;
}

function ms_db_item_query($query, $debug = false) {
	$records = ms_db_array_query($query, $debug);
	return (is_array($records)) ? $records[0] : false;
}
*/
