<?php	
	include_once('constants.inc.php');
	/**
	 * Handles user interactions within the app
	 *
	 * PHP version 5
	 */
	
	class stores{
		/**
		 * 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;
				 $this->setOffset();
			 }else{
				$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
				$this->_db = new PDO($dsn, DB_USER, DB_PASS);
				$this->setOffset();
				
				//$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				//$this->_db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
			 }
		 }
		 
		 
		 public function setOffset(){
			date_default_timezone_set("America/Denver");
			
			$now = new DateTime();
			$mins = $now->getOffset() / 60;
			$sgn = ($mins < 0 ? -1 : 1);
			$mins = abs($mins);
			$hrs = floor($mins / 60);
			$mins -= $hrs * 60;
			$offset = sprintf('%+d:%02d', $hrs*$sgn, $mins);
			
			$this->_db->exec("SET time_zone='$offset';");
		 }
		 
		 
		 
		 /**
		 * Gets a feature by its ID
		 *
		 * @param int $featureID
		 * @return array $theFeature
		 * 		{feature_id, feature_name, feature_start, feature_end, feature_common, feature_headline, feature_text, feature_file, feature_photoHor, feature_photoVert, feature_photoSquare, feature_update, feature_link}
		 */
		 public function getFeature($featureID){
			$sql = "SELECT * FROM features WHERE feature_id = :featureID";
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":featureID", $featureID, PDO::PARAM_INT);
				$stmt->execute();
				$theFeature = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				return $theFeature;
			}
		 }
		 
		 
		 /**
		 * Adds a new feature to the database (despite the name)
		 *
		 * @return int $theID || bool false
		 */
		 public function newFeature(){
			if($_SESSION['Edit'] === 1){
				if($_POST['feature_id'] == ""){ //New feature
					//sanitize the data
					$feat_name = strip_tags($_POST['feat_name']);
					$feat_headline = strip_tags($_POST['feat_headline']);
					$feat_text = strip_tags($_POST['feat_text']);
					$feat_file = strip_tags($_POST['feat_file']);
					$feat_link = strip_tags($_POST['feat_link']);
					$datepicker_start = strip_tags($_POST['datepicker_start']);
					$datepicker_end = strip_tags($_POST['datepicker_end']);
					$feat_photoHor = strip_tags($_POST['feat_photoHor']);
					$feat_photoVer = strip_tags($_POST['feat_photoVer']);
					$feat_photoSqu = strip_tags($_POST['feat_photoSqu']);
					
					
					
					$theLink = str_replace("http://", "", $_POST['feat_link']);
					$theLink = "http://" . $theLink;
					if($theLink == "http://"){
						$theLink = null;
					}
					
					$common = 0;
					
					$sql = "INSERT INTO features(feature_name, feature_start, feature_end, feature_common, feature_headline, feature_text, feature_photoHor, feature_photoVert, feature_photoSquare, feature_update, feature_link) VALUES (:name, :start, :end, :common, :headline, :text, :imgHor, :imgVert, :imgSquare, :user, :link)";
					if($stmt = $this->_db->prepare($sql)){
						$stmt->bindParam(":name", $feat_name, PDO::PARAM_STR);
						$stmt->bindParam(":start", $datepicker_start, PDO::PARAM_STR);
						$stmt->bindParam(":end", $datepicker_end, PDO::PARAM_STR);
						$stmt->bindParam(":common", $common, PDO::PARAM_INT);
						$stmt->bindParam(":headline", $feat_headline, PDO::PARAM_STR);
						$stmt->bindParam(":text", $feat_text, PDO::PARAM_STR);
						$stmt->bindParam(":imgHor", $feat_photoHor, PDO::PARAM_STR);
						$stmt->bindParam(":imgVert", $feat_photoVer, PDO::PARAM_STR);
						$stmt->bindParam(":imgSquare", $feat_photoSqu, PDO::PARAM_STR);
						$stmt->bindParam(":user", $_SESSION['Username'], PDO::PARAM_STR);
						$stmt->bindParam(":link", $theLink, PDO::PARAM_STR);
						$stmt->execute();
						$theID = $this->_db->lastInsertId();
						$stmt->closeCursor();
						//echo "theID: " . $theID;
						return $theID;
					}
				}
			}else{ //Updating an existing feature
				return false;
		    }
		 }
		 
		 
		 /**
		 * Duplicates a feature from the afsshareportal.com sharegroup feed into the local database
		 *
		 * @return int $theID
		 */
		 public function duplicateSGFeature(){
			if($_SESSION['Edit'] === 1){
				if($_POST['feature_id'] == ""){ //New feature
					//sanitize the data
					$feat_name = strip_tags(stripslashes($_POST['feature_name']));
					$feat_headline = strip_tags(stripslashes($_POST['feature_headline']));
					$feat_text = strip_tags(stripslashes($_POST['feature_text']));
					
					$theFolder = "http://www.afsshareportal.com/";
					
					$imgSquare = $theFolder . $_POST['feature_photoSquare'];
					$imgVert = $theFolder . $_POST['feature_photoVert'];
					$imgHoriz = $theFolder . $_POST['feature_photoHor'];
					
					$common = 0;
					
					$sql = "INSERT INTO features(feature_name, feature_start, feature_end, feature_common, feature_headline, feature_text, feature_photoHor, feature_photoVert, feature_photoSquare, feature_update) VALUES (:name, :start, :end, :common, :headline, :text, :imgHor, :imgVert, :imgSquare, :user)";
					if($stmt = $this->_db->prepare($sql)){
						$stmt->bindParam(":name", $feat_name, PDO::PARAM_STR);
						$stmt->bindParam(":start", $_POST['feature_start'], PDO::PARAM_STR);
						$stmt->bindParam(":end", $_POST['feature_end'], PDO::PARAM_STR);
						$stmt->bindParam(":common", $common, PDO::PARAM_INT);
						$stmt->bindParam(":headline", $feat_headline, PDO::PARAM_STR);
						$stmt->bindParam(":text", $feat_text, PDO::PARAM_STR);
						$stmt->bindParam(":imgHor", $imgHoriz, PDO::PARAM_STR);
						$stmt->bindParam(":imgVert", $imgVert, PDO::PARAM_STR);
						$stmt->bindParam(":imgSquare", $imgSquare, PDO::PARAM_STR);
						$stmt->bindParam(":user", $_SESSION['Username'], PDO::PARAM_STR);
						$stmt->execute();
						$theID = $this->_db->lastInsertId();
						$stmt->closeCursor();
						//echo "theID: " . $theID;
						return $theID;
					}
				}
			}else{ //Updating an existing feature
				return false;
		    }
		 }
		 
		 
		 /**
		 * Gets current, old, and future features
		 *
		 * @return int $theID
		 */
		 public function getFeatures(){
			$theFeatures = array();
			
			$theFeatures['current'] = $this->getCurrentFeatures();
			$theFeatures['old'] = $this->getOldFeatures();
			$theFeatures['future'] = $this->getFutureFeatures();
			
			return $theFeatures;
		 }
		 
		 /**
		 * Gets current features
		 *
		 * @return array $theFeatures
		 */
		 public function getCurrentFeatures(){
			$today = $this->formatDateUnix();
			
			//Includes features with today as a start day and today as an end day
			$sql = "SELECT feature_id, feature_name, feature_start, feature_end, feature_common, feature_headline, feature_text, feature_photoHor, feature_photoVert, feature_photoSquare, feature_link, 'webOnly' as feature_file  FROM features WHERE UNIX_TIMESTAMP(feature_start) <= " . $today . " AND UNIX_TIMESTAMP(feature_end) >= " . $today . " ORDER BY feature_common DESC, feature_end";
			
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theFeatures = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theFeatures;
			}
		 }
		 
		 /**
		 * Gets old features
		 *
		 * @return array $theFeatures
		 */
		 public function getOldFeatures(){
			$today = $this->formatDateUnix();
			
			//Includes features with end day before, and not including, today
			$sql = "SELECT feature_id, feature_name, feature_start, feature_end, feature_common, feature_headline, feature_text, feature_photoHor, feature_photoSquare, feature_link FROM features WHERE UNIX_TIMESTAMP(feature_end) < " . $today . " ORDER BY feature_end";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theFeatures = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theFeatures;
			}
		 }
		 
		 
		 /**
		 * Gets future features
		 *
		 * @return array $theFeatures
		 */
		 public function getFutureFeatures(){
			$today = $this->formatDateUnix();
			
			$sql = "SELECT feature_id, feature_name, feature_start, feature_end, feature_common, feature_headline, feature_text, feature_photoHor, feature_photoSquare, feature_link FROM features WHERE UNIX_TIMESTAMP(feature_start) > " . $today . " ORDER BY feature_start";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theFeatures = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theFeatures;
			}
		 }
		 
		 
		 /**
		 * Duplicates a feature from local database
		 *
		 * @param int $featureID
		 * @return int $theID
		 */
		 public function duplicateFeature($featureID){
			$sql = "INSERT INTO features (feature_name, feature_start, feature_end, feature_headline, feature_text, feature_file, feature_photoHor, feature_photoVert, feature_photoSquare, feature_update, feature_link) SELECT feature_name, feature_start, feature_end, feature_headline, feature_text, feature_file, feature_photoHor, feature_photoVert, feature_photoSquare, feature_update, feature_link FROM features WHERE feature_id = :fID";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":fID", $featureID, PDO::PARAM_INT);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$theID = $this->_db->lastInsertId();
				
				$stmt->closeCursor();
				return $theID;
			}
		 }
		 
		 
		 /**
		 * Updates a feature value based on column, id
		 *
		 * @param str $column_id (column name and feature id separated by underscore)
		 * @param mixed $value
		 * @return array $returnThis
		 */
		 public function updateFeatureValue($column_id, $value){
			list($column, $featureID) = explode("_", $column_id);
			$useColumn = "feature_" . $column;
			
			if($column == "link"){
				$value = str_replace("http://", "", $value);
				$value = "http://" . $value;
			}
			
			$sql = "UPDATE features SET " . $useColumn . " = :newValue, feature_update = :user WHERE feature_id = :fID";
			
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":newValue", $value, PDO::PARAM_STR);
				$stmt->bindParam(":user", $_SESSION['Username'], PDO::PARAM_STR);
				$stmt->bindParam(":fID", $featureID, PDO::PARAM_INT);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				
				$returnThis = array("value" => stripslashes($value), "featureID" => $featureID, "user" => $_SESSION['Username'], "session" => $_SESSION);
				return $returnThis;
			}
		 }
		 
		 
		 /**
		 * Removes a sharegroup promotion from showing up on the site
		 *
		 * @param int $feature_id (feature from afsshareportal.com)
		 * @param int $canEdit (not usually passed)
		 * @return array $returnThis (always returns result, on success returns action also)
		 */
		 public function blacklistFeature($feature_id, $canEdit = 0){
			$returnThis = Array();
			if(isset($_SESSION['Edit'])){
				$canEdit = $_SESSION['Edit'];
		    }
			
			//Check if the id is already in database
			$sqlCheck = "SELECT * FROM blacklist WHERE featureID = :fID";
			if($stmtCheck = $this->_db->prepare($sqlCheck)){
				$stmtCheck->bindParam(":fID", $feature_id, PDO::PARAM_INT);
				$stmtCheck->execute();
				$rowCount = $stmtCheck->rowCount();
				$stmtCheck->closeCursor();
			}
			
			//add to database if it does not exist, delete from database if it exists
			if($rowCount == 0){
				$sql = "INSERT INTO blacklist(featureID) VALUES (:fID)";
				$theAction = "insert";
			}else if($rowCount == 1){
				$sql = "DELETE FROM blacklist WHERE featureID = :fID";
				$theAction = "delete";
			}
			
			
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":fID", $feature_id, PDO::PARAM_INT);
				if($canEdit == 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				$returnThis['result'] = true;
				$returnThis['action'] = $theAction;
				return $returnThis;
			}else{
				$returnThis['result'] = false;
				return $returnThis;
			}
		 }
		 
		 
		 /**
		 * Returns all sharegroup promotions that have been blacklisted
		 *
		 * @param int $feature_id (feature from afsshareportal.com)
		 * @param int $canEdit (not usually passed)
		 * @return array $returnThis (always returns result, on success returns action also)
		 */
		 public function getAllBlacklisted(){
			$sql = "SELECT * FROM blacklist";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theReturn = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theReturn;
			}
		 }
		 
		 
		 /**
		 * Formats today's date as Unix
		 *
		 * @return str strtotime($todayFormat)
		 */
		 public function formatDateUnix(){
			$today = getDate();
	
			$theMonth = strlen($today['mon']) == 1 ? "0" : "";
			$theDay = strlen($today['mday']) == 1 ? "0" : "";
			
			$todayFormat =  $today['year'] . "-" . $theMonth . $today['mon'] . "-" . $theDay . $today['mday']; 
			return strtotime($todayFormat);
		 }
		 
		 
		 /**
		 * Gets all of the specials for a specific date
		 *
		 * @param str $date
		 * @return array $theItem || false
		 * 		{deli_id, deli_date, item_price, item_desc, deli_type}
		 */
		 public function getLunchDay($date, $deliType = false){
			$deliTypeSQL = "";
			
			if($deliType !== "false" && $deliType !== false){
				$deliTypeSQL = " AND deli_type = :deliType " ;
			}
			
			$lunchSQL = "SELECT * FROM deli_day WHERE deli_date = :date " . $deliTypeSQL . " ORDER BY deli_type ASC";
			
			if($deliQuery = $this->_db->prepare($lunchSQL)){
				$deliQuery->bindParam(":date", $date, PDO::PARAM_STR);
				if($deliType !== "false" && $deliType !== false){
					$deliQuery->bindParam(":deliType", $deliType, PDO::PARAM_INT);
				}
				$deliQuery->execute();
				$theItem = $deliQuery->fetchAll(PDO::FETCH_ASSOC);
				$deliQuery->closeCursor();
			}
			
			if(count($theItem) > 0){
				return $theItem;
			}else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Removes a special for a specific date based on its type
		 *
		 * @param str $date
		 * @param int $type
		 * @return bool 
		 */
		 public function removeLunchDay($date, $type){
			
			$typeVal = $type + 0;
			
			$deleteSQL = "DELETE FROM deli_day WHERE deli_date = :date AND deli_type = :type";
			
			if($deleteQuery = $this->_db->prepare($deleteSQL)){
				$deleteQuery->bindParam(":date", $date, PDO::PARAM_STR);
				$deleteQuery->bindParam(":type", $typeVal, PDO::PARAM_INT);
				$deleteQuery->execute();
				$deleteQuery->closeCursor();
				
				return true;
			}
			return false;
		 }
		 
		 
		 /**
		 * Removes a special based on date and type and then adds special (can't have two specials with same type on same day)
		 *
		 * @param str $date
		 * @param int $id
		 * @param str $price
		 * @param str $desc
		 * @param int $type
		 * @return bool
		 */
		 public function updateLunchDay($date, $id, $price, $desc, $type){
			$typeVal = $type + 0;
			
			$date = strip_tags($date);
			$price = strip_tags($price);
			$desc = strip_tags($desc);
			
			$deleteSQL = "DELETE FROM deli_day WHERE deli_date = :date AND deli_type = :type";
			
			if($deleteQuery = $this->_db->prepare($deleteSQL)){
				$deleteQuery->bindParam(":date", $date, PDO::PARAM_STR);
				$deleteQuery->bindParam(":type", $typeVal, PDO::PARAM_INT);
				$deleteQuery->execute();
				$deleteQuery->closeCursor();
				
				$addSQL = "INSERT INTO deli_day(deli_id, deli_date, item_price, item_desc, deli_type) VALUES(:id, :date, :price, :desc, :type)";
				if($addQuery = $this->_db->prepare($addSQL)){
					$addQuery->bindParam(":id", $id, PDO::PARAM_INT);
					$addQuery->bindParam(":date", $date, PDO::PARAM_STR);
					$addQuery->bindParam(":price", $price, PDO::PARAM_STR);
					$addQuery->bindParam(":desc", $desc, PDO::PARAM_STR);
					$addQuery->bindParam(":type", $typeVal, PDO::PARAM_INT);
					$addQuery->execute();
					$addQuery->closeCursor();
				}
				
				return true;
			}
			
			return false;
		 }
		 
		 
		 /**
		 * Gets all specials for a specified time frame
		 *
		 * @param str $startDate
		 * @param str $endDate
		 * @return array $theItem || false
		 * 		{deli_id, deli_date, item_price, item_desc, deli_type}
		 */
		 public function getLunchWeek($startDate, $endDate, $deliType = false){
			//$deliType = 2;
			
			
			$startExplode = explode("-", $startDate);
			$endExplode = explode("-", $endDate);
			$deliTypeSQL = "";
			
			if($deliType !== false){
				$deliTypeSQL = " deli_type = :deliType AND " ;
			}
			
			$weekSQL = "SELECT * FROM deli_day WHERE " . $deliTypeSQL . " UNIX_TIMESTAMP(deli_date) >= " . mktime(0,0,0,$startExplode[1],$startExplode[2], $startExplode[0]) . " AND UNIX_TIMESTAMP(deli_date) <= " . mktime(0,0,0,$endExplode[1],$endExplode[2], $endExplode[0]) . " ORDER BY deli_date";
			
			if($weekQuery = $this->_db->prepare($weekSQL)){
				if($deliType !== false){
					$weekQuery->bindParam(":deliType", $deliType, PDO::PARAM_INT);
				}
				
				$weekQuery->execute();
				$theWeek = $weekQuery->fetchAll(PDO::FETCH_ASSOC);
				$numRows = $weekQuery->rowCount();
				$weekQuery->closeCursor();
			}
			if($numRows > 0){
				return $theWeek;
			}
			else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Adds item for specials
		 *
		 * @return int $theID || false
		 */
		 public function addDeliItem(){
			$sql = "INSERT INTO deli(deli_name, deli_photo) VALUES (:name, :photo)";
			
			$itemName = strip_tags($_POST['itemName']);
			$photo = strip_tags($_POST['photo']);
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":name", $itemName, PDO::PARAM_STR);
				$stmt->bindParam(":photo", $photo, PDO::PARAM_STR);
				$stmt->execute();
				$theID = $this->_db->lastInsertId();
				$stmt->closeCursor();
				
				return $theID;
			}else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Gets a special item
		 *
		 * @param int $itemID
		 * @return array $theItem || false
		 * 		{deli_id, deli_name, deli_photo}
		 */
		 public function getDeliItem($itemID){
			$sql = "SELECT * FROM deli WHERE deli_id = :iID";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":iID", $itemID, PDO::PARAM_INT);
				$stmt->execute();
				
				$theItem = $stmt->fetch(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theItem;
			}else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Gets all deli items
		 *
		 * @return array $theItem
		 * 		{deli_id, deli_name, deli_photo}
		 */
		 public function getDeliItems(){
			$sql = "SELECT deli_id, deli_name, deli_photo FROM deli ORDER BY deli_name";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				
				$theItem = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theItem;
			}else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Updates a special item's value based on column, id
		 *
		 * @param str $column_id (column name and feature id separated by underscore)
		 * @param mixed $value
		 * @return array $returnThis
		 */
		 public function updateDeliItem($column_id, $value){
			//echo "In Update Deli Item";
			list($column, $deliID) = explode("_", $column_id);
			$useColumn = "deli_" . $column;
			
			$sql = "UPDATE deli SET " . $useColumn . " = :newValue WHERE deli_id = :dID";
			
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":newValue", $value, PDO::PARAM_STR);
				$stmt->bindParam(":dID", $deliID, PDO::PARAM_INT);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				
				$returnThis = array("value" => stripslashes($value), "deliID" => $deliID, "column" => $useColumn, "session" => $_SESSION);
				return $returnThis;
			}
		 }
		 
		 
		 
		 /**
		 * Adds an event
		 *
		 * @return int $theID || false
		 */
		 public function addEvent(){
			$theLocs = '';
			
			if(isset($_POST['event_location'])){
				foreach($_POST['event_location'] as $aLoc){
					$theLocs .= $aLoc . ', ';
				}
				
				$theLocs = substr($theLocs, 0, -2);
			}
			
			$cleanPost = array_map('strip_tags', $_POST);
			
			$sql = "INSERT INTO events(event_name, event_date, event_desc, event_location, event_start, event_end) VALUES (:name, :date, :desc, :locs, :start, :end)";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":name", $cleanPost['event_name'], PDO::PARAM_STR);
				$stmt->bindParam(":date", $cleanPost['datepicker_start'], PDO::PARAM_STR);
				$stmt->bindParam(":desc", $cleanPost['event_desc'], PDO::PARAM_STR);
				$stmt->bindParam(":locs", $theLocs, PDO::PARAM_STR);
				$stmt->bindParam(":start", $cleanPost['timepicker_start'], PDO::PARAM_STR);
				$stmt->bindParam(":end", $cleanPost['timepicker_end'], PDO::PARAM_STR);
				$stmt->execute();
				$theID = $this->_db->lastInsertId();
				$stmt->closeCursor();
				
				return $theID;
			}else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Gets all events
		 *
		 * @return array $theEvents
		 */
		 public function getAllEvents(){
			$sql = "SELECT event_id, event_name, event_date, event_desc, event_location, event_start, event_end FROM events ORDER BY UNIX_TIMESTAMP(event_date)";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				
				$theEvents = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theEvents;
			}
		 }
		 
		 
		 /**
		 * Gets an event by id
		 *
		 * @param int $eventID
		 * @return array $theEvents
		 */
		 public function getOneEvent($eventID){
			$sql = "SELECT event_id, event_name, event_date, event_desc, event_location, event_start, event_end FROM events WHERE event_id = :eID";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":eID", $eventID, PDO::PARAM_INT);
				$stmt->execute();
				
				$theEvents = $stmt->fetch(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theEvents;
			}
		 }
		 
		 
		 /**
		 * Gets events that happen within the next 60 days
		 *
		 * @return array $theEvents
		 */
		 public function getCurrentEvents($numDays = 60){
			$today = $this->formatDateUnix();
			$numDays = (int) $numDays;
			$daysOffset = $today + (($numDays*24)*60*60);
			
			$sql = "SELECT event_id, event_name, event_date, event_desc, event_location, event_start, event_end FROM events WHERE UNIX_TIMESTAMP(event_date) >= " . $today . " AND UNIX_TIMESTAMP(event_date) <= " . $daysOffset . " ORDER BY UNIX_TIMESTAMP(event_date)";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				
				$theEvents = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theEvents;
			}
			
		 }
		 
		 
		 /**
		 * Updates an event's value based on column, id
		 *
		 * @param str $column_id (column name and feature id separated by underscore)
		 * @param mixed $value
		 * @return array $returnThis
		 */
		 public function updateEventValue($column_id, $value){
			list($column, $eventID) = explode("_", $column_id);
			$useColumn = "event_" . $column;
			$sql = "UPDATE events SET " . $useColumn . " = :newValue WHERE event_id = :eID";
			
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":newValue", $value, PDO::PARAM_STR);
				$stmt->bindParam(":eID", $eventID, PDO::PARAM_INT);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				
				$returnThis = array("value" => stripslashes($value), "eventID" => $eventID, "user" => $_SESSION['Username'], "session" => $_SESSION);
				return $returnThis;
			}
		 }
		 
		 
		 /**
		 * Get locations
		 *
		 * @return array $theLocations
		 */
		 public function getStoreLocations(){
			$sql = "SELECT store_id, store_name, store_update, store_id_share, brdata_store_num FROM stores ORDER BY store_name";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				
				$theLocations = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				return $theLocations;
			}
		 }
		 
		 
		 /**
		 * Get a store's directory items
		 *
		 * @param int $locationID
		 * @return array $theItems
		 */
		 public function getDirectoryItemsStore($locationID){
			$sql = "SELECT i.item_name, i.item_id, si.aisle FROM items i LEFT JOIN store_item si ON i.item_id = si.item_id AND si.store_name = :locID ORDER BY i.item_name ASC";
			//$sql = "SELECT * FROM store_item si RIGHT JOIN items i ON si.item_id = i.item_id UNION SELECT * FROM store_item si LEFT JOIN items i ON si.item_id = i.item_id WHERE si.store_name = :locID";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":locID", $locationID, PDO::PARAM_INT);
				$stmt->execute();
				
				$theItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theItems;
			}
		 }
		 
		 
		 /**
		 * Get a store's directory items that have a value
		 *
		 * @param mixed $locationID
		 * @return array $theReturn
		 */
		 public function getUsedDirectoryItems($locationID){
			$theReturn = array();

			if(is_numeric($locationID)){
				$theId = $locationID;
			}else{
				$theId = $this->getLocationIdByName($locationID);
				$theId = (int)$theId;
			}
			
			$nameSql = "SELECT store_name, store_update FROM stores WHERE store_id = :lID";
			
			if($nameStmt = $this->_db->prepare($nameSql)){
				$nameStmt->bindParam(":lID", $theId, PDO::PARAM_INT);
				$nameStmt->execute();
				$theName = $nameStmt->fetch(PDO::FETCH_ASSOC);
				$nameStmt->closeCursor();
				
				$theReturn['storeInfo'] = $theName;
			}else{
				$theReturn['storeInfo'] = "Store not found";
			}
			
			$sql = "SELECT i.item_name, i.item_id, si.aisle FROM items i INNER JOIN store_item si ON i.item_id = si.item_id AND si.store_name = :locID ORDER BY i.item_name ASC";
			//$sql = "SELECT * FROM store_item si RIGHT JOIN items i ON si.item_id = i.item_id UNION SELECT * FROM store_item si LEFT JOIN items i ON si.item_id = i.item_id WHERE si.store_name = :locID ORDER BY i.item_name ASC";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":locID", $theId, PDO::PARAM_INT);
				$stmt->execute();
				
				$theItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				$theReturn['items'] = $theItems;
			}else{
				$theReturn['items'] = "No Items";
			}
			
			return $theReturn;
		 }
		 
		 public function getDirectoryItems(){
			$sql = "SELECT * FROM items ORDER BY item_name";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				
				$theItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theItems;
			}
		 }
		 
		 
		 /**
		 * Commits the store's input of aisle information
		 *
		 * @return bool
		 */
		 public function processDirectory(){
			if($_SESSION['Edit'] === 1){
				$sqlCheck = "SELECT item_id FROM store_item WHERE item_id = :iID AND store_name = :sID";
				
				if($checkStmt = $this->_db->prepare($sqlCheck)){
					foreach($_POST['item'] as $key => $value){
						$checkStmt->bindParam(":iID", $key, PDO::PARAM_INT);
						$checkStmt->bindParam(":sID", $_POST['store_id'], PDO::PARAM_INT);
						$checkStmt->execute();
						
						$count = $checkStmt->rowCount();
						
						//echo $key . " (" . $count . "): " . $value . "<br>";
						
						if($count > 0 && $value != ""){
							$sql = "UPDATE store_item SET aisle = :aisle WHERE item_id = :itemID AND store_name = :storeID";
							$aisleNeeded = true;
						}else if($value != ""){
							$sql = "INSERT INTO store_item (item_id, store_name, aisle) VALUES (:itemID, :storeID, :aisle)";
							$aisleNeeded = true;
						}else if($count > 0 && $value == ""){
							$sql = "DELETE FROM store_item WHERE item_id = :itemID AND store_name = :storeID";
							$aisleNeeded = false;
						}
						
						if($stmt = $this->_db->prepare($sql)){
							if($aisleNeeded == true){
								$stmt->bindParam(":aisle", strip_tags($value), PDO::PARAM_STR);
							}
							$stmt->bindParam(":itemID", $key, PDO::PARAM_INT);
							$stmt->bindParam(":storeID", $_POST['store_id'], PDO::PARAM_INT);
							$stmt->execute();
						}
					}
					$stmt->closeCursor();
					$checkStmt->closeCursor();
				}
				
				$updateSQL = "UPDATE stores SET store_update = NOW() WHERE store_id = :sID";
				
				if($updateStmt = $this->_db->prepare($updateSQL)){
					$updateStmt->bindParam(":sID", $_POST['store_id'], PDO::PARAM_INT);
					$updateStmt->execute();
					$updateStmt->closeCursor();
				}
				
				return true;
			}
			return false;
		 }
		 
		 
		 /**
		 * Add a directory item to the database
		 *
		 * @param str $theItem
		 * @return bool
		 */
		 public function newDirItem($theItem){
			$sql = "INSERT INTO items (item_name) VALUES (:theItem)";
			$theItem = strip_tags($theItem);
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":theItem", $theItem, PDO::PARAM_STR);
				$stmt->execute();
				$stmt->closeCursor();
				return true;
			}else{
				return false;
			}
		 }
		 
		 
		 /**
		 * Return 15 results from the directory based on a search term
		 *
		 * @param str $term
		 * @param str $store (store name)
		 * @return array $return_arr
		 */
		 public function directorySearch($term, $store){
			$sql = "SELECT * FROM store_item si LEFT JOIN items i ON si.item_id = i.item_id WHERE si.store_name = :store AND i.item_name LIKE '%$term%' ORDER BY item_name ASC LIMIT 15";
			
			$return_arr = array();
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":store", $store, PDO::PARAM_INT);
				$stmt->execute();
				
				$theResult = $stmt->fetchAll(PDO::FETCH_ASSOC);
				
				foreach($theResult as $aResult){
					$row_a = array();
					
					$itemName = $aResult['item_name'];
					$itemID = $aResult['item_id'];
					$itemLocation = $aResult['aisle'];
					
					$row_a['value'] = $itemName;
					$row_a['item_name'] = $itemName;
					$row_a['item_id'] = $itemID;
					$row_a['aisle'] = $itemLocation;
					
					array_push($return_arr, $row_a);
				}
				
				return $return_arr;
				//var_dump($return_arr);
			}
		 }
		 
		 /**
		 * Add no purchase necessary entry to database. Limits one entry per email address per promotion
		 *
		 * @return array $theReturn
		 * 	{action, name, email, thePromotion, error}
		 */
		 public function newNoPurchaseEntry(){
			$theReturn = array();
			
			$sql = "SELECT * FROM noPurchase WHERE theEmail = :email AND thePromotion = :promo";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":email", $_POST['email'], PDO::PARAM_STR);
				$stmt->bindParam(":promo", $_POST['thePromotion'], PDO::PARAM_STR);
				$stmt->execute();
				$numRows = $stmt->rowCount();
				$stmt->closeCursor();
				
				if($numRows > 0){
					$theReturn['action'] = "Error";
					$theReturn['name'] = $_POST['name'];
					$theReturn['email'] = $_POST['email'];
					$theReturn['thePromotion'] = $_POST['thePromotion'];
					$theReturn['error'] = "The email address has already been used.";
				}
				else{
					$sqlInsert = "INSERT INTO noPurchase(userName, theEmail, thePhone, theLocation, thePromotion) VALUES (:user, :email, :phone, :location, :promo)";
					
					$cleanPost = array_map('strip_tags', $_POST);
					
					if($insertStmt = $this->_db->prepare($sqlInsert)){
						$insertStmt->bindParam(":user", $cleanPost['name'], PDO::PARAM_STR);
						$insertStmt->bindParam(":email", $cleanPost['email'], PDO::PARAM_STR);
						$insertStmt->bindParam(":phone", $cleanPost['phone'], PDO::PARAM_STR);
						$insertStmt->bindParam(":location", $cleanPost['location'], PDO::PARAM_INT);
						$insertStmt->bindParam(":promo", $cleanPost['thePromotion'], PDO::PARAM_STR);
						$insertStmt->execute();
						//$theID = $this->_db->lastInsertId();
						$theReturn['name'] = $_POST['name'];
						$theReturn['email'] = $_POST['email'];
						$theReturn['action'] = "added";
						$theReturn['thePromotion'] = $_POST['thePromotion'];
						
						$insertStmt->closeCursor();
					}
				}
				
				return $theReturn;
			}
		 }
		 
		 
		 /**
		 * Get promotions in no purchase table
		 *
		 * @return array $theResults
		 */
		 public function getNoPurchasePromos(){
			$sql = "SELECT thePromotion FROM noPurchase GROUP BY thePromotion";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
			}
			
			return $theResults;
		 }
		 
		 /**
		 * Get entries for no purchase promotions
		 *
		 * @param int $thePromo
		 * @return array $theResults
		 */
		 public function getNoPurchaseEntries($thePromo){
			
			$sql = "SELECT * FROM noPurchase WHERE thePromotion = :promo";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":promo", $thePromo, PDO::PARAM_STR);
				$stmt->execute();
				$theResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
			}
			
			return $theResults;
		 }
		 
		 /**
		 * Get entries for no purchase promotions into CSV file
		 *
		 * @param int $thePromo
		 * @return string $file
		 */
		 public function getNoPurchaseEntriesCSV($thePromo){
			$sql = "SELECT np.userName, np.theEmail, np.thePhone, s.store_name FROM noPurchase np LEFT JOIN stores s ON s.store_id = np.theLocation WHERE thePromotion = :promo";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":promo", $thePromo, PDO::PARAM_STR);
				$stmt->execute();
				$theResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
			}
			
			return $theResults;
		 }
		 
		 
		 /**
		 * Create a new hot deal
		 *
		 * @return array $theReturn
		 * 		{result, deal_id}
		 */
		 public function newHotDeal(){
			$sql = "INSERT INTO hot_deals(deal_name, deal_start, deal_end, deal_photo) VALUES (:name, :start, :end, :photo)";
			$theReturn = Array();
			
			$cleanPost = array_map('strip_tags', $_POST);
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":name", $cleanPost['deal_name'], PDO::PARAM_STR);
				$stmt->bindParam(":start", $cleanPost['datepicker_start'], PDO::PARAM_STR);
				$stmt->bindParam(":end", $cleanPost['datepicker_end'], PDO::PARAM_STR);
				$stmt->bindParam(":photo", $cleanPost['deal_photo'], PDO::PARAM_STR);
				$stmt->execute();
				
								
				$theID = $this->_db->lastInsertId();
				
				$theReturn['deal_id'] = $theID;
				$theReturn['result'] = true;
				
				$stmt->closeCursor();
			}else{
				$theReturn['result'] = false;
			}
			
			return $theReturn;
		 }
		 
		 
		 /**
		 * Get hot deal by id
		 *
		 * @param int $theID
		 * @return array $theResult
		 */
		 public function getHotDeal($theID){
			$sql = "SELECT * FROM hot_deals WHERE deal_id = :dID LIMIT 1";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":dID", $theID, PDO::PARAM_INT);
				$stmt->execute();
				$theResult = $stmt->fetch(PDO::FETCH_ASSOC);
				
				$stmt->closeCursor();
				
				return $theResult;
			}
		 }
		 
		 
		 /**
		 * Updates a hot deal's value based on column, id
		 *
		 * @param str $column_id (column name and feature id separated by underscore)
		 * @param mixed $value
		 * @return array $returnThis
		 */
		 public function updateDealValue($column_id, $value){
			list($column, $dealID) = explode("_", $column_id);
			$useColumn = "deal_" . $column;
			$sql = "UPDATE hot_deals SET " . $useColumn . " = :newValue WHERE deal_id = :fID";
			
			$value = strip_tags($value);
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":newValue", $value, PDO::PARAM_STR);
				$stmt->bindParam(":fID", $dealID, PDO::PARAM_INT);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				
				$returnThis = array("value" => stripslashes($value), "dealID" => $dealID, "user" => $_SESSION['Username'], "session" => $_SESSION);
				return $returnThis;
			}
		 }
		 
		 
		 /**
		 * Get all hot deals
		 *
		 * @return array $theFeatures
		 */
		 public function getHotDeals(){
			$sql = "SELECT deal_id, deal_name, deal_start, deal_end, deal_photo FROM hot_deals ORDER BY deal_name";
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theFeatures = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theFeatures;
			}
		 }
		 
		 
		 /**
		 * Gets deals that are active starts before today and ends after today
		 *
		 * @param str $term
		 * @param str $store (store name)
		 * @return array $return_arr
		 */
		 public function getActiveDeals(){
			$today = $this->formatDateUnix();
			
			$sql = "SELECT deal_id, deal_name, deal_start, deal_end, deal_photo FROM hot_deals WHERE UNIX_TIMESTAMP(deal_start) <= " . $today . " AND UNIX_TIMESTAMP(deal_end) >= " . $today . " ORDER BY deal_end";
			
			
			if($stmt = $this->_db->prepare($sql)){
				$stmt->execute();
				$theFeatures = $stmt->fetchAll(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				
				return $theFeatures;
			}
		 }
		 
		 
		 /**
		 * Takes a store name and gets the id
		 *
		 * @param str $locName
		 * @return int $theID
		 */
		 public function getLocationIdByName($locName){
			$sql = "SELECT store_id FROM stores WHERE LCASE(store_name) = :locName";
				
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":locName", $locName, PDO::PARAM_STR);
				$stmt->execute();
				$theID = $stmt->fetch();
				$stmt->closeCursor();
				
				
				return $theID[0];
			}
		 }
		 
		 
		 /**
		 * Deletes items from different tables
		 *
		 * @param str $type
		 * @param str $id
		 * @return bool
		 */
		 public function deleteUniversal($type, $id){
			switch($type){
				case "feature":
					$table = "features";
					$col = "feature_id";
					break;
				case "deliItem":
					$table = "deli";
					$col = "deli_id";
					break;
				case "event":
					$table = "events";
					$col = "event_id";
					break;
				case "directory":
					$table = "items";
					$col = "item_id";
					break;
				case "hotDeal":
					$table = "hot_deals";
					$col = "deal_id";
					break;
				default:
					return false;
			}
			
			$sql = "DELETE FROM " . $table . " WHERE " . $col . " = :theID";
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":theID", $id, PDO::PARAM_INT);
				if($_SESSION['Edit'] === 1){
						$stmt->execute();
				}
				$stmt->closeCursor();
				if($_SESSION['Edit'] === 1){
						return true;
				}else{
						return false;
				}
			}
		 }
		 
		 /**
		 * Takes a store name and gets the id
		 *
		 * @param str $locName
		 * @return int $theID
		 */
		 public function getFacebookWall($location, $data = null){
			$theFile = $this->getCachedFile($location);
			
			if(is_null($data)){
				return $theFile;
			}else {
				if(!$theFile){
					$cacheFile = $this->getFileName($location);
					file_put_contents($cacheFile, $data);
					
					return true;
				}else {
					return $theFile;
				}
			}
			
		 }
		 
		 private function getCachedFile($file){
			$cacheFile = $this->getFileName($file);
			
			if(file_exists($cacheFile)){
				return file_get_contents($cacheFile);
			}else{
				return false;
			}
		 }
		
		 private function getFileName($file){
			$theSiteParts = explode(".", $_SERVER['HTTP_HOST']);
			$theSite = $theSiteParts[0];
			
			$baseDir = dirname(dirname($_SERVER['DOCUMENT_ROOT']));
			return $baseDir . "/fbwall/" . $theSite . "-" . $file . ".php";
		 }
	}
?>
