<?php
ini_set('display_errors', 'On');
error_reporting(E_ERROR);

/*The following code will sets the distance and volume factors to be used while calculation of efficiency*/

//get units
function getUnits($user_id){
	// include db config class
	require_once __DIR__ . '/db_config.php';

	// connecting to db
	$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
	mysqli_set_charset($mysqli, "utf8");

	$dist_fact = 1;
	$vol_fact = 1;
	
	if($stmt = $mysqli->prepare("SELECT DISTANCE, VOLUME, CONSUMPTION FROM SETTINGS WHERE USER_ID = ?")){
		$stmt->bind_param("i", $user_id);
		$stmt->execute(); 
		$stmt->bind_result($temp_dist, $temp_vol, $temp_cons);
		while($stmt->fetch()){
			$dist_unt = $temp_dist;
			$vol_unt = $temp_vol;
			$cons_unt = $temp_cons;
		}
		
		//set the distance factor
		//set distance factor if distance is in km but consumption is in miles
		if(strcmp(substr($cons_unt, 0, 1), "m")==0 && strcmp($dist_unt, "km")==0){
			$dist_fact = 0.621;
		}
		//set distance factor if distance is in miles but consumption is in km
		else if(strcmp(substr($cons_unt, 0, 1), "m")!=0 && strcmp($dist_unt, "mi")==0){
			$dist_fact = 1.609;
		}
		
		//set the volume factor
		//set volume factor if consumption is in gallons(US)
		if(strpos($cons_unt, "g(US)") !== false){
			if(strcmp($vol_unt, "Ltr")==0){
				$vol_fact = 0.264;
			}
			else if(strcmp($vol_unt, "gal(UK)")==0){
				$vol_fact = 1.201;
			}
		}
		//set volume factor if consumption is in gallons(UK) 
		else if(strpos($cons_unt, "g(UK)") !== false){
			if(strcmp($vol_unt, "Ltr")==0){
				$vol_fact = 0.22;
			}
			else if(strcmp($vol_unt, "gal(US)")==0){
				$vol_fact = 0.833;
			}
		}
		//set volume factor if consumption is in litres
		else{
			if(strcmp($vol_unt, "gal(UK)")==0){
				$vol_fact = 4.546;
			}
			else if(strcmp($vol_unt, "gal(US)")==0){
				$vol_fact = 3.785;
			}
		}
		
		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
	    	} 
	}
	
	mysqli_close($mysqli);
	
	return array($dist_fact, $vol_fact);
}

?>