<?php	
	/**
	 * Handles user interactions within the app
	 *
	 * PHP version 5
	 */
	
	class users{
		/**
		 * 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); 
			} */

			// ticket # 19376 VMT Website admin access issue

			$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
			$this->_db = new PDO($dsn, DB_USER, DB_PASS);
			
		}
		
		
		/**
		* Creates the user account if email doesn't exist in db
		*
		* @return string    -a message that indicates the status
		*/
		public function createAccount(){
		    $verified = 1;
			$emailExplode = explode("@", $_POST['useremail'], 2);
			$userName = $emailExplode[0];	   
				   
			if(count($emailExplode) == 1){
				$theEmail = $userName . "@" . str_replace("www.", "", $_SERVER['SERVER_NAME']);
				//$theEmail = $userName;
			}else{
				$theEmail = $_POST['useremail'];
			}
			
		   $sql = "SELECT COUNT(Username) AS theCount FROM users WHERE user_email=:email";
		   if($stmt = $this->_db->prepare($sql)){
			   $stmt->bindParam(":email", $theEmail, PDO::PARAM_STR);
			   $stmt->execute();
			   $row = $stmt->fetch();
			   
			   if($row['theCount'] != 0){
				   return false;
			   }
			   $stmt->closeCursor();
		   }
			
			$userName = strip_tags($userName);
			$theEmail = strip_tags($theEmail);
			$password = strip_tags($_POST['password']);
			
		    $sql2 = "INSERT INTO users(Username, user_email, Password) VALUES (:name, :email, MD5(:pass))";
		    if($stmt = $this->_db->prepare($sql2)){
				$stmt->bindParam(":name", $userName, PDO::PARAM_STR);
				$stmt->bindParam(":email", $theEmail, PDO::PARAM_STR);
				$stmt->bindParam(':pass', $password, PDO::PARAM_STR);
				$stmt->execute();
				$theID = $this->_db->lastInsertId();
				$stmt->closeCursor();
				$_SESSION['Username'] = htmlentities($userName, ENT_QUOTES);
				$_SESSION['LoggedIn'] = 1;
				$_SESSION['Edit'] = 0;
				$_SESSION['UserID'] = $theID;
				return TRUE;
			}else{
				return FALSE;
			}
		}
		
		public function createAccountInAdmin(){
		    $verified = 1;
			$emailExplode = explode("@", $_POST['useremail'], 2);
			$userName = $emailExplode[0];	   
			
			if(count($emailExplode) == 1){
				$theEmail = $userName . "@" . str_replace("www.", "", $_SERVER['SERVER_NAME']);
				//$theEmail = $userName;
			}else{
				$theEmail = $_POST['useremail'];
			}
		   
		   $sql = "SELECT COUNT(Username) AS theCount FROM users WHERE user_email=:email";
		   if($stmt = $this->_db->prepare($sql)){
			   $stmt->bindParam(":email", $theEmail, PDO::PARAM_STR);
			   $stmt->execute();
			   $row = $stmt->fetch();
			   
			   if($row['theCount'] != 0){
				   return false;
			   }
			   $stmt->closeCursor();
		   }
			
			$userName = strip_tags($userName);
			$theEmail = strip_tags($theEmail);
			$password = strip_tags($_POST['password']);
		   
		    $sql2 = "INSERT INTO users(Username, user_email, Password) VALUES (:name, :email, MD5(:pass))";
		    if($stmt = $this->_db->prepare($sql2)){
				$stmt->bindParam(":name", $userName, PDO::PARAM_STR);
				$stmt->bindParam(":email", $theEmail, PDO::PARAM_STR);
				$stmt->bindParam(':pass', $password, PDO::PARAM_STR);
				$stmt->execute();
				$stmt->closeCursor();
				return true;
			}else{
				return false;
			}
		}
		
		
		public function changeAPassword($theUser, $thePass){
			if($_SESSION['Edit'] === 1){
				$sql = "UPDATE users SET Password = MD5(:pass) WHERE UserID = :uID LIMIT 1";
				try{
					$stmt = $this->_db->prepare($sql);
					$stmt->bindParam(":pass", $thePass, PDO::PARAM_STR);
					$stmt->bindParam(":uID", $theUser, PDO::PARAM_STR);	
					$stmt->execute();
					$stmt->closeCursor();
					
					return TRUE;
				} catch (PDOException $e){
					return FALSE;
				}
			}
		}
		
		/**
		* Checks credentials and logs in the user
		*
		* @return boolean    TRUE on success and FALSE on failure
		*/
		public function accountLogin()
		{
			$emailExplode = explode("@", $_POST['useremail'], 2);
			$userName = $emailExplode[0];
			
			if(count($emailExplode) == 1){
				$theEmail = $userName . "@" . str_replace("www.", "", $_SERVER['SERVER_NAME']);
				//$theEmail = $userName;
			}else{
				$theEmail = $_POST['useremail'];
			}
			
			//NEED TO SEPERATE THE CREATION FROM LOGIN
			
			$sql = "SELECT UserID, Username, user_edit FROM users WHERE user_email = :user AND Password = MD5(:pass) LIMIT 1";
			
			try{
			   $stmt = $this->_db->prepare($sql);
			   $stmt->bindParam(':user', $theEmail, PDO::PARAM_STR);
			   $stmt->bindParam(':pass', $_POST['password'], PDO::PARAM_STR);
			   $stmt->execute(); 
			   if($stmt->rowCount() == 1){
					$row = $stmt->fetch(PDO::FETCH_ASSOC);
					$_SESSION['Username'] = htmlentities($userName, ENT_QUOTES);
					$_SESSION['UserID'] = $row['UserID'];
					$_SESSION['LoggedIn'] = 1;
					$_SESSION['Edit'] = (int) $row['user_edit'];
					
					$log = $_SERVER['DOCUMENT_ROOT'] . "/admin/inc/loggedUsers.txt";
					
					$theEntry = date("Y-m-d H:i:s") . " - " . htmlentities($userName, ENT_QUOTES) . " (Logged In)\n";
					
					$handle = fopen($log, "a+") or die("can't open file");
					fwrite($handle, $theEntry);
					fclose($handle);
				   
					return TRUE;
			   } else{
				   return FALSE;
			   }
			   
			}catch(PDOException $e){
				return FALSE;
			}
		}
		
		/**
		* Checks credentials and logs in the user with Facebook Credentials.
		* Creates account if it doesn't exist.
		*
		* @return boolean    TRUE on success and FALSE on failure
		*/
		public function accountLoginFB()
		{
			$sql = "SELECT Username, user_edit FROM users WHERE user_email = :user AND Password = MD5(:pass) LIMIT 1";
			
			try{
			   $stmt = $this->_db->prepare($sql);
			   $stmt->bindParam(':user', $_POST['useremail'], PDO::PARAM_STR);
			   $stmt->bindParam(':pass', $_POST['password'], PDO::PARAM_STR);
			   $stmt->execute(); 
			   if($stmt->rowCount() == 1){
				   $row = $stmt->fetch(PDO::FETCH_ASSOC);
				   $userName = htmlentities($_POST['username'], ENT_QUOTES);
				   $_SESSION['Username'] = $userName;
				   $_SESSION['LoggedIn'] = 1;
				   $_SESSION['Edit'] = (int) $row['user_edit'];
				   
				   $log = $_SERVER['DOCUMENT_ROOT'] . "/admin/inc/loggedUsers.txt";
					
					$theEntry = date("Y-m-d H:i:s") . " - " . htmlentities($userName, ENT_QUOTES) . " (Logged In Facebook)\n";
					
					$handle = fopen($log, "a+") or die("can't open file");
					fwrite($handle, $theEntry);
					fclose($handle);
					
					
				   return TRUE;
			   } else{
				   $sql2 = "INSERT INTO users(Username, user_email, Password) VALUES (:name, :email, MD5(:pass))";
				   
				   $userName = strip_tags($_POST['username']);
				   $theEmail = strip_tags($_POST['useremail']);
				   $password = strip_tags($_POST['password']);
				   
				   if($stmt = $this->_db->prepare($sql2)){
					   $stmt->bindParam(":name", $userName, PDO::PARAM_STR);
					   $stmt->bindParam(":email", $theEmail, PDO::PARAM_STR);
					   $stmt->bindParam(':pass', $password, PDO::PARAM_STR);
					   $stmt->execute();
					   $stmt->closeCursor();
					   $userName = htmlentities($_POST['username'], ENT_QUOTES);
					   $_SESSION['Username'] = $userName;
					   $_SESSION['LoggedIn'] = 1;
					   $_SESSION['Edit'] = 0;
					   
					   $log = $_SERVER['DOCUMENT_ROOT'] . "/admin/inc/loggedUsers.txt";
					
						$theEntry = date("Y-m-d H:i:s") . " - " . htmlentities($userName, ENT_QUOTES) . " (Logged In Facebook Create)\n";
						
						$handle = fopen($log, "a+") or die("can't open file");
						fwrite($handle, $theEntry);
						fclose($handle);
					   return TRUE;
				   }else{
					   return FALSE;
				   }
			   }
			   
			}catch(PDOException $e){
				return FALSE;
			}
		}
		
		/**
		* Checks credentials and logs in the user
		*
		* @return boolean    TRUE on success and FALSE on failure
		*/
		public function getUsers(){
			$userSQL = "SELECT UserID, user_email, Username, user_edit FROM users ORDER BY Username";
			if($userStmt = $this->_db->prepare($userSQL)){
				$userStmt->execute();
				$users = $userStmt->fetchAll(PDO::FETCH_ASSOC);
				$userStmt->closeCursor();
				return $users;
			}
		}
		
		/**
		* Give / take away a user administrative priveliges
		*
		* @return boolean    TRUE on success and FALSE on failure
		*/
		public function changeEdit($userID, $value){
			if($_SESSION['Edit'] === 1){
				$editSQL = "UPDATE users SET user_edit = :val WHERE UserID = :id";
				if($editStmt = $this->_db->prepare($editSQL)){
					$editStmt->bindParam(":val", $value, PDO::PARAM_INT);
					$editStmt->bindParam(":id", $userID, PDO::PARAM_INT);
					$editStmt->execute();
					$editStmt->closeCursor();
					return true;
				}else{
					return false;
				}
			}
		}
		
		/**
		* Deletes user from database
		*
		* @return boolean    TRUE on success and FALSE on failure
		*/
		public function deleteUser($userID){
			if($_SESSION['Edit'] === 1){
				$deleteSQL = "DELETE FROM users WHERE UserID = :ID";
				if($deleteStmt = $this->_db->prepare($deleteSQL)){
					$deleteStmt->bindParam(":ID", $userID, PDO::PARAM_INT);
					$deleteStmt->execute();
					$deleteStmt->closeCursor();
					return true;
				}else{
					return false;
				}
			}
		}
		
		/**
		* Get user information by user id
		*
		* @return mixed    array on success and FALSE on failure
		*/
		public function getUserInfo($userID){
			$sql = "SELECT * FROM users WHERE UserID = :uID LIMIT 1";
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":uID", $userID, PDO::PARAM_INT);
				$stmt->execute();
				$theUser = $stmt->fetch(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				return $theUser;
			}else{
				return false;
			}
		}
		
		/**
		* Get user information by user email address
		*
		* @return mixed    array on success and FALSE on failure
		*/
		public function getUserInfoByEmail($userEmail){
			$sql = "SELECT * FROM users WHERE user_email = :email LIMIT 1";
			if($stmt = $this->_db->prepare($sql)){
				$stmt->bindParam(":email", $userEmail, PDO::PARAM_INT);
				$stmt->execute();
				$theUser = $stmt->fetch(PDO::FETCH_ASSOC);
				$stmt->closeCursor();
				return $theUser;
			}else{
				return false;
			}
		}
		
		/**
		* Get shopping lists by user
		*
		* @return mixed    array on success and FALSE on failure
		*/
		public function getLists($user){
			 $sql = "SELECT ListID, ListName, ListURL, created FROM lists LEFT JOIN users ON lists.UserID = users.UserID WHERE users.Username = :user";
			 
			 try{
				$stmt = $this->_db->prepare($sql);
				$stmt->bindParam(':user', $user, PDO::PARAM_STR);
				$stmt->execute(); 
				if($stmt->rowCount() > 0){
					$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
					//print_r($rows);
					return $rows;
				} else{
					return FALSE;
				}
				
			 }catch(PDOException $e){
				 return FALSE;
			 }
			 
		}
		 
		/**
		* Get a single shopping list based on the action (URL or ID)
		*
		* @return array
		*/
		public function showOneList($action, $theValue){
			if($action == "view"){
			   $sql = "SELECT ListID, ListName, created FROM lists WHERE ListURL = :listValue";
			}else if($action == "list"){
			   $sql = "SELECT ListID, ListName, created FROM lists WHERE ListID = :listValue";
			}
			
			$results = array();
			if($stmt = $this->_db->prepare($sql)){
			   $stmt->bindParam(':listValue', $theValue, PDO::PARAM_STR);
			   $stmt->execute(); 
			   
			   if($stmt->rowCount() == 1){
				   $results = $stmt->fetch(PDO::FETCH_ASSOC);
				   //$results['ListName'] = $row['ListName'];
			   } else{
				   $results['Error'] = "The list you are trying to access does not exist";
			   }
			   
			}else{
				$results['Error'] = "Could not get the list from the database";
				$results['items']['ListItemID'] = 0;
			}
			
			
			$sql2 = "SELECT i.item_name, i.item_id, li.ListItemQty FROM items i LEFT JOIN list_items li ON i.item_id = li.ListItemID WHERE li.ListID = :listID";
			//$sql2 = "SELECT ListItemID from list_items WHERE ListID = :list";
			try{
			   $stmt = $this->_db->prepare($sql2);
			   $stmt->bindParam(':listID', $results['ListID'], PDO::PARAM_INT);
			   $stmt->execute(); 
			   if($stmt->rowCount() > 0){
				   $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
				   $results['items'] = $rows;
			   } else{
				   $results['Error'] = "The list you are trying to access does not have any items";
				   $results['items'] = array();
			   }
			   
			}catch(PDOException $e){
				$results['Error'] = "Could not get the list items from the database";
				$results['items'] = array();
			}
			return $results;
		}
		
		/**
		* Get a single shopping list by list id
		* 
		* @param string $theList
		* @param int $listID
		* 
		* @return boolean
		*/
		public function saveList($theList, $listID){
			$deleteQuery = "DELETE FROM list_items WHERE ListID = :lID";
			if($deleteStmt = $this->_db->prepare($deleteQuery)){
				$deleteStmt->bindParam(":lID", $listID, PDO::PARAM_INT);
				$deleteStmt->execute();
				$deleteStmt->closeCursor();
			}
			
			$itemQuery = "INSERT INTO list_items(ListItemID, ListID) VALUES (:anItem, :lID)";
			if($addStmt = $this->_db->prepare($itemQuery)){
				foreach($theList as $anItem){
					$addStmt->bindParam(":anItem", $anItem, PDO::PARAM_INT);
					$addStmt->bindParam(":lID", $listID, PDO::PARAM_INT);
					$addStmt->execute();
				}
				
				$addStmt->closeCursor();
				return true;
			}else{
				return false;
			}
		}
		 
		/**
		* Gets the user's preferred store location
		*
		* @param string $user    -the user's user name (their email address)
		* @return array    -sends array with either storeName or Error set
		*/
		public function getStoreLocation($user){
			$userLocationQuery = "SELECT pref_store FROM users WHERE Username = :user";
			try{
			   $stmt = $this->_db->prepare($userLocationQuery);
			   $stmt->bindParam(':user', $user, PDO::PARAM_STR);
			   $stmt->execute(); 
			   if($stmt->rowCount() == 1){
				   $rows = $stmt->fetch(PDO::FETCH_ASSOC);
				   $storeID = $rows['pref_store'];
				   $results['storeID'] = $storeID;
			   } else{
				   $results['Error'] = "The user does not have a preferred store assigned.";
				   return;
			   }
			   
			}catch(PDOException $e){
				$results['Error'] = "Could not get the preferred store from the database";
				return;
			}
			
			$thisLocationQuery = "SELECT store_name FROM stores WHERE store_id = :storeID";
			try{
			   $stmt = $this->_db->prepare($thisLocationQuery);
			   $stmt->bindParam(':storeID', $storeID, PDO::PARAM_INT);
			   $stmt->execute(); 
			   if($stmt->rowCount() == 1){
				   $rows = $stmt->fetch(PDO::FETCH_ASSOC);
				   $results['storeName'] = $rows['store_name'];
			   } else{
				   $results['Error'] = "The store ID does not have a name assigned.";
			   }
			   
			}catch(PDOException $e){
				$results['Error'] = "Could not get the store name from the database";
			}
			return $results;
		}
		 
		/**
		* Changes the user's preferred location
		*
		* @param int $newLocation
		* @param int $userID
		* @return boolean
		*/
		public function changeLocation($newLocation, $userID){
			$locQuery = "UPDATE users SET pref_store = :newLoc WHERE UserID = :user";
			
			if($stmt = $this->_db->prepare($locQuery)){
				$stmt->bindParam(":newLoc", $newLocation, PDO::PARAM_INT);
				$stmt->bindParam(":user", $userID, PDO::PARAM_INT);
				$stmt->execute();
				$stmt->closeCursor();
				return true;
			}else{
				return false;
			}
		}
		 
		 
		/**
		* Gets all of the locations of a specific store
		*
		* @param string $store    -the name of the store (i.e. Macey's, Fresh Market, Dan's)
		* @return array    -all locations from the specified store
		*/
		public function getAllStoreLocations(){
			//$storeSearch = $store . "%";
			$storeQuery = "SELECT store_id, store_name, store_id_share FROM stores ORDER BY store_name ASC";
			try{
			   $stmt = $this->_db->prepare($storeQuery);
			   //$stmt->bindParam(':storeName', $storeSearch, PDO::PARAM_STR);
			   $stmt->execute(); 
			   if($stmt->rowCount() > 0){
				   $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
			   } else{
				   $rows['Error'] = "There are no stores that match the search criteria.";
				   return $rows;
			   }
			   
			}catch(PDOException $e){
				$rows['Error'] = "Error connecting to the database.";
				return $rows;
			}
			
			return $rows;
		}
		 
		 
		/**
		* Sends an email of a specific list
		*
		* @param string $email    -the user's email address
		* @param string $toEmail    -the user's email address
		* @param string $userMsg	-the user's message
		* @param string $listURL   -URL for the list
		* @return boolean    -TRUE sent email or FALSE did not send email
		*/
		public function shareList($email, $toEmail, $userMsg, $listURL){
		   $email = trim($email);
		   $to = trim($toEmail);
		   $root = DOC_ROOT . "shoppingList/view/" . $listURL;

		   $subject = "A shopping list has been shared with you";

		   $headers = <<<MESSAGE
From: $email

MESSAGE;
			$msg = <<<EMAIL
$email has shared a shopping list with you!

They said: $userMsg

 
To view this list, follow the link below.
 
Your list: $root
 
--
Thanks!

EMAIL;
 
				return mail($to, $subject, $msg, $headers);
		}
		 
		
		/**
		* Gets a user's username from the userID
		*
		* @param int $userID
		* @return array    -sends array with either storeName or Error set
		*/
		public function userNameFromID($userID){
			$sql = "SELECT Username FROM users WHERE UserID = :userID";
			try{
				$stmt = $this->_db->prepare($sql);
				$stmt->bindParam(':userID', $userID, PDO::PARAM_INT);
				$stmt->execute(); 
				if($stmt->rowCount() == 1){
					$row = $stmt->fetch(PDO::FETCH_ASSOC);
				} else{
					$row['Error'] = "There is no matching username.";
					return $row;
				}
				
			 }catch(PDOException $e){
				 $row['Error'] = "Error connecting to the database.";
				 return $row;
			 } 
			 
			 return $row;
		}
		
		/**
		* Creates a new list
		*
		* @param int $userID 
		* @return boolean
		*/
		public function newList($userID){
			$listURL = strip_tags($userID . "_" . strtotime("now"));
			$listName = date("F j, Y G:i:s");
			$created = date("Y-m-d H:i:s");
			$newListQuery = "INSERT INTO lists(UserID, ListURL, ListName, created) VALUES (:userID, :listURL, :listName, :created)";
			if($theStmt = $this->_db->prepare($newListQuery)){
				$theStmt->bindParam(":userID", $userID, PDO::PARAM_INT);
				$theStmt->bindParam(":listURL", $listURL, PDO::PARAM_STR);
				$theStmt->bindParam(":listName", $listName, PDO::PARAM_STR);
				$theStmt->bindParam(":created", $created, PDO::PARAM_STR);
				
				$theStmt->execute();
				$theStmt->closeCursor();
				
				return true;
			}else{
				return false;
			}
		}
		
		/**
		* Change the list's name
		*
		* @param string $listName
		* @param string $listNum
		* @return boolean
		*/
		public function saveListName($listName, $listNum){
			$nameQuery = "UPDATE lists SET ListName = :newName WHERE listID = :listNumber";
			
			if($theStmt = $this->_db->prepare($nameQuery)){
				$theStmt->bindParam(":newName", stripslashes($listName), PDO::PARAM_STR);
				$theStmt->bindParam(":listNumber", $listNum, PDO::PARAM_STR);
				$theStmt->execute();
				$theStmt->closeCursor();
				return true;
			}else{
				return false;
			}
		}
		
		/**
		* Deletes shopping list
		*
		* @param string $listNum
		* @return boolean
		*/
		public function deleteList($listNum){
			$deleteQuery = "DELETE FROM lists WHERE listID = :listNumber";
			
			if($theStmt = $this->_db->prepare($deleteQuery)){
				$theStmt->bindParam(":listNumber", $listNum, PDO::PARAM_STR);
				$theStmt->execute();
				$theStmt->closeCursor();
				return true;
			}else{
				return false;
			}
		}

		public function getUserEditValue($email){
			$sql = "SELECT user_edit FROM users WHERE user_email = :userEmail";
			try{
				$stmt = $this->_db->prepare($sql);
				$stmt->bindParam(':userEmail', $email, PDO::PARAM_INT);
				$stmt->execute(); 
				if($stmt->rowCount() == 1){
					$row = $stmt->fetch(PDO::FETCH_ASSOC);
					$row['Success'] = "Can Edit";
				} else{
					$row['Error'] = "There is no matching username.";
					return $row;
				}
				
			}catch(PDOException $e){
				$row['Error'] = "Error connecting to the database.";
				return $row;
			} 
			 
			return $row;
		}
	}
?>
