<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Personal Information</title>
<?php
	include("login.php");
	include("functions.php");
	
	//verifying  session for user
	session_start();
	if (isset($_SESSION['login']))
	{
		$username = $_SESSION['login'];
	}
	else{
		header("location: logout.php");
	}

//initializing form fields
	$result = "Please insert inputs";
	$dateOfBirth = "";
	$weight = "";
	$height = "";
	$gender = "";
	$exerciseLevel = "";
	$age = "";
	
	//get user from database
	$query = 'SELECT * FROM user WHERE username = "'.$_SESSION["login"].'" ';
	$r = mysqli_query($db_connection, $query);
	if (!$r) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
	$row = mysqli_fetch_assoc($r);
	
	//verifying if column height on database is different thn NULL (it is verifying if user has already inputted information to calculate the nutrient ranges)
	if($row['height']!=NULL)
	{
		//getting user's information to calculate nutrient ranges
		$dateOfBirth = $row['dateOfBirth'];
		$weight = $row['weight'];
		$height = $row['height'];
		$gender = $row['gender'];
		$exerciseLevel = $row['exerciseLevel'];
		$age = $row['age'];
		
		//calculating nutrient ranges 
		list($bmi, $calorie, $waterLower, $waterUpper,$carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper) = getresults($age,$weight,$height,$gender,$exerciseLevel);
		
		//building table to display the results
		$result = createTable();
	}
	
//processing form in case of submit button pressed to CHANGE INFORMATION (weight, height, gender, DoB, exerciseLevel)
if (isset($_POST['submitInformation'])){
	
	//getting information from 'informationForm'
	$dateOfBirth = sanitizeMySQL($_POST['dateOfBirth']);
	$weight = sanitizeMySQL($_POST['weight']);
	$height = sanitizeMySQL($_POST['height']);
	$gender = sanitizeMySQL($_POST['gender']);
	$exerciseLevel = sanitizeMySQL($_POST['exerciseLevel']);
	$age = sanitizeMySQL($_POST['age']);
	
	//updating information in the database
	$query = 'UPDATE user SET dateOfBirth = "'.$dateOfBirth.'", weight = '.$weight.', height = '.$height.' , gender = "'.$gender.'", exerciseLevel = "'.$exerciseLevel.'", age = "'.$age.'" WHERE username = "'.$_SESSION["login"].'" ';
	$result = mysqli_query($db_connection, $query);
	if (!$result) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
	
	//calculating nutrient ranges 
	list ($bmi, $calorie, $waterLower, $waterUpper, $carbohydrateLower, $carbohydrateUpper, $fiberLower, $proteinLower, $proteinUpper, $fatLower, $fatUpper)  = getresults($age,$weight,$height,$gender,$exerciseLevel);
	
	//building table to display the results
	$result = createTable();
}


?>
<script language="javascript" type="text/javascript">

// it verifies if the inputs in the registration form are different from NULL, if the Height and Weight are valid numbers and it calculates the user’s age based on the Date of Birth.
function validateForm() {
	
	//gets the information from the form 'informationForm'
	var dateOfBirth = document.forms["informationForm"]["dateOfBirth"].value;
	var weight = document.forms["informationForm"]["weight"].value;
	var height = document.forms["informationForm"]["height"].value;
	var gender = document.forms["informationForm"]["gender"].value;
	var exerciseLevel = document.forms["informationForm"]["exerciseLevel"].value;
	var flag = true;
	var message = "";
	
	//verifies if the date of birth is non-NULL
	if (dateOfBirth == null || dateOfBirth == "") {
		document.forms["informationForm"]["dateOfBirth"].className = "error";
        message = message + "Date of birth must be filled out\n";
        flag = false;
    }
	
	//calculates the age using date of birth
	else {
		var today = new Date();
		dateOfBirth = new Date(dateOfBirth);
		age = today.getFullYear() - dateOfBirth.getFullYear();
		var month = today.getMonth() - dateOfBirth.getMonth();
		var day = today.getDate() - dateOfBirth.getDate();
				
		if (month < 0 || (month == 0 && today.getDate() < dateOfBirth.getDate())) {
       		 age--;
   		}
		if(age == 0){
			age = (today.getTime()-dateOfBirth.getTime())/(1000*60*60*24*30*12)
		}
				
		document.getElementById("age").value = age;
		if(age<=0)
		{
			document.forms["informationForm"]["dateOfBirth"].className = "error";
			message = message + "Date of birth invalid\n";
			flag = false;
		}
	}
	
	//verifies if the weight is non-NULL
	if (weight == null || weight == "") {
		document.forms["informationForm"]["weight"].className = "error";
        message = message + "Weight must be filled out\n";
        flag = false;
    }
	
	//verifies if the weight is a valid number
	else if (isNaN(weight)) {
		document.forms["informationForm"]["weight"].className = "error";
        message = message + "Weight must be a number\n";
        flag = false;
    }
	else if(weight<=0)
	{
		document.forms["informationForm"]["weight"].className = "error";
        message = message + "Weight must be a number greater than 0\n";
		flag = false;
	}
	
	//verifies if the height is non-NULL
	if (height == null || height == "") {
		document.forms["informationForm"]["height"].className = "error";
        message = message + "Height must be filled out\n";
        flag = false;
	}
	
	//verifies if the height is a valid number
	else if (isNaN(height)) {
		document.forms["informationForm"]["height"].className = "error";
        message = message + "Height must be a number\n";
        flag = false;
    }
	else if(height<=0)
	{
		document.forms["informationForm"]["height"].className = "error";
        message = message + "Height must be a number greater than 0\n";
        flag = false;
	}
	
	//verifies if the gender is non-NULL
	if (gender == null || gender == "") {
		document.forms["informationForm"]["gender"].className = "error";
        message = message + "Gender must be selected\n";
        flag = false;
	}
	
	//verifies if the exercise level is non-NULL
	if (exerciseLevel == null || exerciseLevel == "") {
		document.forms["informationForm"]["exerciseLevel"].className = "error";
        message = message + "Exercise Level must be selected\n";
        flag = false;
	}
	
	//display error message if necessary
	if(!flag) alert(message);
	return flag;
	
}

//set class name to focus (normal style to describe non-error)
function setStyleFocus(element)
{
	element.className="focus";
}
</script>
<link rel="stylesheet" type="text/css" href="format.css"></head>
<body >

<!--The upper div creates the upper green block in the top of the webpage  -->
<div  id="upper" style="position:fixed;  top: 0; left:0;">

    <!--creates the 'Logout' button -->
	<div style="position:relative;text-align:left;float: left;"> <input type="button" value="Logout" onclick="location.href='logout.php'" /> </div>
    <!--creates the 'Next Page' button -->
	<div align="right" style="position:relative;text-align:right;float:right;"><input name="nextPage" type="button" value="Next Page" onclick="location.href='foods.php'" style=" margin-right:25px"/></div>
</div>

<!--The information div creates the green block in the left of the webpage  -->
	<div id="information">
	  <form id="informationForm" name="informationForm" method="post" action="" onsubmit="return validateForm()"><b>Information</b>
	            <label for="gender"><br />
	              <br />
	              Gender<br />
        </label>
        <select onfocus="setStyleFocus(this)"  name="gender" id="gender" style="width:99%">
          <option value="" <?php if($gender == '') echo ' selected="selected"'; else echo'';?>>Select</option>
          <option value="Male" <?php if($gender == 'Male') echo ' selected="selected"'; else echo'';?>>Male</option>
          <option value="Female" <?php if($gender == 'Female') echo ' selected="selected"'; else echo'';?>>Female</option>
        </select>
      <br />
          <br />

        <label for="dateOfBirth"> Date of Birth<br />
        </label>
        <input type="date"  onfocus="setStyleFocus(this)"  name="dateOfBirth" id="dateOfBirth" placeholder= " in years"  style="width:99%" <?php echo 'value="'.$dateOfBirth.'" '?>/>
        <input type="hidden" name="age" id="age" <?php echo 'value="'.$age.'" '?>/>
        <br />
        <br />
        <label for="height"> Height</label>
        <br />
<input type="text" name="height" onfocus="setStyleFocus(this)"  placeholder= " in inches" id="height"  style="width:99%" <?php echo 'value="'.$height.'" '?>/>
<br />
<br />
<label for="weight"> Weight<br />
</label>
<input placeholder=" in pounds" onfocus="setStyleFocus(this)"  type="text" name="weight" id="weight"  style="width:99%" <?php echo 'value="'.$weight.'" '?>/>
<br />
<br />
<label for="exerciseLevel"> Exercise Level<br />
</label>
<select onfocus="setStyleFocus(this)"  name="exerciseLevel" id="exerciseLevel"  style="width:100%">
<option value="" <?php if($exerciseLevel == '') echo ' selected="selected"'; else echo'';?>>Select</option>
                                         <option value="Sedentary" <?php if($exerciseLevel == 'Sedentary') echo ' selected="selected"'; else echo'';?>>Sedentary</option>
                                         <option value="Low Active" <?php if($exerciseLevel == 'Low Active') echo ' selected="selected"'; else echo'';?>>Low Active</option>
                                         <option value="Active" <?php if($exerciseLevel == 'Active') echo ' selected="selected"'; else echo'';?>>Active</option>
                                         <option value="Very Active" <?php if($exerciseLevel == 'Very Active') echo ' selected="selected"'; else echo'';?>>Very Active</option>
</select>
<br />
<br />
<input type="submit" name="submitInformation" onfocus="setStyleFocus(this)"  id="submitInformation" value="Submit"   style="width:46%"/>
<input type="reset" name="resetInformation" onfocus="setStyleFocus(this)" id="resetInformation" value="Reset" style="width:47%; margin-left:4%" >
<br />
      </form>
      <br />
</div>
    
    <!--The result div creates the green block in the right of the webpage  -->
    <div id="result">
    <?php echo $result; ?>
    </div>
    <br />
<br />
<br />
<br />
</body>
</html>