<?php	
	include_once('constants.inc.php');
	/**
	 * Handles user interactions within the app
	 *
	 * PHP version 5
	 */
	
	class recipes{
		/**
		 * Database Object
		 *
		 * @var object
		 */
		 private $_db;
		 
		 
		 /**
		 * Creates a db object if it isn't already set
		 *
		 * @param object $db
		 * @return void
		 */
		 public function __construct($db=NULL){
			if(is_object($db)){
				$this->_db = $db;
			}else{
			   $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
			   $this->_db = new PDO($dsn, DB_USER, DB_PASS); 
			}
		 }
		 
		 /**
		 * Get Recipes and group by category or by dish title
		 *
		 * @param str $group
		 * @return array $theRecipes(recipe id, dish title, dish image, description, category)
		 */
		 public function getAllRecipes($group = ""){
			switch($group){
					case "category":
							$groupBy = " ORDER BY c.name";
							break;
					default:
							$groupBy = " ORDER BY r.DishTitle";
							break;
			}
			
			$sql = "SELECT r.ID, r.DishTitle, r.DishImage, r.description, r.approved, c.name AS category FROM recipe_recipes r LEFT JOIN recipe_categories c ON r.Category = c.ID WHERE c.id <> 146" . $groupBy;
			
			if($theQuery = $this->_db->prepare($sql)){
					$theQuery->execute();
					$theRecipes = $theQuery->fetchAll(PDO::FETCH_ASSOC);
					$theQuery->closeCursor();
					return $theRecipes;
			}
		 }
		 
		 /**
		 * Get Single Recipe by id
		 *
		 * @param int $recipeID
		 * @return array $theRecipe
		 */
		 public function getRecipeByID($recipeID){
			if(is_numeric($recipeID)){
				$theId = $recipeID;
			}else{
				$theId = $this->getRecipeIdByName($recipeID);
				$theId = (int)$theId;
			}
			
			//echo $theId;
			
			if($theId != 0){
				$sql = "SELECT r.ID, r.DishTitle, r.DishImage, r.description, r.PrepTime, r.CookTime, r.Serves, r.IngredientDetails AS ingredients, r.PreparationDetails AS directions, r.MainIng, r.approved, c.name AS category FROM recipe_recipes r LEFT JOIN recipe_categories c ON r.Category = c.ID WHERE r.ID = :recipeID";
			
				if($stmt = $this->_db->prepare($sql)){
						$stmt->bindParam(":recipeID", $theId, PDO::PARAM_INT);
						$stmt->execute();
						$theRecipe = $stmt->fetchAll(PDO::FETCH_ASSOC);
						
						$stmt->closeCursor();
						
						return $theRecipe[0];
				}
			}
		 }
		 
		 /**
		 * Get Recipes Id when recipe name is provided
		 *
		 * @param str $theName
		 * @return int $theRecipe['ID']
		 */
		 public function getRecipeIdByName($theName){
			$theName = strtolower(str_replace("-", " ", $theName));
			$sql = "SELECT ID FROM recipe_recipes WHERE DishTitle = LCASE(:name) LIMIT 1";
			if($stmt = $this->_db->prepare($sql)){
					$stmt->bindParam(":name", $theName, PDO::PARAM_INT);
					$stmt->execute();
					$theRecipe = $stmt->fetch(PDO::FETCH_ASSOC);
					
					$stmt->closeCursor();
					return $theRecipe['ID'];
			}
			return 0;
		 }
		 
		 /**
		 * Get Featured recipe. If recipe is assigned today, return that, otherwise get
		 *
		 * @param str $group
		 * @return array $theRecipes(recipe id, dish title, dish image, description, category)
		 */
		 public function getFeaturedRecipe(){
			$todayCheck = $this->getFeaturedRecipeToday(date('Y/m/d'));
			//echo $todayCheck;
			if($todayCheck){
				$theReturn = $this->getFutureFeatRecipe();
			}else{
				$theFuture = $this->getFutureFeatRecipe();
				$thePast = $this->getOnePastFeatRecipe();
				$theReturn = array_merge($thePast, $theFuture);
			}
			
			return $theReturn;
		 }
		 
		 /**
		 * Gets a month's worth of featured recipes, including the last featured recipe if the
		 * first of the month does not have an assigned recipe
		 *
		 * @param date $wantedMonth
		 * @return array $theRecipes
		 */
		 public function getMonthFeaturedRecipe($wantedMonth){
			$featureCheck = $this->featureRecipeExists($wantedMonth);
			
			//If the first day of the month doesn't have an assigned recipe, get the last assigned recipe
			if(!$featureCheck){
				$firstRecipe = $this->getOnePastFeatRecipe($wantedMonth);
			}else{
				$firstRecipe = array();
			}
			
			$futureRecipes = $this->getMonthFeatRecipe($wantedMonth);
			return array_merge($firstRecipe, $futureRecipes);
		 }
		 
		 /**
		 * Gets a month's worth of featured recipes
		 *
		 * @param date $wantedMonth
		 * @return array $theRecipes
		 */
		 public function getMonthFeatRecipe($date){
			$lastDay = strtotime(date('Y-m-t', strtotime($date)));
			$firstDay = strtotime(date('Y-m-01', strtotime($date)));
			
			$sql = "SELECT recipe_id, DishTitle, recipe_start FROM recipe_featured WHERE UNIX_TIMESTAMP(recipe_start) >= " . $firstDay . " AND UNIX_TIMESTAMP(recipe_start) <= " . $lastDay . " ORDER BY recipe_start ASC";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theReturn;
			}
		 }
		 
		 /**
		 * Checks if there is a featured recipe for today
		 *
		 * @param date $wantedMonth
		 * @return array $theRecipes
		 */
		 public function getFeaturedRecipeToday($today){
			$sql = "SELECT recipe_id FROM recipe_featured WHERE UNIX_TIMESTAMP(recipe_start) = UNIX_TIMESTAMP(DATE(NOW())) LIMIT 1";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theReturn = $stmt->fetch(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				if($theReturn && count($theReturn) == 1){
					return true;
				}else{
					return false;
				}
			}
		 }
		 
		 /**
		 * Checking if the provided date has a featured recipe assigned
		 *
		 * @param date $theDate
		 * @return bool
		 */
		 public function featureRecipeExists($theDate){
			$firstDay = strtotime(date('Y-m-01', strtotime($theDate)));
			$sql = "SELECT recipe_id FROM recipe_featured WHERE recipe_start = :date LIMIT 1";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":date", $firstDay, PDO::PARAM_INT);
				$stmt->execute();
				$theReturn = $stmt->fetch(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				if($theReturn && count($theReturn) == 1){
					return true;
				}else{
					return false;
				}
			}
		 }
		 
		 /**
		 * Gets the last featured recipe relative to a given date
		 *
		 * @param date $date
		 * @return array $theReturn
		 */
		 public function getOnePastFeatRecipe($date = null){
			if($date == null){
				$useDate = "DATE(NOW())";
			}else{
				$useDate = "'" . $date . "'";
			}
			
			$sql = "SELECT recipe_id, DishTitle, recipe_start FROM recipe_featured WHERE UNIX_TIMESTAMP(recipe_start) < UNIX_TIMESTAMP(" . $useDate . ") ORDER BY recipe_start DESC LIMIT 1";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theReturn;
			}
		 }
		 
		 /**
		 * Gets all future featured recipes
		 *
		 * @param date $date
		 * @return array $theReturn
		 */
		 public function getFutureFeatRecipe($date = null){
			if($date == null){
				$useDate = "DATE(NOW())";
			}else{
				$useDate = "'" . $date . "'";
			}
			
			
			$sql = "SELECT recipe_id, DishTitle, recipe_start FROM recipe_featured WHERE UNIX_TIMESTAMP(recipe_start) >= UNIX_TIMESTAMP(" . $useDate . ") ORDER BY recipe_start ASC";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theReturn;
			}
		 }
		 
		 
		 /**
		 * Deletes any assigned featured recipe on specified date and then assigns featured recipe to the specified date
		 *
		 * @param int $recipeID
		 * @param str $recipeName
		 * @param date $recipeDate
		 * @return bool
		 */
		 public function setFeaturedRecipe($recipeID, $recipeName, $recipeDate){
			$this->deleteFeaturedRecipe($recipeDate);
			
			//$returnThis = array('result'=>false);
			
			$sql = "INSERT INTO recipe_featured(recipe_id, DishTitle, recipe_start) VALUES(:rID, :name, :date) ";
			
			$recipeID = strip_tags($recipeID);
			$recipeName = strip_tags($recipeName);
			$recipeDate = strip_tags($recipeDate);
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":rID", $recipeID, PDO::PARAM_INT);
				$stmt->bindParam(":name", $recipeName, PDO::PARAM_STR);
				$stmt->bindParam(":date", $recipeDate, PDO::PARAM_STR);
				$stmt->execute();
				$stmt->closeCursor();
				
				return true;
				
				//$returnThis['month'] = $this->getMonthFeatRecipe($recipeDate);
			}
		 }
		 
		 
		 /**
		 * Deletes any assigned featured recipe on specified date
		 *
		 * @param date $theDate
		 * @return bool
		 */
		 public function deleteFeaturedRecipe($theDate){
			$sql = "DELETE FROM recipe_featured WHERE recipe_start = :date";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":date", $theDate, PDO::PARAM_STR);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				if($_SESSION['Edit'] === 1){
						return true;
				}else{
						return false;
				}
			}
		 }
		 
		 
		 /**
		 * Adds recipe to database from $_POST array
		 *
		 * @return array $theRecipes
		 */
		 public function insertRecipe(){
			if($_SESSION['Edit'] === 1){
				$combinedIngredients = "";
				
				foreach($_POST['ingredient'] as $ingredient){
					//echo $ingredient . "<br>";
					$combinedIngredients = $combinedIngredients . "|" . $ingredient;
				}
				
				//remove the initial pike ( | )
				$combinedIngredients = substr($combinedIngredients, 1);
				
				$combinedDirections = "";
				foreach($_POST['directions'] as $direction){
						//echo $ingredient . "<br>";
						$combinedDirections = $combinedDirections . "|" . $direction;
				}
				
				//remove the initial pike ( | )
				$combinedDirections = substr($combinedDirections, 1);
				
				
				$category = $_POST['recipeCategory'] + 0;
				$theImage = substr($_POST['recipe_photoSqu'], (strrpos($_POST['recipe_photoSqu'], '/') + 1));
				$prepTime = $_POST['preptimeBox'] . " " . $_POST['prepTimeFrame'];
				$cookTime = $_POST['cooktimeBox'] . " " . $_POST['cookTimeFrame'];
				$mainIng = str_replace(" ", "_", $_POST['mainIng']);
				$servings = $_POST['servingsBox'] + 0;
				
				$recipeSQL = "INSERT INTO recipe_recipes(DishTitle, Category, description, IngredientDetails, PreparationDetails, MainIng, Serves, PrepTime, CookTime, DishImage) VALUES (:title, :cat, :desc, :ingred, :prepDet, :mainIng, :serve, :prepTime, :cookTime, :img)";
				
				$recipeName = strip_tags($_POST['recipeName']);
				$category = strip_tags($category);
				$combinedIngredients = strip_tags($combinedIngredients);
				$description = strip_tags($_POST['descriptionArea']);
				$combinedDirections = strip_tags($combinedDirections);
				$mainIng = strip_tags($mainIng);
				$servings = strip_tags($servings);
				$prepTime = strip_tags($prepTime);
				$cookTime = strip_tags($cookTime);
				$theImage = strip_tags($theImage);
				
				if($recipeStmt = $this->_db->prepare($recipeSQL)){
					$recipeStmt->bindParam(":title", $recipeName, PDO::PARAM_STR);
					$recipeStmt->bindParam(":cat", $category, PDO::PARAM_INT);
					$recipeStmt->bindParam(":desc", $description, PDO::PARAM_STR);
					$recipeStmt->bindParam(":ingred", $combinedIngredients, PDO::PARAM_STR);
					$recipeStmt->bindParam(":prepDet", $combinedDirections, PDO::PARAM_STR);
					$recipeStmt->bindParam(":mainIng", $mainIng, PDO::PARAM_STR);
					$recipeStmt->bindParam(":serve", $servings, PDO::PARAM_INT);
					$recipeStmt->bindParam(":prepTime", $prepTime, PDO::PARAM_STR);
					$recipeStmt->bindParam(":cookTime", $cookTime, PDO::PARAM_STR);
					$recipeStmt->bindParam(":img", $theImage, PDO::PARAM_STR);
					$theTest = $recipeStmt->execute();
					
					$theID = $this->_db->lastInsertId();
					
					$recipeStmt->closeCursor();
					
					return $theID;
				}
			}else{
				return false;
			}
		 }
		 
		 /**
		 * Gets category names
		 *
		 * @return array $theCategories
		 */
		 public function getCategoryNames(){
				$sql = "SELECT * FROM recipe_categories WHERE type = 'categories'";
				
				if($stmt = $this->_db->prepare($sql)){
						$stmt->execute();
						$theCategories = $stmt->fetchAll(PDO::FETCH_ASSOC);
						$stmt->closeCursor();
						
						return $theCategories;
				}
		 }
		 
		 /**
		 * Gets a produce item by name
		 *
		 * @param date $itemName
		 * @return array $theReturn
		 */
		 public function getProduceItem($itemName){
				$sql = "SELECT id, name, description, photo, searchTerm FROM produceItems WHERE name = :theName";
				
				if($stmt = $this->_db->prepare($sql)){
						$stmt->bindParam(":theName", str_replace("_", " ", $itemName), PDO::PARAM_STR);
						$stmt->execute();
						
						$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
						
						$stmt->closeCursor();
						
						return $theReturn;
				}
		 }
		 
		 
		 /**
		 * Gets all the produce items names
		 *
		 * @return array $theReturn
		 */
		 public function getProduceNames(){
				$sql = "SELECT id, name FROM produceItems";
				
				if($stmt = $this->_db->prepare($sql)){
						$stmt->execute();
						
						$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
						
						$stmt->closeCursor();
						
						return $theReturn;
				}
		 }
		 
		 
		 /**
		 * Searches the database for other recipes that have the same item
		 *
		 * @param date $searchTerm
		 * @return array $theReturn
		 */
		 public function otherRecipes($searchTerm){
				$sql = "SELECT id, DishTitle FROM recipe_recipes WHERE IngredientDetails REGEXP '[[:<:]]$searchTerm'";
				
				if($stmt = $this->_db->prepare($sql)){
						//$stmt->bindParam(":search", $searchTerm, PDO::PARAM_STR);
						$stmt->execute();
						$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
						$stmt->closeCursor();
						
						return $theReturn;
				}
				
		 }
		
		
	}
?>