<?php
function sanitizeString($var)
{
	if (get_magic_quotes_gpc()) $var = stripslashes($var);
	$var = htmlentities($var);
	$var = strip_tags($var);
	return $var;
}

function sanitizeMySQL($var)
{
	$var = sanitizeString($var);
	return $var;
}

//using the parameters ( Age, Weight, Height, Gender and Exercise Level) this function will calculate the nutrient ranges. 
function getresults($age,$w,$h,$gender,$exerciseLevel)
{
	$weight = 0.453592*$w; //kilograms
	$height = 2.54*$h/100; //meters
	
	$bmi = getBMI($weight,$height);
	$calorie = getCalorie($exerciseLevel,$age,$gender,$height,$weight);
	
	$waterLower = getWaterLower($age,$gender);
	$waterUpper = getWaterUpper($age,$gender);
	$carbohydrateLower = getCarbohydrateLower($calorie);
	$carbohydrateUpper = getCarbohydrateUpper($calorie);
	$fiberLower = getFiberLower($age,$gender);
	$proteinLower = getProteinLower($calorie,$age);
	$proteinUpper = getProteinUpper($calorie,$age);
	$fatLower = getFatLower($calorie,$age);
	$fatUpper = getFatUpper($calorie,$age);

	return array($bmi, $calorie, $waterLower, $waterUpper, $carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper);
}

//calculates Body Mass Index using user’s weight and height.
function getBMI($w,$h){
	return round($w/(($h)*($h)),2);
}

//calculates the daily-recommended amount of calories using user’s exercise level, age, gender, height and weight.
function getCalorie($exerciseLevel,$age,$gender,$height,$weight){
	$pa = getPA($exerciseLevel,$age,$gender);
	
	if($age<0.33){
		$eer = (89*$weight-100)+175;
	}
	else if($age<0.58){
		$eer = (89*$weight-100)+56;
	}
	else if($age<1.08){
		$eer = (89*$weight-100)+22;
	}
	else if($age<3){
		$eer = (89*$weight-100)+20;
	}
	else if($age<9){
		if($gender=="Male"){
			$eer = 88.5-(61.9*$age)+$pa*((26.7*$weight)+(903*$height))+20;
		}
		else{
			$eer = 135.3-(30.8*$age)+$pa*((10*$weight)+(934*$height))+20;
		}
	}
	else if($age<19){
		if($gender=="Male"){
			$eer = 88.5-(61.9*$age)+$pa*((26.7*$weight)+(903*$height))+25;
		}
		else{
			$eer = 135.3-(30.8*$age)+$pa*((10*$weight)+(934*$height))+25;
		}
	}
	else{
		if($gender=="Male"){
			$eer = 662-(9.53*$age)+$pa*((15.91*$weight)+(539.6*$height));													        }
		else{
			$eer = 354-(6.91*$age)+$pa*((9.36*$weight)+(726*$height));
		}
	}
	return round($eer,0);
}

//calculates the Physical Activity Coefficients using user’s exercise level, age and gender.
function getPA($exerciseLevel,$age,$gender){
	
	if($exerciseLevel=="Sedentary"){
		$x=0;
	}
	else if($exerciseLevel=="Low Active"){
		$x=1;
	}
	else if($exerciseLevel=="Active"){
		$x=2;
	}
	else{
		$x=3;
	}
	
	if($gender=="Male"&&$age<19){
		$y=0;
	}
	else if($gender=="Female"&&$age<19){
		$y=1;
	}
	else if($gender=="Male"){
		$y=2;
	}
	else {
		$y=3;
	}
	
	$PATable = array(array(1.0,1.13,1.26,1.42),array(1.0,1.16,1.31,1.56),array(1.0,1.11,1.25,1.48),array(1.0,1.12,1.27,1.45));
	return $PATable[$y][$x];
}

//calculates the daily lower recommended amount of water, using user’s age and gender.
function getWaterUpper($age,$gender){
	return 7500;
}

//calculates the daily upper recommended amount of water, using user’s age and gender.
function getWaterLower($age,$gender){
	
	if($age<0.58){
		$water = 700;
	}
	else if($age<1.08){
		$water = 800;
	}
	else if($age<4){
		$water = 1300;
	}
	else if($age<9){
		$water = 1700;
	}
	else if($age<14){
		if($gender=="Male"){
			$water = 2400;
		}
		else{
			$water = 2100;
		}
	}
	else if($age<19){
		if($gender=="Male"){
			$water = 3300;
		}
		else{
			$water = 2300;
		}
	}
	else{
		if($gender=="Male"){
			$water = 3700;
		}
		else{
			$water = 2700;
		}
	}
	return $water;
}

// calculates the daily lower recommended amount of carbohydrate using user’s daily-recommended amount of calories.
function getCarbohydrateLower($calories){
	$x=4; //energy provided by carbs
	
	return round(0.45*$calories/$x);
}

//calculates the daily upper recommended amount of carbohydrate using user’s daily-recommended amount of calories.
function getCarbohydrateUpper($calories){
	$x=4; //energy provided by carbs
	
	return round(0.65*$calories/$x);
}

//calculates the daily lower recommended amount of protein, using user’s daily-recommended amount of calories and age.
function getProteinLower($calories,$age){
	$x=4; //energy provided by protein
	if($age<4){
		return round(0.05*$calories/$x);
	}
	if($age<19){
		return round(0.1*$calories/$x);
	}
	return round(0.1*$calories/$x);
}

//calculates the daily upper recommended amount of protein, using user’s daily-recommended amount of calories and age.
function getProteinUpper($calories,$age){
	$x=4; //energy provided by protein
	if($age<4){
		return round(0.2*$calories/$x);
	}
	if($age<19){
		return round(0.3*$calories/$x);
	}
	return round(0.35*$calories/$x);
}

//calculates the daily lower recommended amount of fat, using user’s daily-recommended amount of calories and age.
function getFatLower($calories,$age){
	$x=9; //energy provided by fat
	if($age<4){
		return round(0.3*$calories/$x);
	}
	if($age<19){
		return round(0.25*$calories/$x);
	}
	return round(0.2*$calories/$x);
}

//calculates the daily upper recommended amount of fat, using user’s daily recommended amount of calories and age.
function getFatUpper($calories,$age){
	$x=9; //energy provided by fat
	if($age<4){
		return round(0.4*$calories/$x);
	}
	if($age<19){
		return round(0.35*$calories/$x);
	}
	return round(0.35*$calories/$x);
}

//calculates the daily lower recommended amount of fiber, using user’s age and gender.
function getFiberLower($age,$gender){
	
	if($gender=="Male"){
		$x=0;
	}
	else{
		$x=1;
	}
	
	if($age<1){
		$y=0;
	}
	else if($age<4){
		$y=1;
	}
	else if($age<9){
		$y=2;
	}
	else if($age<14){
		$y=3;
	}
	else if($age<19){
		$y=4;
	}
	else if($age<51){
		$y=5;
	}
	else {
		$y=6;
	}
	
	$fiberTable = array(array("ND",19,25,31,38,38,30),array("ND",19,25,26,26,25,21));
	return $fiberTable[$x][$y];
}

// creates the html table to display the user's nutrients ranges
function createTable(){
	
	global $gender, $age, $height, $weight, $exerciseLevel, $bmi, $calorie, $waterLower, $waterUpper,$carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper;	
	
	
	return '<table border="0" cellspacing="0" cellpadding="2" width="100%">

  <tr>
    <td>Gender</td>
    <td>'.$gender.'</td>
  </tr>
  <tr>
    <td>Age</td>
    <td>'.round($age,2).' Years</td>
  </tr>
  <tr>
    <td>Height</td>
    <td>'.$height.' in.</td>
  </tr>
  <tr>
    <td>Weight</td>
    <td>'.$weight.' lbs.</td>
  </tr>
  <tr>
    <td>Exercise Level</td>
    <td>'.$exerciseLevel.'</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>BMI</td>
    <td>'.$bmi.'</td>
  </tr>
  <tr>
    <td>Caloric Needs</td>
    <td>'.$calorie.' kcal/day</td>
  </tr>
  <tr>
    <td>Carbohydrates</td>
    <td>'.$carbohydrateLower.' - '.$carbohydrateUpper.' grams</td>
  </tr>
  <tr>
    <td>Protein</td>
    <td>'.$proteinLower.' - '.$proteinUpper.' grams</td>
  </tr>
  <tr>
    <td>Fat</td>
    <td>'.$fatLower.' - '.$fatUpper.' grams</td>
  </tr>
  <tr>
    <td>Water</td>
    <td>'.$waterLower.' - '.$waterUpper.' grams</td>
  </tr>
  <tr>
    <td>Fiber</td>
    <td>'.$fiberLower.' grams</td>
  </tr>
</table>';
}

//gets the set of food returned by the lp function and shows the solution on the screen 
function showingSolution($values,$food,$portion,$direction){
	
	include("login.php");
	
	//rounding the values
	for($i=0;$i<count($values);$i++){
		if($direction == "MAX"){
			$values[$i]=floor($values[$i]);
		}
		else {
			$values[$i]=ceil($values[$i]);
		}
	}
	
	//creating html table
	$message1="<table border='1'><tr><td>nutrients</td>";
	$message2="<tr><td>water</td>";
	$message3="<tr><td>carb</td>";
	$message4="<tr><td>fiber</td>";
	$message5="<tr><td>protein</td>";
	$message6="<tr><td>fat</td>";
	
	for($a=0;$a<count($food);$a++){
			
			//calculating values for each nutrient
			$water[$a] = (( floatval($food[$a]['255'])/$portion))*$values[$a];
			$carbohydrate[$a] = ( floatval($food[$a]['205'])/$portion)*$values[$a];
			$fiber[$a] = ( floatval($food[$a]['291'])/$portion)*$values[$a];
			$protein[$a] = ( floatval($food[$a]['203'])/$portion)*$values[$a];
			$fat[$a] = ( floatval($food[$a]['204'])/$portion)*$values[$a];
			
			$message1 .= "<td>".$food[$a]["Long_Desc"]."</td>";
			$message2 .= "<td>".$food[$a]["255"]." x <b>".$values[$a]/$portion."</b></td>";
			$message3 .= "<td>".$food[$a]["205"]." x <b>".$values[$a]/$portion."</b></td>";
			$message4 .= "<td>".$food[$a]["291"]." x <b>".$values[$a]/$portion."</b></td>";
			$message5 .= "<td>".$food[$a]["203"]." x <b>".$values[$a]/$portion."</b></td>";
			$message6 .= "<td>".$food[$a]["204"]." x <b>".$values[$a]/$portion."</b></td>";
			
	}
	$message1.="</tr>";
	$message2.="</tr>";
	$message3.="</tr>";
	$message4.="</tr>";
	$message5.="</tr>";
	$message6.="</tr></table><br />
<br />
";
	
	echo $message1.$message2.$message3.$message4.$message5.$message6;
	
	$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);
	
	$result=array();
	
	list($bmi, $calorie, $waterLower, $waterUpper, $carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper) = getresults($row['age'],$row['weight'],$row['height'],$row['gender'],$row['exerciseLevel']);
	
	$result[0]=array_sum($water);
	$result[1]=array_sum($carbohydrate);
	$result[2]=array_sum($fiber);
	$result[3]=array_sum($protein);
	$result[4]=array_sum($fat);
		
			$message = "<table border='1'>";
	

	$message .= "<tr><td>".$waterLower."</td><td>".ceil($result[0])."</td><td>".floor($result[0])."</td><td>".$waterUpper."</td></tr>";
	$message .= "<tr><td>".$carbohydrateLower."</td><td>".ceil($result[1])."</td><td>".floor($result[1])."</td><td>".$carbohydrateUpper."</td></tr>";
	$message .= "<tr><td>".$fiberLower."</td><td>".ceil($result[2])."</td><td>".floor($result[2])."</td><td>fiber upper</td></tr>";
	$message .= "<tr><td>".$proteinLower."</td><td>".ceil($result[3])."</td><td>".floor($result[3])."</td><td>".$proteinUpper."</td></tr>";
	$message .= "<tr><td>".$fatLower."</td><td>".ceil($result[4])."</td><td>".floor($result[4])."</td><td>".$fatUpper."</td></tr>";
	
	echo $message;
	
}


//gets the set of food returned by the lp function and checks if this set of foods will satisfy the user’s nutrient ranges, adding up all the amounts of a specific nutrient and comparing with the lower value and upper value
function checkSolution($values,$food,$portion, $direction){
	
	//if the set is empty, no solution
	if(count($food)<=0) return false;
	
	include("login.php");
	
	//calculating the amount of nutrient for each food, times the quantity recommended for the meal plan
	for($a=0;$a<count($food);$a++){
			
			$water[$a] = (( floatval($food[$a]['255'])/$portion))*$values[$a];
			$carbohydrate[$a] = ( floatval($food[$a]['205'])/$portion)*$values[$a];
			$fiber[$a] = ( floatval($food[$a]['291'])/$portion)*$values[$a];
			$protein[$a] = ( floatval($food[$a]['203'])/$portion)*$values[$a];
			$fat[$a] = ( floatval($food[$a]['204'])/$portion)*$values[$a];
			
	}
	
	//getting 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);
	
	$result=array();
	
	//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']);
	//calculating the amount of each nutrient according to the meal plan
	$result[0]=array_sum($water);
	$result[1]=array_sum($carbohydrate);
	$result[2]=array_sum($fiber);
	$result[3]=array_sum($protein);
	$result[4]=array_sum($fat);
	
	//defining the error
	$e = 0.1;
	$flag = array(false,false,false,false,false);
	
	//calculating the error for each nutrient
	$error = array(($waterUpper-$waterLower)*$e,($carbohydrateUpper-$carbohydrateLower)*$e,($fiberLower)*$e,($proteinUpper-$proteinLower)*$e,($fatUpper-$fatLower)*$e );
	
	//checking the nutrients
	if($waterLower<=ceil($result[0])+1&&$waterUpper>=floor($result[0])-1)
		$flag[0]=true;
	if($carbohydrateLower<=ceil($result[1])+1&&$carbohydrateUpper>=floor($result[1])-1)
		$flag[1]=true;
	if($fiberLower<=ceil($result[2])+1||$fiberLower<=floor($result[2])-1)
		$flag[2]=true;
	if($proteinLower<=ceil($result[3])+1&&$proteinUpper>=floor($result[3])-1)
		$flag[3]=true;
	if($fatLower<=ceil($result[4])+1&&$fatUpper>=floor($result[4])-1)
		$flag[4]=true;
		
	//in case of positive solution, showing the results
	if($flag[0]&&$flag[1]&&$flag[2]&&$flag[3]&&$flag[4])
		showingSolution($values,$food,$portion,$direction);
	return $flag[0]&&$flag[1]&&$flag[2]&&$flag[3]&&$flag[4];
}


function interpretResults($values,$food, $like,$portion){
	
	include("login.php");
	$message1="<table border='1'><tr><td>nutrients</td>";
	$message2="<tr><td>water</td>";
	$message3="<tr><td>carb</td>";
	$message4="<tr><td>fiber</td>";
	$message5="<tr><td>protein</td>";
	$message6="<tr><td>fat</td>";
	
	for($a=0;$a<count($food);$a++){
			
			$water[$a] = (( floatval($food[$a]['255'])/$portion))*$values[$a];
			$carbohydrate[$a] = ( floatval($food[$a]['205'])/$portion)*$values[$a];
			$fiber[$a] = ( floatval($food[$a]['291'])/$portion)*$values[$a];
			$protein[$a] = ( floatval($food[$a]['203'])/$portion)*$values[$a];
			$fat[$a] = ( floatval($food[$a]['204'])/$portion)*$values[$a];
			
			$message1 .= "<td>".$food[$a]["Long_Desc"]."</td>";
			$message2 .= "<td>".$food[$a]["255"]." x ".$values[$a]/$portion."</td>";
			$message3 .= "<td>".$food[$a]["205"]." x ".$values[$a]/$portion."</td>";
			$message4 .= "<td>".$food[$a]["291"]." x ".$values[$a]/$portion."</td>";
			$message5 .= "<td>".$food[$a]["203"]." x ".$values[$a]/$portion."</td>";
			$message6 .= "<td>".$food[$a]["204"]." x ".$values[$a]/$portion."</td>";
			
	}
	$message1.="</tr>";
	$message2.="</tr>";
	$message3.="</tr>";
	$message4.="</tr>";
	$message5.="</tr>";
	$message6.="</tr></table>";
	
	echo $message1.$message2.$message3.$message4.$message5.$message6;
	
	$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);
	
	$result=array();
	
	list($bmi, $calorie, $waterLower, $waterUpper, $carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper) = getresults($row['age'],$row['weight'],$row['height'],$row['gender'],$row['exerciseLevel']);
	
	if($like==0){
		$result[0]=array_sum($water);
		$result[1]=array_sum($carbohydrate);
		$result[2]=array_sum($fiber);
		$result[3]=array_sum($protein);
		$result[4]=array_sum($fat);
	}
	else{
		$result[0]=array_sum($water)+$like['255'];
		$result[1]=array_sum($carbohydrate)+$like['205'];
		$result[2]=array_sum($fiber)+$like['291'];
		$result[3]=array_sum($protein)+$like['203'];
		$result[4]=array_sum($fat)+$like['204'];
	}
	
	/*$message = "<table border='1'>";
	

	$message .= "<tr><td>".$waterLower."</td><td>".$result[0]."</td><td>".$waterUpper."</td></tr>";
	$message .= "<tr><td>".$carbohydrateLower."</td><td>".$result[1]."</td><td>".$carbohydrateUpper."</td></tr>";
	$message .= "<tr><td>".$fiberLower."</td><td>".$result[2]."</td><td>fiber upper</td></tr>";
	$message .= "<tr><td>".$proteinLower."</td><td>".$result[3]."</td><td>".$proteinUpper."</td></tr>";
	$message .= "<tr><td>".$fatLower."</td><td>".$result[4]."</td><td>".$fatUpper."</td></tr>";
		
	echo $message;*/
}

function check($r){
	if ($r == NULL){
		return false;
	}
	
	include("login.php");
	$query = "SELECT * FROM user WHERE username = '".$r['username']."' ";
	$result = mysqli_query($db_connection, $query);
	if (!$result) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
	$row = mysqli_fetch_assoc($result);
	
	list($bmi, $calorie, $waterLower, $waterUpper, $carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper) = getresults($row['age'],$row['weight'],$row['height'],$row['gender'],$row['exerciseLevel']);

	$query = "SELECT * FROM food_des WHERE NDB_No = '".$r['NDB_No']."' ";
	$result = mysqli_query($db_connection, $query);
	if (!$result) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
	$row = mysqli_fetch_assoc($result);

	if($row['205']>$carbohydrateUpper) return false;
	if($row['203']>$proteinUpper) return false;
	if($row['204']>$fatUpper) return false;
	return true;

}

?>