<script type="text/javascript">
function openwin(url, width, height) {
var name = "popup"; // popup name
var width = width; // popup width
var height = height; // popup height
var left = (screen.width - width) / 2 ;
var top = (screen.height - height) / 2;
var windowproperties = "width="+ width +",height="+ height +",left="+ left +",top="+ top +",scrollbars=1";
window.open(url, name, windowproperties);
}
</script>


<?php
if ($_SESSION['FirstName'] == "") {
	echo 'You are not authorized to view this page. <br><br>You may <a href="index.php">log in here.</a>';
	exit;
	}

//require_once ('mysql_connect.php');
$action          = $_GET["a"];
$active = $_POST['chkactive'];
$headerimg = $_POST['headerimg'];

$catkey = $_GET["catkey"];
$showdesc = $_GET["description"];
//test for any categories with 0 as order number...to correct any ordering issues from creating records
$query = "Select * from menuCategory where orderNum ='0'";
	//echo $query;
$rt=mysql_query($query);          // query executed
//echo mysql_error();
while($nt=mysql_fetch_array($rt)){	 
	//get highest ordernum before adding new record - will increase by one and assign to new category
	$query2 = "Select max(orderNum) as maxnum from menuCategory";
	$rt2=mysql_query($query2);          // query executed 
	//echo $query2;
	echo mysql_error();                    // if any error is there that will be printed to the screen
	while($nt2=mysql_fetch_array($rt2)){
		//echo "maxnum=" . $nt2[maxnum] . "<br>";
		$updqry="Update menuCategory set orderNum = '" . ($nt2[maxnum] +1) . "' where RecordKey = " . $nt[RecordKey];	
		//echo $updqry;
		mysql_query($updqry);
	}
	mysql_close;
}
mysql_close;
			
//code to save multiple categories in database
if (isset($_POST['multi_cat_submit']))
{	
	$i = 0;
	foreach ($_POST['input_cat'] as $value)
	{
		if(!empty($value))
		{
			$query1 = "Select max(orderNum) as maxnum from menuCategory";
			$rt = mysql_query($query1);          // query executed 
			while($nt=mysql_fetch_array($rt)){
				 $highnum = ($nt[maxnum] +1);
			}
			 $query2 = "Insert into menuCategory (categoryName, orderNum,description)
			 Values ('" . mysql_real_escape_string($value) . "', '" .  $highnum  . "','".mysql_real_escape_string($_POST['input_text'][$i])."')";
			 mysql_query($query2); 
		}
			 $i++;
	}
	
}

	//echo 'Action = ' . $action; (for testing)
if (($action == "add") && ($_POST['newcat'] !=="")) {
      //check for duplicate before adding
			$query = "Select * from menuCategory where categoryName ='" . mysql_real_escape_string($_POST['newcat']) . "'";
			$rt=mysql_query($query);          // query executed
			echo mysql_error();
			if (mysql_num_rows($rt) == 0) {	//if no existing record by this name... 
			//get highest ordernum before adding new record - will increase by one and assign to new category
			$query = "Select max(orderNum) as maxnum from menuCategory";
			$rt=mysql_query($query);          // query executed 
			echo mysql_error();                    // if any error is there that will be printed to the screen
			while($nt=mysql_fetch_array($rt)){
				$highnum = ($nt[maxnum] +1);
			
				}
			$query = "Insert into menuCategory (categoryName, orderNum) Values ('" . mysql_real_escape_string($_POST['newcat']) . "', '" .  $highnum  . "')";

			if (!mysql_query($query)){
					echo $query;
  					die('Error: ' . mysql_error());
 			 } else {
 			 	//Update flag if new category added
 			 	/*$checkRecordQuery = "Select * from monitoring_changes where user_id = '".$_SESSION['UserID']."'";
 			 	$cResult = mysql_query($checkRecordQuery); 
 			 	if(mysql_num_rows($cResult) == 0){
	 			 	$setFlagQuery = "Insert into monitoring_changes (user_id,user_record_key,flag)
 				 					 Values ('".$_SESSION['UserID']."' , '".$_SESSION['recordKey']."' , 1 )";
 			 		mysql_query($setFlagQuery);
 			 	}else{
 			 		$updateFlagQuery = "Update monitoring_changes set flag=1 where user_id = '".$_SESSION['UserID']."'";
 			 		mysql_query($updateFlagQuery);
 			 	}*/
 			 	include "monitorchanges.php";

				echo "<div align=center><font color=red>Category added successfully.</font></div>";
				
			}
		} else {
       echo "<div align=center><font color=red>!Error: Duplicate category not added.</font></div>";
		}
 }
/*if ($action == "update") {
$checkbox = $_POST['chkdelete'];
//die("updating...");

	if (empty($checkbox)) {   //delete not checked, save other updated info
		
		
		if (isset($_POST["category"])) {	//will not be set and able to update if category selected is disabled...
			$query = "UPDATE menuCategory SET categoryName = '" . mysql_real_escape_string($_POST['category']) . "', Active ='";
			if (empty($active)){
				$query = $query . "0'";
			} else {
				$query = $query . "1'";
			}
			//$query = $query . ", orderNum = '" . $_POST['ordernum'] . "'";
			//if(!empty($_POST['description'])) {
				$query = $query .  ", description = '" . mysql_real_escape_string($_POST['description']) . "'";
			//}
				$query = $query .  ", alias = '" . mysql_real_escape_string($_POST['alias']) . "'";
				
				$query = $query .  ", category_type = '" . $_POST['cattype'] . "'";
				
			if($headerimg>"") {
				$query = $query .  ", headerImg = '" . $headerimg . "'";
				
			}
	    	$query = $query . " WHERE recordKey = '" . $_GET['key'] ."'" ;
			echo $query;
			mysql_query($query) or die(mysql_error());   //execute query
	
			//confirmation message that update worked...
			echo "<font color=red>Category updated successfully.</font>";

		}

	} else { 
		
		
	$query = "DELETE FROM menuCategory WHERE recordKey = '" . $_GET["key"] ."'" ;
	
	

	mysql_query($query) or die(mysql_error());   //execute query

	//confirmation message that delete worked...
	echo "<font color=red>Category deleted successfully.</font>";

		}
	}	//end of update query
	*/

		$query = "SELECT recordKey, categoryName, category_type, active, orderNum, description, headerImg from menuCategory Order By orderNum";
		$rt=mysql_query($query);          		                  
		$rowcount = mysql_num_rows($rt);

echo '<div id="single-admin-button">
<ul>
<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
<a href="editmenuitem.php"><li>EDIT MENU ITEMS</li></a>
<a><li id="multiple_cat_btn" data-popup-id="mulptipleCatPopup">ADD MULTIPLE CATEGORIES</li></a>
</ul>
</div>';
echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new category: <br><input type="text" name="newcat" size=50> <input id="save-button" type="submit" name="save" value="Save"></form>';


echo '<div align="center">';



echo '';
//new section for drag and drop ordering
$query = "SELECT recordKey, categoryName, category_type, active, orderNum, description, headerImg, alias from menuCategory Order By orderNum";
$rt=mysql_query($query);  
echo"<ul id='catsort'><p class='drag-header'><strong>TO CHANGE ORDER:</strong> simply drag below category to desired placement. To edit category settings click the settings icon on the right of the category link.</p>";  
$x=1;  
while($nt=mysql_fetch_array($rt)){
	//add dynamic css
		/*echo"<style>
		#toPopup_$x {
			font-family: 'lucida grande',tahoma,verdana,arial,sans-serif;
			background: none repeat scroll 0 0 #FFFFFF;
			border: 10px solid #ccc;
			border-radius: 3px 3px 3px 3px;
			color: #333333;
			display: none;
			font-size: 14px;
			left: 50%;
			margin-left: -402px;
			position: fixed;
			top: 20%;
			width: 400px;
			z-index: 2;
		}
		</style>";*/
	$class = 'category';
	$alias = $nt['alias'];
		
	if(($nt[categoryName]=="Pizza")||($nt[categoryName]=="Pizza Toppings")||($nt[categoryName]=="Pizza Sauce")||($nt[categoryName]=="Pizza Crust")){
		$pizza ='1';
		$class .= ' pizza';
	}
	if((($nt[categoryName]=="Pizza")||($nt[categoryName]=="Pizza Toppings")||($nt[categoryName]=="Pizza Sauce")||($nt[categoryName]=="Pizza Crust"))&&($nt[active]=='1')){
		$usepizza ='1';
		$pcats = 1;
	}else {
		$usepizza ='0';
	}

	if($nt[categoryName]=="Options") {
		$class .= ' option';
	}
	if(($nt[categoryName]=="Options")&&($nt[active]=='1')){
		$optcat = 1;
	}  
	
	if($nt[categoryName]=="Fixings") {
		$class .= ' fixing';
	}
	if(($nt[categoryName]=="Fixings")&&($nt[active]=='1')){
		$fixcat = 1;
	}

	
	
	$id="cat-".$nt[recordKey];
	echo'<li id="'.$id.'" name="'.$id.'" class="'.$class.'"';
	if($nt['active'] != '1') {
		//echo ' style="display:none;"';
		$status = "<i>(inactive)</i>";
	} else {
		$status ="";
	}
	if($alias<>""){
		$catName = $alias;
		$alias_flag = " <font color='red' size='1'>*<i>Alias</i></font>";
	} else {
		$catName = stripslashes($nt[categoryName]);
		$alias_flag = "";
	}
	
	echo '><span id="catName-'.$nt['recordKey'].'">'.$catName.' '. $status.$alias_flag .'</span><span class="remove-icon"><a class="popup" href="#" alt="Change Category Settings" data-popup-id="'.$nt['recordKey'].'">
	<img src="images/gear-icon.png" title="Category Settings"></a></li>';
	
	echo '<div id="popup_'.$nt['recordKey'].'" class="toPopDiv catSettings">
		<div class="close"></div>
		<span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
		<div id="popup_content"> <!-- your content start -->';
			echo "<h3>&nbsp; &nbsp;Editing settings for category: <strong>".$nt[categoryName]."</strong></h3>
			<form>
			<input type='hidden' name='action' value='update'>";
			echo '<p>Category name:</p><a name="'.$nt[categoryName]. '"></a><input id="catName_'.$nt['recordKey'].'" type="text" name="category" size="75" value="' . $nt[categoryName] . '"';
			if(($pizza=='1')||($nt[categoryName]=='Options')||($nt[categoryName]=='Fixings')){
					echo ' readonly=readonly';
			}
			echo '>';
			
			echo "<br><p>Alias:</p> <input id='alias_".$nt['recordKey']."' type='text' name='alias' size='20' value='". $nt[alias] . "'>";
			
			echo"<br /><br /><p>Category Description:</p>
			<textarea id='catDesc_".$nt['recordKey']."' name='description' cols=75 rows=3>".stripslashes($nt[description])."</textarea><br>
			<i><font size=2>This will show up below the category name on your menu.</font></i><br /><br />";
			//active option
			if(($pizza=='1')||($nt[categoryName]=='Options')||($nt[categoryName]=='Fixings')){
				//don't allow changing status here on these categories
				echo '<input id="catActive_'.$nt['recordKey'].'" type="checkbox" name="chkactive" value="true" checked style="display:none;">';
			} else{
				echo '<p>Active: <input style="margin-top:2px;" id="catActive_'.$nt['recordKey'].'" type="checkbox" name="chkactive"';
				if(!empty($nt[active])){
					echo 'checked=true';
				}
				echo '></p>';
			}
			
			
						//delete category option
			if(($pizza=='1')||($nt[categoryName]=='Options')||($nt[categoryName]=='Fixings')){		
				echo '<input id="catDelete_'.$nt['recordKey'].'" type="checkbox" name="chkdelete" value="true" style="display:none;">';				
			}else{
				echo '<p>Delete: <input style="margin-top:2px;" id="catDelete_'.$nt['recordKey'].'" type="checkbox" name="chkdelete" value="false"></p>';
			}
			
			
			
			//add selector for caegory type
			if(($pizza!=1)&&($nt[categoryName]!="Options")&&($nt[categoryName]!="Fixings")){
				echo'<p>Category type: <select id="catType_'.$nt['recordKey'].'" name="cattype">
				<option value="0"';
				if($nt[category_type]=='0'){echo " selected=selected";}
				echo'>Standard</option>
				<option value="1"';
				if($nt[category_type]=='1'){echo " selected=selected";}
				echo'>Pizza</option>
				</select></p>';
			}
					

			echo '<br /><button id="save-button" class="update-menu" data-cat-id="'.$nt['recordKey'].'">Save Changes</button>';
			echo "</form>
			<br />";

			// header image
			echo "<center><h3>Current header image for category:<em> $nt[CategoryName]</em></h3>";
			if(!empty($nt[headerImg])){
				echo '<span id="catHeaderImg_'.$nt['recordKey'].'">';
				echo "<div id='menu-wrapper'><div align=right><img src='../images/cat-headers/".$nt[headerImg]."'></div></div>";
				echo '</span>';
			} else {
				echo '<span id="catHeaderImg_'.$nt['recordKey'].'">';
				echo "None selected.";
				echo '<br />';
				echo '</span>';
			}
			echo "<a class='popup_cat_img' href='#'>Click here to select a different header image for this category</a>
			<br /><br />";

	echo '</div> <!-- your content end -->
	</div> <!-- to popup end -->';

	$x++;
	
	//reset pizza category flag
	$pizza =0; 
}
echo '<input id="cur-popup-id" type="hidden" name="curCatId" value="" />';
echo '<div id="catImgPopup" class="toPopDiv catHeaderImg">
	<div class="close imgPopup"></div>
	<span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
	<div id="popup_content"> <!-- your content start -->';
	echo "Select an image below to replace this header image.<br>";
	buildImageList("../images/cat-headers/");
echo '</div> <!-- your content end -->
</div> <!-- to popup end -->';

echo '<input id="cur-popup-id" type="hidden" value="" />';
echo"</ul>";
echo "<div id='built-in-box'><p class='built-in-header'><strong>BUILT-IN CATEGORIES</strong><br />For Pizza and Pizza Toppings use the built in categories.</p>";
echo '<ul id="built-in-inside">';
// echo '<li>Pizza categories: ';
// if ($pcats ==1)  {
//      echo '<font color="green"> <b>ON</b></font> - <a href="' . $_SERVER['PHP_SELF'] . '?a=pcatoff"> <font color="blue">Turn off Pizza categories</font></a></li>';
// } else{
//     echo '<font color="red"> <b>OFF</b></font> - <a href="' . $_SERVER['PHP_SELF'] . '?a=pcaton"> <font color="blue">Turn on Pizza categories</font></a></li>';
// }

echo '<li> ';
if ($fixcat ==1)  {
     //echo '<font color="green"> <b>ON</b></font> - <a href="' . $_SERVER['PHP_SELF'] . '?a=fcatoff"> <font color="blue">Turn off Fixings category</font></a>';
} else{
	$fixcat=0;
    //echo '<font color="red"> <b>OFF</b></font> - <a href="' . $_SERVER['PHP_SELF'] . '?a=fcaton"> <font color="blue">Turn on Fixings category</font></a>';
}
echo ' <div style="float:left;">Pizza categories: </div><input type="checkbox" class="switchButton" data-switch-type="pizza" value="'.$fixcat.'"';
if($pcats==1){echo ' checked="checked"';}
echo'>';
echo"</li>";

echo '<li>';
echo ' <div style="float:left;">Fixings: </div><input type="checkbox" class="switchButton" data-switch-type="fixing" value="'.$fixcat.'"';
if($fixcat==1){echo ' checked="checked"';}
echo'>';
echo"</li>";

echo '<li>';
echo ' <div style="float:left;">Options: </div><input type="checkbox" class="switchButton" data-switch-type="option" value="'.$fixcat.'"';
if($optcat==1){echo ' checked="checked"';}
echo'>';
echo"</li>";

// echo '<li>Options: ';
// if ($optcat ==1)  {
//      echo '<font color="green"> <b>ON</b></font> - <a href="' . $_SERVER['PHP_SELF'] . '?a=ocatoff"> <font color="blue">Turn off Options category</font></a></li>';
// } else{
//     echo '<font color="red"> <b>OFF</b></font> - <a href="' . $_SERVER['PHP_SELF'] . '?a=ocaton"> <font color="blue">Turn on Options category</font></a></li>';
// }

	echo '<li><a href="editmenuitem.php"><font color="blue">Edit menu items</font></a></li>
		
		</ul></div></div></table></div>';

//Code for creating multiple categories form
echo '<div id="mulptipleCatPopup" class="toPopDiv ">
			<div id="close_btn"></div>
			<div class="close close_Popup"></div>
				<span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
				<div id="popup_content"> <!-- your content start -->';
				echo "<h3>Create multiple categories:</h3>";
	echo "<form method='POST' action='editmenucat.php'>
			<table id='multiple_cat_table' border='1' cellpadding=0 cellspacing=0 style='text-align:center' >
					<tr>
						<th>S.No</th>
						<th>Category Name</th>
						<th>Category Description</th>
					</tr>
					<tr>
						<td>1</td>
						<td><input type='text' name='input_cat[]' placeholder='enter here'></td>
						<td><textarea row=5 column=20 name='input_text[]'></textarea></td>
					</tr>
					<tr>
						<td>2</td>
						<td><input type='text' name='input_cat[]' placeholder='enter here'></td>
						<td><textarea row=5 column=20 name='input_text[]'></textarea></td>
					</tr>
					<tr>
						<td>3</td>
						<td><input type='text' name='input_cat[]' placeholder='enter here'></td>
						<td><textarea row=5 column=20 name='input_text[]'></textarea></td>
					</tr>
					<tr>
						<td>4</td>
						<td><input type='text' name='input_cat[]' placeholder='enter here'></td>
						<td><textarea row=5 column=20 name='input_text[]'></textarea></td>
					</tr>
			</table>
			<input type='submit' class='mult_btn' value='SAVE' name='multi_cat_submit'>	
		 </form>";

		 echo "<button id='add_more_btn'>+ ADD MORE</button><br><br>";
				
echo '</div> <!-- your content end -->
</div> <!-- to popup end -->';


?>
<script>
//hide and show multiple categories div form
$('#multiple_cat_btn').click(function() {
	$( "#mulptipleCatPopup" ).fadeIn( "slow", function() {
	});
});

$('#close_btn').click(function() {
	$('#mulptipleCatPopup').hide();
});

//append single row in form
$('#add_more_btn').click(function() {
	var rowCount = $('#multiple_cat_table tr').length;
	var html="<tr>"+
				"<td>"+rowCount+"</td>"+
				"<td><input type='text' name='input_cat[]' placeholder='enter here'></td>"+
				"<td><textarea row=5 column=20 name='input_text[]'></textarea></td>"+
			 "</tr>";
	
	$('#multiple_cat_table').append(html);

});

//delete row from form
// $('#del_row_btn').click(function() {
// 	$( "#multiple_cat_table tr:last" ).remove();
// });
</script>

<script>$("#catsort").sortable({
    axis: 'y',
    stop: function (event, ui) {
        var data = $(this).sortable("serialize").toString();
		var idsInOrder = $(this).sortable("toArray").toString();
		//alert(idsInOrder); //popup alert to show data for testing		
		//var elem = document.getElementById("results").value = idsInOrder;	//update results input field for testing
        $.ajax({
            data: data,
            type: 'POST',
            url: 'save_cat_order.php'
        });
    }
});
</script>
<script>
      $(function() {
        $('#basic.demo input').switchButton();

        $('#basic2.demo input').switchButton();

        $("#labels.demo input").switchButton({
          on_label: 'YES',
          off_label: 'NO'
        });

        $("#default.demo input").switchButton({
          checked: false
        });

        $("#labels2-1.demo input").switchButton({
          show_labels: false
        });

        $("#labels2-2.demo input").switchButton({
          labels_placement: "right"
        });

        $("#labels2-3.demo input").switchButton({
          labels_placement: "left"
        });

        $("input.switchButton").switchButton({
          width: 65,
          height: 15,
          button_width: 30,
		  labels_placement: "both"
        });

        $('input.switchButton').change(function(e) {
        	type = $(this).data('switch-type');
        	if(this.checked) {
        		// on
        		option = 'on';
        	}else{
        		// off
        		option = 'off';
        	}

        	update_category(type, option);
        });

        $("#slider-2.demo input").switchButton({
          width: 100,
          height: 40,
          button_width: 70
        });
		
      });
    </script>
	<script type="text/javascript">
	var append = 0;//set value for monitor changes funciontality
	    function update_category(type, option) {
	    	var action = '';
	    	switch(type) {
	    		case 'pizza':
	    			action += 'pcat';
	    			break;
	    		case 'fixing':
	    			action += 'fcat';
	    			break;
	    		case 'option':
	    			action += 'ocat';
	    			break;
	    		default:
	    			console.error('Invalid type.');
	    			return false;
	    	}

	    	switch(option) {
	    		case 'on':
	    			action += 'on';
	    			break;
	    		case 'off':
	    			action += 'off';
	    			break;
	    		default:
	    			console.error('Invalid option.');
	    			return false;
	    	}

	    	request = $.ajax({
	    		url: 'update_menu_cat.php?a='+action
	    	});

	    	request.done(function(response, textStatus) {
	    		// success
	    		if(option == 'on') {
	    			$('.category.'+type).show();
	    		} else {
	    			$('.category.'+type).hide();
	    		}
	    		if(append == 0){
	    			$('#warning-li').remove();
	    			$('.admin-left-sidebar').append('<li id="warning-li"><font color=red>Warning: Menu Export Required</font></li>');
	    			$("#logout-li").attr("onclick", "return warningAction(1,1)");
	    			append++;
	    		}
	    		return true;
	    	});

	    	request.fail(function (jqXHR, textStatus, errorThrown){
		        // log the error to the console
		        console.error(
		            "The following error occured: "+
		            textStatus, errorThrown
		        );
		    });
	    }
	</script>
<?php
//function to get category header images:
function buildImageList($theFolder) {

	// Execute code if the folder can be opened, or fail silently
	if ($contents = @ scandir($theFolder)) {
		// initialize an array for matching files
		$found = array();
		// Create an array of file types
		$fileTypes = array('jpg','jpeg','gif','png');
		// move through the folder, and add filename to $found array if type matches
		$found = array();
		foreach ($contents as $item) {
			$fileInfo = pathinfo($item);
			if (array_key_exists('extension', $fileInfo) && in_array($fileInfo['extension'],$fileTypes)) {
				$found[] = $item;
			}
		}

		// Check the $found array is not empty
		if ($found) {
		  // Sort in natural, case-insensitive order, and populate menu
			natcasesort($found);
			foreach ($found as $filename) {
				$img_name = "../images/cat-headers/" .$filename;
				echo "<span id='category-picture'><a class='saveCatImg' data-img-filename='$filename' href='#'><img src='$img_name' style='border:none;margin:2px;'></a></span>";
			}
		}
	}
}	//end of image list function
?>