<?php	
	include_once('constants.inc.php');
	require_once('Firebase/JWT/JWT.php');
	require_once('Firebase/JWT/BeforeValidException.php');
	require_once('Firebase/JWT/ExpiredException.php');
	require_once('Firebase/JWT/SignatureInvalidException.php');
	include_once('class.features.inc.php');
	include_once('class.users.inc.php');
	
	use \Firebase\JWT\JWT;
	/**
	 * 
	 *
	 * PHP version 5
	 */
	
	class brdata{
		
		private $url = "https://webservices.brdata.com/api/AppUsers/";
		private $token = "";
		private $key = "w6bsp9jmpt3bvDX59C7gjaZ7BfGH8aCAm3pS3W5JbWTz7muhS8EdbpqNqBAABwJH";
		public $idNumber = null;
		public $rewardAmount = null;
		public $responseCode = null;
		public $responseText = null;
		public $transactions = null;
		public $errorMsg = "None";
		
		
		public function __construct(){
			$this->token = $this->getToken();
			$this->getStores();
		}
		
		private function getToken(){
			$theFile = $this->getCachedFile("siteToken");
			
			if(!$theFile){
				$url = $this->url . "gettoken";
				
				$headers = array(
					'clientid: ' . BRDATA_USER, 
					'appid: ' . BRDATA_APPID, 
					'timestamp: ' . time(),
					'signature: ' . hash_hmac('sha256', BRDATA_USER . BRDATA_APPID . time(), BRDATA_SECRET),
					
				);
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				$result=curl_exec($ch);
				
				$information = curl_getinfo($ch);
				
				$token = json_decode($result, true);
			
				curl_close($ch);
				
				if(isset($token['AppUserToken'][0])){
					$cacheFile = $this->getFileName("siteToken");
					file_put_contents($cacheFile, $token['AppUserToken'][0]['JWTAccessToken']);
					return $token['AppUserToken'][0]['JWTAccessToken'];
				}else{
					header("Location: https://" . $_SERVER['SERVER_NAME'] . "/connection-issue");
					die;
				}
			}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];
			if($theSite == "sso" || $theSite == "new"){
				$theSite = $theSiteParts[1];
			}
			
			$baseDir = dirname(dirname($_SERVER['DOCUMENT_ROOT']));
			return $baseDir . "/brdata/" . $theSite . "-" . $file . ".php";
		}
		
		public function getSecurityQuestions(){
			$theFile = $this->getCachedFile("securityQuestions");
			
			if(!$theFile){
				$url = $this->url . "securityquestions?a=" . BRDATA_APPID;
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				$result=curl_exec($ch);
				
				$theQuestions = json_decode($result, true);
				
				curl_close($ch);
				
				$questionsHTML = '';
				
				foreach($theQuestions['AppUserQuestions']['Questions'] as $key => $oneQuestion){
					$questionsHTML .= '<option>' . $oneQuestion['Question'] . '</option>';
				}
				
				$cacheFile = $this->getFileName("securityQuestions");
				
				file_put_contents($cacheFile, $questionsHTML);
				
				return $questionsHTML;
			}else{
				return $theFile;
			}
			
		}
		
		public function getStores(){
			$theFile = $this->getCachedFile("stores");
			
			if(!$theFile){
				$url = $this->url . "getstores?a=" . BRDATA_APPID;
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				$result=curl_exec($ch);
				
				$theStores = json_decode($result, true);
				
				curl_close($ch);
				
				
				$storesHTML = '';
				
				foreach($theStores['GetAppStoreInfo'] as $key => $oneStore){
					$validLocation = true;
				
					if(defined('BRDATA_REPLACE_LOCATION')){
						if(strpos($oneStore['StoreName'], BRDATA_REPLACE_LOCATION) === false){
							$validLocation = false;
						}else{
							$oneStore['StoreName'] = str_replace(BRDATA_REPLACE_LOCATION, "", $oneStore['StoreName']);
						}
					}

					if($validLocation){
						$storesHTML .= '<option value="' . trim($oneStore['StoreNumber']) . '">' . $oneStore['StoreName'] . ' - ' . $oneStore['StoreAddress1'] . '</option>';
					}
				}
				
				$cacheFile = $this->getFileName("stores");
				
				file_put_contents($cacheFile, $storesHTML);

				$cacheFile2 = $this->getFileName("allLocations");
				
				file_put_contents($cacheFile2, json_encode($theStores['GetAppStoreInfo']));
				
				return $storesHTML;
			}else{
				return $theFile;
			}
			
		}
		
		public function registerUser(){
			$url = $this->url . "register?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			$userData = [];
			
			$invalidInputs = 0;
			
			//$_POST['email'] = "test7@test.com";
			//$_POST['phone'] = "1111111117";
			
			//New Field: emailOptIn = yes
			
			foreach($_POST as $key => $post){
				$userInfo = is_string($post) ? strip_tags($post) : $post;
				$_POST[$key] = $userInfo;
				
				switch($key){
					case "zipcode":
						$validInput = $this->validateZip($userInfo);
						$sendInput = true;
						$brdataCol = "zip";
						break;
					case "phone":
						$validInput = $this->validatePhone($userInfo);
						$sendInput = true;
						$brdataCol = "phone";
						break;
					case "secondaryPhone":
						if($userInfo !== ""){
							$validInput = $this->validatePhone($userInfo);
						}else {
							$validInput = true;
						}
						$sendInput = true;
						$brdataCol = "secondaryPhone";
						break;
					case "birthdate":
						$validInput = $this->validateBirthdate($userInfo);
						$sendInput = true;
						$brdataCol = "birthday";
						break;
					case "email":
						$validInput = $this->validateEmail($userInfo);
						$sendInput = true;
						$brdataCol = "email";
						break;
					case "firstname":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "firstName";
						break;
					case "lastname":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "lastName";
						break;
					case "securityquestion":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "securityQuestion";
						break;
					case "mystore":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "myStore";
						break;
					case "submitBtn":
					case "whichForm":
					case "g-recaptcha-response":
						$validInput = true;
						$sendInput = false;
						break;
					default:
						$validInput = true;
						$sendInput = true;
						$brdataCol = $key;
						break;
				}
				
				if(!$validInput){
					$invalidInputs++;
					$invalidInputsKey = $key;
				}else if($sendInput == true){
					$userData[$brdataCol] = $userInfo;
				}
			}
			
			if($invalidInputs === 0){
				if(!isset($userData['optOutEmail'])){
					$userData['optOutEmail'] = [];
				}

				$userSubscriptions = [];

				foreach($userData['optOutEmail'] as $subscriptionID){
					$thisSubscription = [
						'emailsubscriptionid' => $subscriptionID,
						'email' => $userData['email'], 
						'optoutemail' => 'false'
					];

					$userSubscriptions[] = $thisSubscription;
				}

				unset($userData['optOutEmail']);
				
				//Check if the user exists using main phone
				$userInfo = $this->getUser($userData['phone'], true);
				
				//If it doesn't exist, check based on secondary phone
				if(is_null($userInfo['FrequentShopperJWT']) && $userData['secondaryPhone'] !== ""){
					$userInfo = $this->getUser($userData['secondaryPhone'], true);
				}
				
				//Need to check if it is a skeleton account.
				if(is_null($userInfo['FrequentShopperJWT'])){
					$isSkeleton = false;
				}else{
					$isSkeleton = $this->isSkeletonAccount($userInfo);
				}
				
				if($isSkeleton){
					//Update the user with the supplied data
					$userData['newPW'] = $userData['password'];
					$userData['FrequentShopperJWT'] = $userInfo['FrequentShopperJWT'];
					$_POST['frqShopperNo'] = $userInfo['FrqShopperNo'];
					
					$updateSecurity = $this->updateSecurity($userInfo['FrqShopperNo'], $userData['securityQuestion'], $userData['securityanswer']);
					
					$updatedUser = $this->updateUser();
					
					
					if(isset($updatedUser['success']) && $updatedUser['success'] === true){
						//Update the password
						$updatePW = $this->updatePasswordUnauthenticated($userData);
						$optOutAllEmails = $this->updateAllEmailSubscriptions($userData['email'], true);
						$updateEmailSubscription = $this->updateEmailSubscription($userSubscriptions, $userData['email']);

						$refreshedUser = $this->getUser($userData['email'], true);

						//Login the user
						$this->loginUserSessionVars($refreshedUser, $userData['FrequentShopperJWT']);
						return true;
					}else{
						//updatedUser contains an errorCode and reason
						return $updatedUser;
					}
					
				}else{
					//Register the user
					$data_string = json_encode($userData);
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
					curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
						'Content-Type: application/json',
						'Content-Length: ' . strlen($data_string),
						$authorization
						)
					);           
					
					$result = curl_exec($ch);
					
					$userReturn = json_decode($result, true);
					$information = curl_getinfo($ch);

					curl_close($ch);
					
					
					if(isset($userReturn['AppUserRegister'])){
						if(isset($userReturn['AppUserRegister']['errorCode'])){
					// if(true){
					// 	if(false){
							//Return the error code
							return $userReturn['AppUserRegister'];
						}else{
							
							$updateEmailSubscription = $this->updateEmailSubscription($userSubscriptions, $userData['email']);

							$userReturn['AppUserRegister']['UserEmailSubscriptions'] = $updateEmailSubscription['AppUserEmailSubscriptions'];

							//No error code so login the user
							$this->loginUserSessionVars($userReturn['AppUserRegister'], $userReturn['FrequentShopperJWT']);
							return true;
						}
					}else{
						//Figure out what error codes could come back and report - $userReturn['AppUserRegister'] is not set
						$theReturn = [];
						$theReturn['errorCode'] = "000000011";
						$theReturn['reason'] = "The user was not able to be registered.";
						return $theReturn;
					}
				}
				
				
			}else{
				$theReturn = [];
				$theReturn['AppUserRegister']['errorCode'] = "000000003";
				$theReturn['AppUserRegister']['reason'] = "Invalid inputs";
				$theReturn['AppUserRegister']['badInputs'] = $invalidInputsKey;
				return $theReturn['AppUserRegister'];
			}
		}
		
		public function updateUser(){
			$url = $this->url . "update?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			$userData = [];
			
			$invalidInputs = 0;
			
			//$_POST['email'] = "test7@test.com";
			//$_POST['phone'] = "1111111117";
			
			foreach($_POST as $key => $post){
				if(!is_array($post)){
					$userInfo = strip_tags($post);
				}else{
					$userInfo = $post;
				}

				$_POST[$key] = $userInfo;
				
				switch($key){
					case "zipcode":
						$validInput = $this->validateZip($userInfo);
						$sendInput = true;
						$brdataCol = "zip";
						break;
					case "phone":
						$validInput = $this->validatePhone($userInfo);
						$sendInput = true;
						$brdataCol = "phone";
						break;
					case "secondaryPhone":
						if($userInfo !== ""){
							$validInput = $this->validatePhone($userInfo);
						}else {
							$validInput = true;
						}
						$sendInput = true;
						$brdataCol = "secondaryPhone";
						break;
					case "birthdate":
						$validInput = $this->validateBirthdate($userInfo);
						$sendInput = true;
						$brdataCol = "birthday";
						break;
					case "email":
						$validInput = $this->validateEmail($userInfo);
						$sendInput = true;
						$brdataCol = "email";
						break;
					case "firstname":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "firstName";
						break;
					case "lastname":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "lastName";
						break;
					case "securityquestion":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "securityQuestion";
						break;
					case "mystore":
						$validInput = true;
						$sendInput = $userInfo !== "0" ? true : false;
						$brdataCol = "myStore";
						break;
					case "frqShopperNo":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "frqShopperNo";
						break;
					case "submitBtn":
					case "whichForm":
					case "action":
					case "g-recaptcha-response":
						$validInput = true;
						$sendInput = false;
						break;
					default:
						$validInput = true;
						$sendInput = true;
						$brdataCol = $key;
						break;
				}
				
				if(!$validInput){
					$invalidInputs++;
				}else if($sendInput == true){
					$userData[$brdataCol] = $userInfo;
				}
			}
			
			if($invalidInputs === 0){
				// if(!isset($userData['optOutEmail'])){
				// 	$userData['optOutEmail'] = [];
				// }

				// $userSubscriptions = [];

				// foreach($userData['optOutEmail'] as $subscriptionID){
				// 	$thisSubscription = [
				// 		'emailsubscriptionid' => $subscriptionID,
				// 		'email' => $userData['email'], 
				// 		'optoutemail' => false
				// 	];

				// 	$userSubscriptions[] = $thisSubscription;
				// }
				
				unset($userData['optOutEmail']);
				
				$data_string = json_encode($userData);
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
					'Content-Type: application/json',
					'Content-Length: ' . strlen($data_string),
					$authorization
					)
				);
				
				
				$result = curl_exec($ch);
				
				$userReturn = json_decode($result, true);
				
				$information = curl_getinfo($ch);
				
				
				curl_close($ch);
			}else{
				$theReturn = [];
				$theReturn['AppUserUpdate']['errorCode'] = "000000003";
				$theReturn['AppUserUpdate']['reason'] = "There were invalid inputs. Please fill all inputs with the correct information.";
				return $theReturn['AppUserUpdate'];
			}
			
			//If user was updated send back confirmation
			if(isset($userReturn['AppUserUpdate']['FrqShopperNo'])){
				$refreshedUser = $this->getUser($userData['email'], true);

				$this->loginUserSessionVars($refreshedUser, isset($_SESSION['FS_JWT']) ? $_SESSION['FS_JWT'] : false);
				return ["success" => true, "userObj" => $refreshedUser];
			}else{
				
				if(isset($userReturn['AppUserUpdate']['errorCode'])){
					$theReturn = $userReturn;
				}else{
					$theReturn = [];
					$theReturn['AppUserUpdate']['errorCode'] = "000000004";
					$theReturn['AppUserUpdate']['reason'] = "Unknown error - 000000004";
				}
				
				return $theReturn['AppUserUpdate'];
			}
		}
		
		public function accountLogin(){
			$url = $this->url . "login?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			$userData = [];
			$userData['emailOrPhone'] = strip_tags($_POST['username']);
			$userData['password'] = strip_tags($_POST['password']);
			
			$data_string = json_encode($userData);
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string),
				$authorization
				)
			);            
			
			$result = curl_exec($ch);
			
			$userReturn = json_decode($result, true);
			//echo "<pre>";
			//var_dump($userReturn);
			//echo "</pre>";
			//
			curl_close($ch);
			
			if(isset($userReturn['AppUserLogin']) && !isset($userReturn['AppUserLogin']['errorCode'])){
				$this->loginUserSessionVars($userReturn['AppUserLogin'], $userReturn['FrequentShopperJWT']);
				return true;
			}else{
				//Figure out what error codes could come back and report
				if(isset($userReturn['AppUserLogin'])){
					return $userReturn['AppUserLogin'];
				}else {
					$theReturn = [];
					$theReturn['errorCode'] = "000000014";
					$theReturn['reason'] = "Couldn't Login.";
					return $theReturn;
				}
			}
		}
		
		public function loginUserSessionVars($userInfo, $fs_jwt){
			if(!isset($_SESSION)){
				session_start();
			}
			
			$firstName = isset($userInfo['FirstName']) ? $userInfo['FirstName'] : "User";
			$lastName = isset($userInfo['LastName']) ? $userInfo['LastName'] : " ";
			$_SESSION['Username'] = $firstName;
			$_SESSION['UserID'] = $userInfo['FrqShopperNo'];
			$_SESSION['LoggedIn'] = 1;
			$_SESSION['Edit'] = 0;
			$_SESSION['MyStore'] = isset($userInfo['MyStore']['MyStoreNumber']) ? $userInfo['MyStore']['MyStoreNumber'] : false;
			$_SESSION['MyStoreAFS'] = isset($userInfo['MyStore']['MyStoreNumber']) ? $this->mapLocationsBRtoAFS($userInfo['MyStore']['MyStoreNumber']) : false;
			$_SESSION['FS_JWT'] = $fs_jwt;
			$_SESSION['FrequentShopperNum'] = isset($userInfo['FrqShopperNo']) ? $userInfo['FrqShopperNo'] : false;
			$_SESSION['userInformation'] = $userInfo;
			$_SESSION['userRoles'] = $this->getUserRoles($userInfo['FrqShopperNo']);
			
			if(isset($userInfo['Email'])){
				//Can user edit
				$userObj = new users();
				$canEdit = $userObj->getUserEditValue($userInfo['Email']);
				
				
				$_SESSION['Edit'] = isset($canEdit['user_edit']) ? (int) $canEdit['user_edit'] : 0;
			}
		}
		
		public function getUser($userFEP, $forceLoad = false){
			if(!isset($_SESSION['userInformation']) || $forceLoad === true){
				
				$userFEP = str_replace("-","", str_replace("(","", str_replace(")","",$userFEP)));
				$url = $this->url . "getuserinfo?a=" . BRDATA_APPID . "&fep=" . $userFEP;
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				$result=curl_exec($ch);
				
				$userReturn = json_decode($result, true);
				
				curl_close($ch);
				
				
				$userReturn['GetAppUserInfo']['FrequentShopperJWT'] = isset($userReturn['FrequentShopperJWT']) ? $userReturn['FrequentShopperJWT'] : null;
				$_SESSION['userInformation'] = $userReturn['GetAppUserInfo'];
			}else{
				
			}
			
			return $_SESSION['userInformation'];
		}
		
		public function verifySecurity(){
			$url = $this->url . "verifysecurityanswer?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			$userData = [];
			
			$invalidInputs = 0;
			
			foreach($_POST as $key => $post){
				$userInfo = strip_tags($post);
				$_POST[$key] = $userInfo;
				
				switch($key){
					case "pwResetEmail":
						$validInput = $this->validateEmail($userInfo);
						$sendInput = true;
						$brdataCol = "email";
						break;
					case "pwResetSecurityquestion":
						$validInput = true;
						$sendInput = true;
						//$userInfo = urlencode($userInfo);
						$brdataCol = "securityQuestion";
						break;
					case "pwResetSecurityanswer":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "securityAnswer";
						break;
					case "newPW":
					case "submitBtn":
					case "whichForm":
					case "action":
					case "g-recaptcha-response":
						$validInput = true;
						$sendInput = false;
						break;
					default:
						$validInput = true;
						$sendInput = true;
						$brdataCol = $key;
						break;
				}
				
				if(!$validInput){
					$invalidInputs++;
				}else if($sendInput == true){
					$userData[$brdataCol] = $userInfo;
				}
			}
			
			if($invalidInputs === 0){
				$data_string = json_encode($userData);
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
					'Content-Type: application/json',
					'Content-Length: ' . strlen($data_string),
					$authorization
					)
				);
				$result=curl_exec($ch);
				
				$userReturn = json_decode($result, true);
				
				$information = curl_getinfo($ch);
				
				curl_close($ch);
				
				if(isset($userReturn['AppUserSecurity']['success']) && $userReturn['AppUserSecurity']['success'] == "true"){
					//Passed verification. Move on to resetting password
					
					//Get FrequentShopperJWT
					$userInfo = $this->getUser($userData['email']);
					
					if(isset($userInfo['FrequentShopperJWT'])){
						$userInfoReset['FrequentShopperJWT'] = $userInfo['FrequentShopperJWT'];
					}else{
						$userReturn['errorCode'] = "000000009";
						$userReturn['reason'] = "Can't find user.";
						return $userReturn;
					}
					
					$userInfoReset['phone'] = '';
					$userInfoReset['email'] = $userData['email'];
					$userInfoReset['newPW'] = $_POST['newPW'];
					$userInfoReset['oldpassword'] = '';
					
					$passwordReset = $this->updatePasswordUnauthenticated($userInfoReset);
					
					if(isset($passwordReset['success']) && $passwordReset['success'] === "true"){
						$userReturn['Success'] = "true";
					}else{
						$userReturn['errorCode'] = "000000010";
						$userReturn['reason'] = "Password could not be reset.";
					}
					
				}else{
					//Failed verification
					$userReturn['errorCode'] = "000000008";
					$userReturn['reason'] = "Your answer to the Security Question was incorrect. Please try again.";
				}
			}
			
			return $userReturn;
		}
		
		public function updateSecurity($userFEP, $securityQuestion, $securityAnswer){
			$url = $this->url . "updatesecurityanswer?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			$userData = [];
			$userData['frqShopperNo'] = $userFEP;
			$userData['securityQuestion'] = $securityQuestion;
			$userData['securityAnswer'] = $securityAnswer;
			
			$data_string = json_encode($userData);
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLINFO_HEADER_OUT, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string),
				$authorization
				)
			);
			$result=curl_exec($ch);
			
			$userReturn = json_decode($result, true);
			
			curl_close($ch);
			
			if($userReturn['AppUserSecurity']['success'] !== "true"){
				$userReturn['AppUserSecurity']['errorCode'] = "000001102";
				$userReturn['AppUserSecurity']['reason'] = "Did not update security question and answer. [" . $data_string . "][" . json_encode($_POST) . "]";
			}
			return $userReturn['AppUserSecurity'];
		}
		
		public function updatePassword($userInfo){
			if(isset($userInfo['newPW']) && trim($userInfo['newPW']) !== ""){
				$url = $this->url . "changepassword?a=" . BRDATA_APPID;
				$authorization = "Authorization: Bearer " . $this->token;
				
				$userData = [];
				$userData['email'] = $this->getUserName('email', $userInfo['phone'], $userInfo['email']);
				$userData['oldpassword'] = isset($userInfo['oldpassword']) ? $userInfo['oldpassword'] : '';
				
				$userData['newpassword'] = isset($userInfo['newPW']) ? trim($userInfo['newPW']) : '';
				$data_string = json_encode($userData);
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string), $authorization ));
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				
				$result = curl_exec($ch);
				$information = curl_getinfo($ch);
				
				$userReturn = json_decode($result, true);
				curl_close($ch);
				
				
				//$theReturn = isset($userReturn['AppUserChangePassword']['success']) ? $userReturn['AppUserChangePassword']['success'] === "true" ? true : false : false;
				
				if($userReturn['AppUserChangePassword']['success'] === "false"){
					$userReturn['AppUserChangePassword']['errorCode'] = "000000002";
					$userReturn['AppUserChangePassword']['reason'] = "Old password does not match";
				}
				return $userReturn['AppUserChangePassword'];
			}else{
				$theReturn = [];
				$theReturn['AppUserChangePassword']['errorCode'] = "000000001";
				$theReturn['AppUserChangePassword']['reason'] = "New Password was empty";
				return $theReturn['AppUserChangePassword'];
			}
			
		}
		
		public function updatePasswordUnauthenticated($userArray){
			if(isset($userArray['newPW']) && trim($userArray['newPW']) !== ""){
				$userData = [];
				$invalidInputs = 0;
				
				foreach($userArray as $key => $post){
					$userInfo = strip_tags($post);
					$userArray[$key] = $userInfo;
					
					switch($key){
						case "email":
							$validInput = $this->validateEmail($userInfo);
							$sendInput = true;
							$brdataCol = "email";
							break;
						case "newPW":
							$validInput = true;
							$sendInput = true;
							$brdataCol = "newpassword";
							break;
						case "pwResetSecurityquestion":
						case "pwResetSecurityanswer":
						case "submitBtn":
						case "whichForm":
						case "action":
						case "FrequentShopperJWT":
						case "g-recaptcha-response":
							$validInput = true;
							$sendInput = false;
							break;
						default:
							$validInput = true;
							$sendInput = false;
							$brdataCol = $key;
							break;
					}
					
					if(!$validInput){
						$invalidInputs++;
					}else if($sendInput == true){
						$userData[$brdataCol] = $userInfo;
					}
				}
				
				if($invalidInputs === 0){
					$url = $this->url . "passwordreset?a=" . BRDATA_APPID;
					$authorization = "Authorization: Bearer " . $this->token;
					$userJWT = "FrequentShopperJWT: " . $userArray['FrequentShopperJWT'];
					
					//$userData['oldpassword'] = '';
					
					$data_string = json_encode($userData);
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($data_string), $authorization, $userJWT ]);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
					curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					
					$result = curl_exec($ch);
					
					$information = curl_getinfo($ch);
					
					$userReturn = json_decode($result, true);
					curl_close($ch);
					
					if(isset($userReturn['AppUserPasswordReset']['success']) && $userReturn['AppUserPasswordReset']['success'] === "true"){
						//Do nothing on purpose
					}else{
						$userReturn['AppUserPasswordReset']['errorCode'] = "000000005";
						$userReturn['AppUserPasswordReset']['reason'] = "Required parameters missing or empty";
					}
					return $userReturn['AppUserPasswordReset'];
				}
			}else{
				$theReturn = [];
				$theReturn['AppUserPasswordReset']['errorCode'] = "000000001";
				$theReturn['AppUserPasswordReset']['reason'] = "New Password was empty";
				return $theReturn['AppUserPasswordReset'];
			}
		}
		
		public function getAvailableEmailSubscriptions(){
			$theFile = $this->getCachedFile("emailSubscriptions");
			$theFile = false;

			if(!$theFile){

				$url = $this->url . "/emailsubscriptions?a=" . BRDATA_APPID;
				$authorization = "Authorization: Bearer " . $this->token;

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				$result=curl_exec($ch);
				
				$availableSubscriptions = json_decode($result, true);

				curl_close($ch);

				if(count($availableSubscriptions['AppUserEmailSubscriptions']) > 0){
					$sortedSubscriptions = $availableSubscriptions['AppUserEmailSubscriptions'];

					$weeklyAdSubscription = array_shift($sortedSubscriptions);
					
					usort($sortedSubscriptions, function($a, $b){
						return strcasecmp($a['EmailSubscriptionProgram'], $b['EmailSubscriptionProgram']);
					});
					
					array_unshift($sortedSubscriptions, $weeklyAdSubscription);
					$cacheFile = $this->getFileName("emailSubscriptions");
				
					file_put_contents($cacheFile, json_encode($sortedSubscriptions));

					return $sortedSubscriptions;
				}else{
					return false;
				}
			}else{
				return json_decode($theFile);
			}
		}

		public function updateAllEmailSubscriptions($email, $optOutValue){
			// NOTE: sending true will opt them out of all email subscriptions. Sending false will add them to all of the email subscriptions
			 
			
			$url = $this->url . "updateallemailsubscriptions?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			$userData = [];
			//$userData['FrqShopperNo'] = $frequentShopper;
			$userData['Email'] = $email;
			$userData['optoutemail'] = $optOutValue === true ? "true" : "false";
			
			$data_string = json_encode($userData);
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLINFO_HEADER_OUT, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string), $authorization ));
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			
			$result = curl_exec($ch);
			
			$userReturn = json_decode($result, true);
			$information = curl_getinfo($ch);
			curl_close($ch);

			if(isset($userReturn["AppUserEmailSubscriptions"]['errorCode'])){
				$userReturn['success'] = false;
			}else{
				$userReturn['success'] = true;
			}

			return $userReturn;
			
		}

		public function updateEmailSubscription($subscription, $email){
			$url = $this->url . "updateemailsubscription?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			// $userData = [];
			// $userData['emailsubscriptionid'] = $emailSubscriptionID;
			// $userData['optoutemail'] = $optOutValue;
			// $userData['email'] = $userEmail;
			
			$data_string = json_encode($subscription);
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLINFO_HEADER_OUT, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string), $authorization ));
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			
			$result = curl_exec($ch);
			
			$userReturn = json_decode($result, true);
			$information = curl_getinfo($ch);
			curl_close($ch);

			if(isset($userReturn["AppUserEmailSubscriptions"]['errorCode'])){
				$userReturn['success'] = false;
			}else{
				$userReturn['success'] = true;
				
				if(!isset($_SESSION)){
					session_start();
				}

				$userReturn['sessionUser'] = $_SESSION['userInformation'];

				$refreshedUser = $this->getUser($email, true);

				$_SESSION['userInformation'] = $userReturn['refreshedUser'] = $refreshedUser;
			}

			return $userReturn;
		}
		
		public function isSkeletonAccount($theUser){
			//$columns = ["Birthday", "LastName", "MiddleInitial", "FirstName", "Phone", "ZipCode", "State", "City", "Address2", "Address1", "Email"];
			//$filledColumns = [];
			//$isSkeleton = false;
			//
			//foreach($columns as $column){
			//	$checkValue = trim($theUser[$column]);
			//	if(!empty($checkValue)){
			//		$filledColumns[] = $column;
			//	}
			//}
			//
			//if(count($filledColumns) === 1 && in_array("Phone", $filledColumns)){
			//	$isSkeleton = true;
			//}
			
			$isSkeleton = false;
			
			if($theUser['Email'] == ""){
				$isSkeleton = true;
			}
			
			return $isSkeleton;
		}

		public function getCharities($userFEP){
			$theFile = $this->getCachedFile("charities");
			
			if(!$theFile){

				$userFEP = str_replace("-","", str_replace("(","", str_replace(")","",$userFEP)));

				$url = $this->url . $userFEP . "/charities/available?a=" . BRDATA_APPID;
				$authorization = "Authorization: Bearer " . $this->token;

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				$result=curl_exec($ch);
				
				$availableCharities = json_decode($result, true);

				curl_close($ch);

				if(count($availableCharities['AppUserCharities']) > 0 && !isset($availableCharities['AppUserCharities']['errorCode'])){
					$sortedCharities = [];
					
					foreach ($availableCharities['AppUserCharities'] as $charity) {
						$charityComponents = explode('_', $charity['Description']);
						
						$city = isset($charityComponents[1]) ? trim($charityComponents[1]) : "None";
						$name = trim($charityComponents[0]);
						$zip = isset($charityComponents[2]) ? $charityComponents[2] : "None";

						$sortedCharities[$city][] = [
							'name' => $name, 
							'id' => $charity['CharityID'],
							'zip' => $zip
						];
					}
					
					ksort($sortedCharities);

					$cacheFile = $this->getFileName("charities");
				
					file_put_contents($cacheFile, json_encode($sortedCharities));

					return $sortedCharities;
				}else{
					return false;
				}
			}else{
				return json_decode($theFile);
			}
		}

		public function getUserCharities($userFEP){
			if(!isset($_SESSION['userInformation']['UserCharity'])){
				$userFEP = str_replace("-","", str_replace("(","", str_replace(")","",$userFEP)));

				$url = $this->url . $userFEP . "/charities?a=" . BRDATA_APPID;
				$authorization = "Authorization: Bearer " . $this->token;

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				$result=curl_exec($ch);
				
				$userCharities = json_decode($result, true);
				
				curl_close($ch);


				if(count($userCharities['AppUserCharities']) > 0 && !isset($userCharities['AppUserCharities']['errorCode'])){
					$_SESSION['userInformation']['UserCharity'] = (array) $userCharities['AppUserCharities'][0];
					return $userCharities['AppUserCharities'][0];
				}else{
					return false;
				}
			}else{
				return $_SESSION['userInformation']['UserCharity'];
			}
		}

		public function updateUserCharity($charityID) {
			if(!isset($_SESSION)){
				session_start();
			}

			$userFEP = str_replace("-","", str_replace("(","", str_replace(")","",$_SESSION['FrequentShopperNum'])));

			$url = $this->url . $userFEP . "/charities/" . $charityID . "?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			$JWT = $_SESSION['FS_JWT'];
			
					
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLINFO_HEADER_OUT, true);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
				'Content-Type: application/json',
				'Content-Length: 0',
				$authorization,
				"FrequentShopperJWT: " . $JWT)
			);
			
			$result=curl_exec($ch);
			$information = curl_getinfo($ch);
			
			curl_close($ch);

			$charityReturn = json_decode($result, true);
			
			if(isset($charityReturn['AppUserCharities'][0]['CharityID'])){
				$theReturn['success'] = true;
				$_SESSION['userInformation']['UserCharity'] = (array) $charityReturn['AppUserCharities'][0];
				//$this->getUser($_SESSION['userInformation']['Email'], true);
				$theReturn['charity'] = $charityReturn['AppUserCharities'][0];
			}else{
				//Failed verification
				$theReturn['success'] = false;
				$theReturn['errorCode'] = "000000400";
				$theReturn['reason'] = "Charity was not updated.";
			}
			
			return $theReturn;
		}

		public function getUserRoles($userFEP){
			$userFEP = str_replace("-","", str_replace("(","", str_replace(")","",$userFEP)));

			$url = $this->url . $userFEP . "/roles?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_POST, 0);
			$result=curl_exec($ch);
			
			$userRoles = json_decode($result, true);
			
			curl_close($ch);
			
			$theRoles = '';

			if(count($userRoles['AppUserRoles']) > 0){
				foreach($userRoles['AppUserRoles'] as $role){
					if(isset($role['Name'])){
						$theRoles .= $role['Name'] . ', ';
					}
				}
			}
			
			return rtrim($theRoles, ', ');
		}
		
		public function addSecondaryUser() {
			$url = $this->url . "registersecondaryuser?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			if(!isset($_SESSION)){
				session_start();
			}
			
			$JWT = $_SESSION['FS_JWT'];
			
			$userData = [];
			
			$invalidInputs = 0;
			$requiredFields = ['phone', 'email', 'firstName', 'lastName', 'password'];
			foreach($_POST as $key => $post){
				$userInfo = strip_tags($post);
				$_POST[$key] = $userInfo;
				
				switch($key){
					case "secondaryPhone":
						$validInput = $this->validatePhone($userInfo);
						$sendInput = true;
						$brdataCol = "phone";
						if($validInput === true){unset($requiredFields[0]);}
						break;
					case "secondaryEmail":
						$validInput = $this->validateEmail($userInfo);
						$sendInput = true;
						$brdataCol = "email";
						if($validInput === true){unset($requiredFields[1]);}
						break;
					case "firstname":
						$validInput = !empty(trim($userInfo));
						$sendInput = true;
						$brdataCol = "firstName";
						if($validInput === true){unset($requiredFields[2]);}
						break;
					case "lastname":
						$validInput = !empty(trim($userInfo));
						$sendInput = true;
						$brdataCol = "lastName";
						if($validInput === true){unset($requiredFields[3]);}
						break;
					case "password":
						$validInput = !empty(trim($userInfo));
						$sendInput = true;
						$brdataCol = "password";
						if($validInput === true){unset($requiredFields[4]);}
						break;
					case "newPW":
					case "submitBtn":
					case "whichForm":
					case "action":
					case "g-recaptcha-response":
						$validInput = true;
						$sendInput = false;
						break;
					default:
						$validInput = true;
						$sendInput = false;
						$brdataCol = $key;
						break;
				}
				
				if(!$validInput){
					$invalidInputs++;
				}else if($sendInput == true){
					$userData[$brdataCol] = $userInfo;
				}
			}
			
			if($invalidInputs === 0){
				$userData['allowSecondaryLogin'] = "false";
				
				if(count($requiredFields) === 0){
					
					$data_string = json_encode($userData);
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_POST, 1);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
						'Content-Type: application/json',
						'Content-Length: ' . strlen($data_string),
						$authorization,
						"FrequentShopperJWT: " . $JWT)
					);
					
					$result=curl_exec($ch);
					$information = curl_getinfo($ch);
					
					$userReturn = json_decode($result, true);
					
					curl_close($ch);
					
					if(isset($userReturn['AppUserRegisterSecondaryUser'][0]['SecondaryUserID'])){
						$allSecondary = array();
						foreach ($userReturn['AppUserRegisterSecondaryUser'] as $object){
							$allSecondary[] = (array) $object;
						}
						
						$_SESSION['userInformation']['SecondaryUsers'] = $allSecondary;
						
						$userReturn['success'] = true;
					}else{
						//Failed verification
						$userReturn['errorCode'] = "000000100";
						$userReturn['reason'] = "Secondary User was not created.";
					}
				}else{
					$userReturn = [];
					$userReturn['errorCode'] = "000000101";
					$userReturn['reason'] = "All fields are required. Please fill them out and resubmit the form. (" . implode(", ", $requiredFields) . ")";
				}
			}else{
				$userReturn = [];
				$userReturn['errorCode'] = "000000102";
				$userReturn['reason'] = "All fields are required. Please fill them out and resubmit the form. (" . implode(", ", $requiredFields) . ")";
			}
			
			return $userReturn;
		}
		
		public function updateSecondaryUser() {
			$url = $this->url . "updatesecondaryuser?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			if(!isset($_SESSION)){
				session_start();
			}
			
			$JWT = $_SESSION['FS_JWT'];
			
			$userData = [];
			
			$invalidInputs = 0;
			$requiredFields = ['phone', 'email', 'firstName', 'lastName', 'secondaryUserID'];
			foreach($_POST as $key => $post){
				$userInfo = strip_tags($post);
				$_POST[$key] = $userInfo;
				
				switch($key){
					case "secondaryPhone":
						$validInput = $this->validatePhone($userInfo);
						$sendInput = true;
						$brdataCol = "phone";
						if($validInput === true){unset($requiredFields[0]);}
						break;
					case "secondaryEmail":
						$validInput = $this->validateEmail($userInfo);
						$sendInput = true;
						$brdataCol = "email";
						if($validInput === true){unset($requiredFields[1]);}
						break;
					case "firstname":
						$validInput = !empty(trim($userInfo));
						$sendInput = true;
						$brdataCol = "firstName";
						if($validInput === true){unset($requiredFields[2]);}
						break;
					case "lastname":
						$validInput = !empty(trim($userInfo));
						$sendInput = true;
						$brdataCol = "lastName";
						if($validInput === true){unset($requiredFields[3]);}
						break;
					case "secondaryUserID":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "secondaryUserID";
						if($validInput === true){unset($requiredFields[4]);}
						break;
					case "password":
					case "newPW":
					case "submitBtn":
					case "whichForm":
					case "action":
					case "g-recaptcha-response":
						$validInput = true;
						$sendInput = false;
						break;
					default:
						$validInput = true;
						$sendInput = false;
						$brdataCol = $key;
						break;
				}
				
				if(!$validInput){
					$invalidInputs++;
				}else if($sendInput == true){
					$userData[$brdataCol] = $userInfo;
				}
			}
			
			if($invalidInputs === 0){
				$userData['allowSecondaryLogin'] = "false";
				
				if(count($requiredFields) === 0){
					
					$data_string = json_encode($userData);
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
					curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
						'Content-Type: application/json',
						'Content-Length: ' . strlen($data_string),
						$authorization,
						"FrequentShopperJWT: " . $JWT)
					);
					
					$result=curl_exec($ch);
					$information = curl_getinfo($ch);
					
					$userReturn = json_decode($result, true);
					
					if(isset($userReturn['AppUserUpdateSecondaryUser'][0]['SecondaryUserID'])){
						$userReturn['success'] = true;
						$_SESSION['userInformation']['SecondaryUsers'] = (array) $userReturn['AppUserUpdateSecondaryUser'];
						//$this->getUser($_SESSION['userInformation']['Email'], true);
						$userReturn['reload'] = true;
					}else{
						//Failed verification
						$userReturn['errorCode'] = "000000200";
						$userReturn['reason'] = "Secondary User was not updated.";
					}
				}else{
					$userReturn = [];
					$userReturn['errorCode'] = "000000101";
					$userReturn['reason'] = "All fields are required. Please fill them out and resubmit the form. (" . implode(", ", $requiredFields) . ")";
				}
			}else{
				$userReturn = [];
				$userReturn['errorCode'] = "000000101";
				$userReturn['reason'] = "All fields are required. Please fill them out and resubmit the form. (" . implode(", ", $requiredFields) . ")";
			}
			
			return $userReturn;
		}
		
		public function deleteSecondaryUser() {
			$url = $this->url . "updatesecondaryuser?a=" . BRDATA_APPID;
			$authorization = "Authorization: Bearer " . $this->token;
			
			if(!isset($_SESSION)){
				session_start();
			}
			
			$JWT = $_SESSION['FS_JWT'];
			
			$userData = [];
			$invalidInputs = 0;
			$requiredFields = ['secondaryUserID'];
			foreach($_POST as $key => $post){
				$userInfo = strip_tags($post);
				$_POST[$key] = $userInfo;
				
				switch($key){
					case "secondaryUserID":
						$validInput = true;
						$sendInput = true;
						$brdataCol = "secondaryUserID";
						if($validInput === true){unset($requiredFields[0]);}
						break;
					case "g-recaptcha-response":
						$validInput = true;
						$sendInput = false;
						break;
					default:
						$validInput = true;
						$sendInput = false;
						$brdataCol = $key;
						break;
				}
				
				if(!$validInput){
					$invalidInputs++;
				}else if($sendInput == true){
					$userData[$brdataCol] = $userInfo;
				}
			}
			
			if($invalidInputs === 0){
				$userData['statusCode'] = "IN";
				
				if(count($requiredFields) === 0){
					
					$data_string = json_encode($userData);
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
					curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(            
						'Content-Type: application/json',
						'Content-Length: ' . strlen($data_string),
						$authorization,
						"FrequentShopperJWT: " . $JWT)
					);
					
					$result=curl_exec($ch);
					$information = curl_getinfo($ch);
					
					$userReturn = json_decode($result, true);
					
					if(isset($userReturn['AppUserUpdateSecondaryUser'][0]['SecondaryUserID'])){
						$userReturn['success'] = true;
						$_SESSION['userInformation']['SecondaryUsers'] = (array) $userReturn['AppUserUpdateSecondaryUser'];
						//$this->getUser($_SESSION['userInformation']['Email'], true);
						//$userReturn['reload'] = true;
					}else{
						//Failed verification
						$userReturn['errorCode'] = "000000300";
						$userReturn['reason'] = "Secondary User was not deleted.";
					}
				}else{
					$userReturn = [];
					$userReturn['errorCode'] = "000000301";
					$userReturn['reason'] = "All fields are required. Please fill them out and resubmit the form. (" . implode(", ", $requiredFields) . ")";
				}
			}else{
				$userReturn = [];
				$userReturn['errorCode'] = "000000301";
				$userReturn['reason'] = "All fields are required. Please fill them out and resubmit the form. (" . implode(", ", $requiredFields) . ")";
			}
			
			return $userReturn;
		}
		
		public function tokenLogin($userToken){
			try{
				$decoded = JWT::decode($userToken, base64_decode($this->key), array('HS256'));
			} catch (Exception $e) {
				header("Location: https://" . $_SERVER['SERVER_NAME'] . "/login?td=false");
				die;
			}
			
			//print_r($decoded);
			
			$userInfo = $this->getUser($decoded->frequentShopper, true);
			
			if($userInfo['FrqShopperNo'] === $decoded->frequentShopper){
				$this->loginUserSessionVars($userInfo, $userInfo['FrequentShopperJWT']);
				return true;
			}else{
				header("Location: https://" . $_SERVER['SERVER_NAME'] . "/login?t=false");
				die;
			}
			
		}
		
		private function validateZip($zipCode){
			if (preg_match('#[0-9]{5}#', $zipCode) || empty(trim($zipCode)))
				return true;
			else
				return false;
		}
		
		private function validatePhone($phoneNum){
			$phoneNum = "(" . $phoneNum . ")";
			
			if (preg_match('/^[0-9]{10}+$/', str_replace("-","", str_replace("(","", str_replace(")","",$phoneNum))))){
				return true;
			}else{
				return false;
			}
		}
		
		private function validateBirthdate($birthDate){
			if (preg_match("/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/", $birthDate) || empty(trim($birthDate)))
				return true;
			else
				return false;
		}
		
		private function validateEmail($email){
			if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
				return true;
			}else{
				return false;
			}
		}
		
		private function getUserName($preference, $phone = "", $email = ""){
			if($phone !== "" && $preference === "phone"){
				return $phone;
			}
			
			return $email;
		}
		
		private function mapLocationsBRtoAFS($brStoreNum){
			$storeObj = new stores();
			$stores = $storeObj->getStoreLocations();
			//echo "<pre>";
			//var_dump($brStoreNum);
			//echo "</pre>";
			//echo "<pre>";
			//var_dump($stores);
			//echo "</pre>";
			
			$storeReturn = [];
			
			foreach($stores as $store){
				if(trim($brStoreNum) == $store['brdata_store_num']){
					$storeReturn['store_name'] = $store['store_name'];
					$storeReturn['store_id_share'] = $store['store_id_share'];
					break;
				}
			}

			if(empty($storeReturn)){
				$theFile = json_decode($this->getCachedFile("allLocations"));

				foreach($theFile as $store){
					if(trim($brStoreNum) == trim($store->StoreNumber)){
						$storeReturn['store_name'] = $store->StoreName;
						$storeReturn['store_id_share'] = '';
						break;
					}
				}
			}
			
			
			return $storeReturn;
		}
	}
?>
