<?php
  require('inc/sessionStart.php');
  
  $action = "manage";
  
  if(isset($_GET['a'])){
    if($_GET['a'] == "manage"){
	  $action = "manage";
    }
  }
?>

<?php
  $pageTitle = "Administration: Recipe Management";
  $pageDescription = "";
  $pageKeywords = "";
?>

<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/header.php");
?>
<script async src="//afsshareportal.com/js/moment.min.js"></script>
<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/mainNav.php");
  include_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.recipes.inc.php");
  $recipeObj = new recipes();
?>

    <section class="container">
      <div id="blankBuffer" class="carousel-buffer"></div>
      <div id="noEditError" class="hideObject">
			<div class="alert alert-error">
				  <a class="close" data-dismiss="alert" href="#">x</a>You can only <span id="noEditErrorText"></span> if you have editing capabilities.
			</div>
	  </div>
	  <section class="container" id="storePortal">
	    <div class="row">
		  <div class="span3 sideNav">
			<?php include('inc/sideNav.php'); ?>
		  </div>
		  
		  <div class="span9 portalContent">
			<div class="contentContain">
			  <div id="recipeContain">
				<?php
				  if($action == "base"){
				?>
				  <!--<h2>All Recipes</h2>-->
				  
					<div id="currentFeatured"></div>
					<h2>Select a Recipe to be featured on your homepage.</h2>
					<div id="sharedRecipes" class="clearfix">
					  <h3>Shared Recipes</h3>
					</div>
					<div id="localRecipes" class="clearfix">
					  <h3>Your Recipes <a href="/admin/addRecipes.php"><i class="icon-plus-sign muted"></i></a></h3>
					   <?php
						$allRecipes = $recipeObj->getAllRecipes();
						
						foreach($allRecipes as $aRecipe){
					  ?>
						<div id="recipe_<?php echo $aRecipe['ID']; ?>" class="recipeContain clearfix">
						  <img src="/Kickstrap/img/<?php echo $aRecipe['DishImage']; ?>" width="70" height="70" style="float:left; margin-right:15px;" alt="Picture for <?php echo $aRecipe['DishTitle']; ?>">
						  <h4><?php echo $aRecipe['DishTitle']; ?></h4>
						  <p><?php echo $aRecipe['category']; ?></p>
						  <span class="homeFeatureRecipe btn">Feature on home page</span>
						</div>
					  <?php
						}// end foreach($allRecipes as $aRecipe)
					  ?>
					</div> <!-- end #localRecipes -->
				  
				<?php
				  }else if($action == "manage"){
					$theDate = date('Y-m-01');
					$theRecipes = $recipeObj->getMonthFeaturedRecipe($theDate);
					
				?>
				  <h2>Manage Featured Recipe <span class="floatRight btn"><a href="/admin/addRecipes.php">Add Recipe</a></span></h2>
				  <div id="recipeManage" class="clearfix">
					<div id="calendar">
					  <?php include('inc/calendar.php'); ?>
					  
					  <div style="clear:both;"></div>
					  <div id="changeSpecialContainer"></div>
					</div>
					<div id="viewLunch">
					  <div id="changeLunchContain">
						
					  </div>
					</div>
				  </div>
				  <h3>Select a recipe to assign to a day</h3>
				  <?php
						$allRecipes = $recipeObj->getAllRecipes();
						if(count($allRecipes) > 0){
				  ?>
					<div id="localRecipesCal" class="clearfix">
					  <h5 class="recipeHeader">Your Recipes</h5>
					   
					  <?php
						foreach($allRecipes as $aRecipe){
					  ?>
						<div id="recipe_<?php echo $aRecipe['ID']; ?>" class="recipeContain clearfix">
						  <img src="/Kickstrap/img/<?php echo $aRecipe['DishImage']; ?>" width="70" height="70" style="float:left; margin-right:15px;" alt="Picture for <?php echo $aRecipe['DishTitle']; ?>">
						  <h4><?php echo $aRecipe['DishTitle']; ?></h4>
						  <p><?php echo $aRecipe['category']; ?></p>
						  <span class="homeFeatureRecipe btn">Feature on home page</span>
						</div>
					  <?php
						}// end foreach($allRecipes as $aRecipe)
					  ?>
					</div> <!-- end #localRecipes -->
				  <?php
						}
				  ?>
				  <div id="sharedRecipesCal" class="clearfix">
					
				  </div>
				  
				  <script>
					var theRecipes = <?php echo json_encode($theRecipes); ?>;
					var theDate = '<?php echo $theDate; ?>';
					
					var theDateComponents = theDate.split("-");
					var curMonth = theDateComponents[1];
					
					theRecipes[0]['recipe_start'] = theDate;
					
					$("body").on("click", ".day", function(){
					  $(".pickedDay").removeClass("pickedDay");
					  $(this).addClass("pickedDay");
					  var theDate = $(this).attr("rel");
					  
					  var anotherDateComponent = theDate.split("-");
					  var thisMonth = anotherDateComponent[1];
					  
					  
					  if(thisMonth != curMonth){
						curMonth = thisMonth;
						$.ajax({
						  type: "POST",
						  url: "lookUp.php",
						  data: "action=getMonthFeaturedRecipe&theDate=" + theDate,
						  dataType: "json",
						  success: function(theResponse){
							theRecipes = theResponse;
							theRecipes[0]['recipe_start'] = theDate.slice(0,-2) + "01";
							doDayClick(theDate);
						  }
						});
					  }else{
						doDayClick(theDate);
					  }
					  
					});
					
					function doDayClick(theDate){
					  $.each(theRecipes, function(){
						$(".day[rel=" + this.recipe_start + "]").addClass("assignedDay");
					  });
					  
					  var arrayIndex = -1;
					  var closestDate = getClosestDate(theDate);
					  
					  $.each(theRecipes, function(key, value){
						if(value.recipe_start == closestDate){
						  arrayIndex = key;
						  return false;
						}
					  });
					  
					  
					  var wantedRecipe = null;
					  $.each(allRecipes, function(){
						if(this['ID'] == theRecipes[arrayIndex]['recipe_id'] && this['DishTitle'] == theRecipes[arrayIndex]['DishTitle']){
						  wantedRecipe = this;
						  return false;
						}
					  });
					  
					  var featuredHTML = "";
					  featuredHTML = "<h3>Featured Recipe for " + theDate + "</h3>";
					  featuredHTML += "<div id='recipe_" + wantedRecipe['ID'] + "' class='recipeContain clearfix'>";
					  featuredHTML += "<img src='//afsshareportal.com/Kickstrap/img/recipes/" + wantedRecipe['DishImage'] + "' width='70' height='70' style='float:left; margin-right:15px;' alt='" + wantedRecipe['DishTitle'] + "'>";
					  featuredHTML += "<h4>" + wantedRecipe['DishTitle'] + "</h4>";
					  featuredHTML += "<p>" + wantedRecipe['category'] + "</p>";
					  if($(".day[rel=" + theDate + "]").is(".assignedDay")){
						featuredHTML += "<p class='removeFeatureRecipe btn'>Remove Featured Recipe</p>";
					  }
					  featuredHTML += "</div>";
					  
					  
					  $("#changeLunchContain").html(featuredHTML);
					}
					
					function getClosestDate(theDate){
					  var closestDate = "";
					  
					  if($(".pickedDay").is(".assignedDay")){
						closestDate = theDate;
					  }else{
						var theCounter = theDate.substr(theDate.length - 2);
						var theBase = theDate.substr(0, theDate.length - 2);
						
						for(theCounter; theCounter > 0; theCounter--){
						  if(theCounter < 10){
							var wantedDate = theBase + "0" + theCounter;
						  }else{
							var wantedDate = theBase + theCounter;
						  }
						  
						  if($(".day[rel='" + wantedDate + "']").is(".assignedDay")){
							closestDate = wantedDate;
							break;
						  }
						}
					  }
					  return closestDate;
					}
					
					function getFeaturedRecipeCal(){
					  $("#today_date").click();
					};
				  </script>
				<?php
				  }
				?>
			  </div> <!-- end #recipeContain -->
			</div> <!-- end #contentContain -->
		  </div> <!-- end .portalContent -->
	    </div> <!-- end .row -->
	    
      </section>
      
    </section>
      
    
  
  <script src="js/includeJS.js"></script>
  <script>
	var allRecipes = "";
	var theAction= "<?php echo $action; ?>";
	getRecipesShared();
	
   
    function getRecipesShared(){
	  $.ajax({
		type: "GET",
		url: base_site + "lookUpFeatures.php",
		data: "action=getAllRecipes",
		dataType: "jsonp",
		jsonp : "callback",
		jsonpCallback: "recipecallback"
	  });
	}
	
	function recipecallback(theResponse){
	  var theHTML = "";
	  var theCount = 0;
	  allRecipes = theResponse;
	  
	  $.each(theResponse, function(){
		if(this.DishImage !== null){
		  theHTML += "<div id='recipe_" + this.ID + "' class='recipeContain clearfix'>";
		  theHTML += "<img src='//afsshareportal.com/Kickstrap/img/recipes/" + this.DishImage + "' width='70' height='70' style='float:left; margin-right:15px;' alt='" + this.DishTitle + "'>";
		  theHTML += "<h4>" + this.DishTitle + "</h4>";
		  theHTML += "<p>" + this.category + "</p>";
		  theHTML += "<span class='homeFeatureRecipe btn'>Feature on home page</span>";
		  theHTML += "</div>";
		}
	  });
	  
	  if(theAction == "base"){
		getFeaturedRecipe();
		$("#sharedRecipes").append(theHTML);
	  }else{
		getFeaturedRecipeCal();
		theHTML = "<h5 class='recipeHeader'>Shared Recipes</h5>" + theHTML;
		$("#sharedRecipesCal").append(theHTML);
	  }
	}
	
	
	function getFeaturedRecipe(){
	  $.ajax({
	    type: "POST",
	    url: "interactions.php",
	    data: "action=getFeatureRecipe",
	    dataType: "json",
	    success: function(theResponse){
		  //console.log(theResponse);
		  $(".featuredRecipe, .featuredRecipeFuture").remove();
		  var theCount = 0;
		  
		  $.each(theResponse, function(){
			//console.log(this);
			if(theCount == 0){
			  setFeature($("#recipe_" + this.recipe_id));
			  $("#recipe_" + this.recipe_id).prepend("<p class='featuredRecipe'>Featured Recipe <span class='theRecipeDate hideObject'>" + this.recipe_start + "</span> <a href='#' class='removeFeatureRecipe'><i class='icon-trash pull-right'></i></a></p>");
			}else{
			  $("#recipe_" + this.recipe_id).prepend("<p class='featuredRecipeFuture'>Featured Recipe Starting: <span class='theRecipeDate'>" + this.recipe_start + "</span> <a href='#' class='removeFeatureRecipe'><i class='icon-trash pull-right'></i></a></p>");
			}
			
			
			theCount++;
		  });
	    }
      });
	}
	
	$("body").on("click", ".removeFeatureRecipe", function(e){
	  e.preventDefault();
	  var theDate = $(".pickedDay").attr("rel");
	  
	  var wantedDate = getClosestDate(theDate);
	  
	  $.ajax({
	    type: "POST",
	    url: "interactions.php",
	    data: "action=removeFeatRecipe&date=" + wantedDate,
	    dataType: "json",
	    success: function(theResponse){
		  var reference = $("#changeLunchContain");
		  if(theResponse){
			reference.prepend("<div class='deleteThisIn2 alert alert-success'>You have removed this feature</div>");
			
			$.each(theRecipes, function(key, value){
			  if(value['recipe_start'] == theDate){
				theRecipes.splice(key,1);
				return false;
			  }
			});
			
			$(".pickedDay").removeClass("assignedDay").click();
		  }
	    }
      });
	});
	
	function setFeature(referObj){
	  //console.log(referObj);
	  $(".featuredRecipe").remove();
	  
	  $("#currentFeatured").html("");
	  
	  referObj.clone().appendTo("#currentFeatured").attr("id", "").prepend("<a href='/admin/recipes.php?a=manage' class='btn pull-right'>Manage Featured Recipe</a><h3>Current Feature on Home Page</h3>").children("input, .homeFeatText").remove();
	  
	  
	  //referObj.prepend("<p class='featuredRecipe'>Featured Recipe</p>");
	}
	
	
	$("body").on("click", "#nextMonth, #prevMonth", function(){
		var type = $(this).attr("id");
		var months = [ "January", "February", "March", "April", "May", "June", 
				 "July", "August", "September", "October", "November", "December" ];
		//var theDate = "20130701";
		var theDate = $(".calendar").attr("id");
		
		if(type == "nextMonth"){
		  var dateComponents = new moment(theDate).add('M', 1);
		}else{
		  var dateComponents = new moment(theDate).subtract('M', 1);
		}
		
		
		var monthNum = ("0" + (dateComponents.month() + 1)).slice(-2);
		var month = dateComponents.format("MMMM");
		var year = dateComponents.year();
		var dayDate = ("0" + dateComponents.date()).slice(-2);
		var refDate = year + "-" + monthNum + "-" + dayDate;
		var newCalendar = buildCalendar(month, year, refDate);
		
		$("#calendar").html(newCalendar);
		$.each(theRecipes, function(){
		  $(".day[rel=" + this.recipe_start + "]").addClass("assignedDay");
		});
		//$("#calendar").append("<div style='clear:both'></div>" + deliDropdown);
	});
	
	
   $(document).ready(function() {
	  $("body").on("click", ".homeFeatureRecipe", function(e){
		$("#featRecipeDateContain").remove();
		var theHTML = "";
		theHTML += "<div style='clear:both' id='featRecipeDateContain'><label for='datepicker_start'>Start Date:</label><div id= 'datepicker_start1' class='input-append date datepicker' data-date-format='yyyy-mm-dd' data-date='<?php echo date('Y-m-d'); ?>'><input type='text' id='datepicker_start' name='datepicker_start' value='' readonly='readonly' required/><span class='add-on'><i class='icon-calendar'></i></span></div><div class='btn-group'><span class='btn' id='setFeaturedBtn'>Set Featured Recipe</span><span class='btn' id='cancelBtn'>Cancel</span></div></div>";
		$(this).parents(".recipeContain").append(theHTML).css("height", "auto");
		
		datepickerInit();
	  });
	  
	  $("body").on("click", "#setFeaturedBtn", function(e){
		$(":checkbox").prop("checked", false);
		var $this = $(this);
		var recipeID = $(this).parents(".recipeContain").attr("id").replace("recipe_", "");
		var recipeName = $(this).parents(".recipeContain").children("h4").text();
		var theDate = $("#datepicker_start").val();
		
		$(this).parents(".recipeContain").attr("style", "");
		
		$.ajax({
		  type: "POST",
		  url: "interactions.php",
		  data: "action=setFeatureRecipe&recipeID=" + recipeID + "&recipeName=" + recipeName + "&date=" + theDate,
		  dataType: "json",
		  success: function(theResponse){
			//SET ASSIGNED DAY ON PICKED DAY
			theRecipes.push({"DishTitle": recipeName, "recipe_id": recipeID, "recipe_start": theDate});
			$("#featRecipeDateContain").remove();
			$(".pickedDay").addClass("assignedDay").click();
		  }
		});
		
	  });
	  
	  $("body").on("click", "#cancelBtn", function(e){
		$(this).parents("#featRecipeDateContain").remove();
	  });
	  
	  function datepickerInit(){
		var now = new moment().set('hour', 0);
		var theMonth = now.format("MM");
		
		now = $(".pickedDay").attr("rel");
		
		var dateStart = $("#datepicker_start1").datepicker({
		  onRender: function(date){
			$("#datepicker_start").val(now);
		  }
		}).on('changeDate', function(ev){
		  dateStart.hide();
		}).data('datepicker');
	  }
   });
  </script>
  

<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/footer.php'); ?>
