<html>
<body><?php 

//receives as parameters a set of foods (array_food_final) and a portion number. Calculates the meal plan based on user's nutritional ranges
function lp($portion,$array_food_final){

	include("login.php");
	
	//initializing variables
	$text = $food = $water = $carbohydrate = $fiber = $protein = $fat = $calorie = $function = $restrictions = $variables = array();
	
	//calculating nutritional value based on the portion number
	for($a=0;$a<count($array_food_final);$a++)
	{	
			$row = $array_food_final[$a];
			$food = $row["NDB_No"];
	
			$water[$a] = (( floatval($row['255'])/$portion));
			$carbohydrate[$a] = ( floatval($row['205'])/$portion);
			$fiber[$a] = ( floatval($row['291'])/$portion);
			$protein[$a] = ( floatval($row['203'])/$portion);
			$fat[$a] = ( floatval($row['204'])/$portion);
	}
	
	//create the constraits array to the Linear Programming package
	$constraits = array(neg($carbohydrate),neg($protein),neg($fat),neg($water), $water,neg($fiber),$carbohydrate,$protein,$fat);
	
	//getting the user's information
	$query = "SELECT * FROM user WHERE username = '".$_SESSION['login']."' ";
	$result = mysqli_query($db_connection, $query);
	if (!$result) echo "Database query failed";
	$row = mysqli_fetch_assoc($result);
	
	//getting user's nutritional ranges
	list($bmi, $calorie, $waterLower, $waterUpper, $carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper) = getresults($row['age'],$row['weight'],$row['height'],$row['gender'],$row['exerciseLevel']);
	//create the definitions array to the Linear Programming package
	$definitions = array($carbohydrateLower*(-1),$proteinLower*(-1),$fatLower*(-1),$waterLower*(-1),$waterUpper,$fiberLower*(-1),$carbohydrateUpper, $proteinUpper,$fatUpper);
	
	//counting number of variables and constraints
	$variables=count($array_food_final);
	$constr = count($constraits);
	
	//initializing function array to be used by the Linear Programming package
	for($i=0;$i<$variables;$i++){
		$function[$i]=-1;
	}
	
	//creating string to be used by the Linear Programming package
	$execQuery = "glpk.exe MIN ".(($variables+1)*($constr)+5+$variables)." ";
	$execQuery .= $variables." ".$constr." " ;
	for($i=0;$i<$variables;$i++) $execQuery .= "1 ";
	for($i=0;$i<($constr);$i++) for($j=0;$j<($variables);$j++)$execQuery .= $constraits[$i][$j]." ";
	for($i=0;$i<($constr);$i++) $execQuery .= $definitions[$i]." ";
	
	//creating file that will be read by the Linear Programming package
	$filename = $_SESSION['login'].time().".txt";
	$myfile = fopen($filename, "w");
	fwrite($myfile, $execQuery);
	fclose($myfile);
	
	//running the package
	exec("glpk.exe MIN ".(($variables+1)*($constr)+5+$variables)." ".$filename,$output);
	
	//destroying file that will be read by the Linear Programming package
	unlink($filename);
	return $output;
}

//change a value to negative
function neg($a){
	for($i=0;$i<count($a);$i++){
		$a[$i]=$a[$i]*(-1);
	}
	return $a;
}
?>
</body>
</html>
