<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../styles.css">
<title>PHP: Food Macro Percentage Calculator</title>
</head>
<body>
<h1 class="lesson-h1">PHP: Food Macro Percentage Calculator</h1>
<?php
$error = "";
$message = "";
$calories = htmlentities($_POST['calories']);
$fat = htmlentities($_POST['fat']);
$carbs = htmlentities($_POST['carbs']);
$protein = htmlentities($_POST['protein']);
if(isset($_POST['calories'])){
if(empty($_POST['calories']) || empty($_POST['fat']) || empty($_POST['carbs']) || empty($_POST['protein'])){
$error = "<h3>Error #22: All Fields Are Required</h3>";
} else {
$fat_calories = $fat * 9;
$carb_calories = $carbs * 4;
$protein_calories = $protein * 4;
$fat_percent = $fat_calories / $calories;
$carb_percent = $carb_calories / $calories;
$protein_percent = $protein_calories / $calories;
$total_calories = $fat_calories + $carb_calories + $protein_calories;
if($total_calories > $calories){
$error = "<h3>Error #11: Grams Provided Does Not Match Calorie Count</h3>";
} else {
$message = "<h3 style='text-decoration: underline;'>Macro Percentages</h3>
<h4>Total Calories: $calories</h4><hr>
<h4>Grams of Fat: $fat</h4>
<h4>Fat Percentage: ".substr($fat_percent, 2, 2)."% | $fat_calories/$calories Total Calories</h4><hr>
<h4>Grams of Carbohydrates: $carbs</h4>
<h4>Carbohydrate Percentage: ".substr($carb_percent, 2, 2)."% | $carb_calories/$calories Total Calories</h4><hr>
<h4>Grams of Protein: $protein</h4>
<h4>Protein Percentage: ".substr($protein_percent, 2, 2)."% | $protein_calories/$calories Total Calories</h4><hr>";
}
}
}
?>
<form action="index.php" method="post" class='lesson-form'>
<h4>Macro % Calculator</h4>
<label for="calories">
<input type="number" name="calories" id="calories" placeholder="Calories per Serving">
</label>
<label for="fat">
<input type="number" name="fat" id="fat" placeholder="Grams of Fat">
</label>
<label for="carbs">
<input type="number" name="carbs" id="carbs" placeholder="Grams of Carbs">
</label>
<label for="protein">
<input type="number" name="protein" id="protein" placeholder="Grams of Protein">
</label>
<input type="submit" value="Calculate">
</form>
<?php
echo "<h3>$error</h3>";
echo "<div>$message</div><hr>";
include('../show_code.php');
show_code('index.php');
?>
</body>
</html>