<!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>Food Categories</title>
<?php
	
include("functions.php");
include("login.php");
	
	//verifying  session for ADM
session_start();
	if (isset($_SESSION['login']))
	{
		$username = $_SESSION['login'];
	}
	else{
		header("location: register.php");
	}

	$categorie = "0100"; //categorie 0100 is Dairy and Egg Products - default categorie
	$filter = "";// filter disabled - default filter
	$save = false; //save changes is false - default value
	
	
//If a categorie is selected, it changes categorie variable, otherwise it will keep default value
if (isset($_POST['categorie'])){
	$categorie = sanitizeMySQL($_POST['categorie']);
}

//If a filter is typed, it changes filter variable, otherwise it will keep default value
if (isset($_POST['searchCategorie'])){
	$filter = sanitizeMySQL($_POST['searchCategorie']);
}

//If the button "save" is pressed, save variable will be true
if (isset($_POST['savePreferences'])){
	$save = true;
}

?>

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

//submit the categorie form when a categorie is pressed
function enviar() {
	document.categorieForm.submit();
}

//set class name to focus (normal style to describe non-error)
function setStyleFocus(element)
{
	element.className="focus";
}

//selects all the like checkboxes at once and deselects all the dislikes checkboxes.
function selectLike(){
	
	//get all check boxes
	var allElems = document.getElementsByTagName('input');
	var likeAll = document.getElementById('likeAll');
	var dislikeAll = document.getElementById('dislikeAll');
	
	for (i = 0; i < allElems.length; i++) {
		if (allElems[i].type == 'checkbox' && allElems[i].value == '1') {
					allElems[i].checked = document.getElementById('likeAll').checked;
			}
		if (allElems[i].type == 'checkbox' && allElems[i].value == '-1'&&document.getElementById('likeAll').checked) {
					allElems[i].checked = false;
			}
	}
	dislikeAll.checked = false;
}

//selects all the dislike checkboxes at once and deselects all the likes checkboxes.
function selectDislike(){
	
	//get all check boxes
	var allElems = document.getElementsByTagName('input');
	var likeAll = document.getElementById('likeAll');
	var dislikeAll = document.getElementById('dislikeAll');	
	
	for (i = 0; i < allElems.length; i++) {
		if (allElems[i].type == 'checkbox' && allElems[i].value == '-1') {
					allElems[i].checked = document.getElementById('dislikeAll').checked;
			}
		if (allElems[i].type == 'checkbox' && allElems[i].value == '1'&&document.getElementById('dislikeAll').checked) {
					allElems[i].checked = false;
			}
	}
	likeAll.checked = false;
}

//this function is activated when a like check box is selected, and it deselects the dislike checkbox of that food.
function optionLike(id){
	
	var dislikeButton = document.getElementById(id);	
	dislikeButton.checked = false;
}

//this function is activated when a dislike check box is selected, and it deselects the like checkbox of that food
function optionDislike(id){
	
	var likeButton = document.getElementById(id);	
	likeButton.checked = false;
}


</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 'Previous Page' and 'Next Page' button -->
    <div align="right" style="position:relative;text-align:right;float:right;"><input name="previousPage" type="button" value="Previous Page" onclick="location.href='index.php'" style=" margin-right:25px"/><input name="nextPage" type="button" value="Next Page" onclick="location.href='mealPlan.php'" style=" margin-right:25px"/></div>

</div>
	  <form id="categorieForm" name="categorieForm" method="post" action="">
      
      
  <!--The information div creates the green block in the left of the webpage  -->
	<div id="information">

	    <label for="Categories">
        Food Categories:<br />
		<select size="23" onfocus="setStyleFocus(this)"  name="categorie" id="categorie" style="width:99%;height:100%">
        <option onclick="enviar()" value="0" <?php if($categorie == "0") echo ' selected="selected" ';?> >All categories</option>
		<?php
		
			//getting all categories
			$query = 'SELECT * FROM fd_group ';
			$result = mysqli_query($db_connection, $query);
			if (!$result) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
			
			//showing categories
			while($row = mysqli_fetch_assoc($result))
			{	
				$row['FdGrp_Desc'];
				echo '<option onclick="enviar()" value="'.$row['FdGrp_CD'].'" ';
				if($categorie == $row['FdGrp_CD']) echo ' selected="selected" '; 
				echo ' >'.$row['FdGrp_Desc'].'</option>';
			}
		?>
        </select>
        </label>

</div>


<!--The result div creates the green block in the right of the webpage  -->
<div id="result">
    
    <!-- creates the filter text box and button  -->
    <div style="position:relative;text-align:left;float: left;">
    <input type="text" id="searchCategorie" name="searchCategorie" value='<?php echo $filter;?>' /><input type="submit" value="Filter" id="filter" /></div>
    
    <!-- creates the save button  -->
    <div  style="position:relative;text-align:right;float: right;"><input type="submit" value="Save" id="savePreferences"  name="savePreferences"/></div>
    <br /><br />
    
    <!-- creates the like/dislike check boxes set  -->
    <div id="partialResults">
    <table width="100%">
        <tr><td width="80%" valign="middle"><b>Description</b></td><td align="right"><b>Like/Dislike</b><br />
        <input type="checkbox" name="likeAll" onclick="selectLike()" id="likeAll"/>
        <input type="checkbox" name="likeAll" onclick="selectDislike()" id="dislikeAll"/>
        </td></tr>
    </table>
    <?php
			//getting foods from database based on the categorie and filter
			if($categorie == "0") $query = "SELECT * FROM food_des WHERE FdGrp_Cd like '%%' ";
			else $query = "SELECT * FROM food_des WHERE FdGrp_Cd like '".$categorie."'  ";
			if (isset($_POST['searchCategorie'])){
				$query .= " AND Long_Desc like '%".$_POST['searchCategorie']."%'";
			}
			$result = mysqli_query($db_connection, $query);
			if (!$result) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
	?>
	<table width="100%">
    <?php
		//showing liked foods and disliked foods
			while($row = mysqli_fetch_assoc($result)){
				
				//if user pressed save button
				if($save){
					
					//delete all dislikes from database
					$query = 'DELETE FROM dislikes WHERE username = "'.$_SESSION['login'].'" AND NDB_No = "'.$row['NDB_No'].'" ';
					$dislikes = mysqli_query($db_connection, $query);
					if (!$dislikes) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
					
					//delete all dislikes from database
					$query = 'DELETE FROM likes WHERE username = "'.$_SESSION['login'].'" AND NDB_No = "'.$row['NDB_No'].'" ';
					$likes = mysqli_query($db_connection, $query);
					if (!$likes) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
					
					//verifies if the checkbox for a food exists
					if(isset($_POST['like'.$row['NDB_No']])){
						//verifies if the checkbox for a food is checked
						if($_POST['like'.$row['NDB_No']]=="-1"){
							$query = 'INSERT INTO dislikes (username, NDB_No) VALUES ("'.$_SESSION['login'].'", "'.$row['NDB_No'].'") ';
							$dislikes = mysqli_query($db_connection, $query);
							if (!$dislikes) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
						}
						//verifies if the checkbox for a food is unchecked
						else if($_POST['like'.$row['NDB_No']]=="1"){
							$query = 'INSERT INTO likes (username, NDB_No) VALUES ("'.$_SESSION['login'].'", "'.$row['NDB_No'].'") ';
							$dislikes = mysqli_query($db_connection, $query);
							if (!$dislikes) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
						}
					}
				}
				
				//initialing variables
				$checkedLike = 'checked="checked"';
				$checkedDislike = 'checked="checked"';
				
				//getting the dislikes
				$query = 'SELECT * FROM dislikes WHERE username = "'.$_SESSION['login'].'" AND NDB_No = "'.$row['NDB_No'].'" ';
				$dislikes = mysqli_query($db_connection, $query);
				if (!$dislikes) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
				
				//getting the likes
				$query = 'SELECT * FROM likes WHERE username = "'.$_SESSION['login'].'" AND NDB_No = "'.$row['NDB_No'].'" ';
				$likes = mysqli_query($db_connection, $query);
				if (!$likes) echo "<script type='text/javascript'>alert('Database query failed');</script>"; 
				
				//if there is no dislike
				if(mysqli_num_rows($dislikes)==0){
					$checkedDislike = '';
				}
				
				//if there is no likes
				if(mysqli_num_rows($likes)==0){
					$checkedLike = '';
				}
				
				//showing the food description, like and dislike check boxes
				echo '<tr><td colspan=2 width="80%"><hr></td></tr><tr><td>';
				echo $row['Long_Desc'].'<br>';
				echo '</td><td align="right"><input name="like'.$row['NDB_No'].'" type="checkbox" onclick="optionLike(\'dislike'.$row['NDB_No'].'\')" id="like'.$row['NDB_No'].'" value="1" '.$checkedLike.'/>
					  <input  name="like'.$row['NDB_No'].'" type="checkbox" onclick="optionDislike(\'like'.$row['NDB_No'].'\')" id="dislike'.$row['NDB_No'].'" value="-1"   '.$checkedDislike.'/>
				</td></tr>';
			}
	?>
    </table>
    </div>
    </div>
            </form>
</body>
</html>