<?php
  if(!isset($_SESSION)){
	session_start();
  }
  
  $httpsVersion = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http';
  
  
  include_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/sessionStartGeneral.php");
  
  require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.brdata.inc.php");
  $brdataObj = new brdata();
  $availableSubscriptions = $brdataObj->getAvailableEmailSubscriptions();
  $theError = false;
  
  if(isset($_GET['update']) && $_GET['update'] == "true"){
	if(!isset($_SESSION['LoggedIn']) || !isset($_SESSION['FS_JWT']) || !isset($_SESSION['LoggedIn'])){
	  header("Location: https://" . $_SERVER['SERVER_NAME'] . "?error=noAccess");
	}
	
	$update = true;
	$theUser = $brdataObj->getUser($_SESSION['FrequentShopperNum']);
	$stores = $brdataObj->getStores();
	
	if(isset($_POST['whichForm']) && $_POST['whichForm'] == "update"){
	  $theResult = $brdataObj->updateUser();
	  
	  if(isset($theResult['success']) && $theResult['success'] === true){
		header("Location: " . $httpsVersion . "://" . $_SERVER['SERVER_NAME'] . "/account");
	  }else{
		$theError = true;
		
		if($theResult['errorCode'] == "000000004"){
		  $errorMessage = "An unknown error occured.";
		}else if($theResult['errorCode'] == "000000003"){
		  $errorMessage = $theResult['reason'];
		}else if($theResult['errorCode'] == "13"){
		  $errorMessage = "Server Error. Please try again in a few minutes.";
		}else{
		  if(isset($theResult['reason'])){
			$errorMessage = $theResult['reason'];
		  }else{
			$errorMessage = "Unknown error occured.";
		  }
		}
	  
	  }
	}
	
  }else{
	if(!isset($_POST['whichForm']) && isset($_SESSION['LoggedIn']) && isset($_SESSION['Username']) && $_SESSION['LoggedIn'] === 1){
	  header("Location: " . $httpsVersion . "://" . $_SERVER['SERVER_NAME'] . "/account");
	  //echo "<h1>YES, YOU ARE LOGGED IN</h1>";
	  die;
	}
	$update = false;
	
	if(isset($_POST['whichForm']) && $_POST['whichForm'] == "register"){
	  if(!empty($_POST['email']) && !empty($_POST['password'])){
		$theResult = $brdataObj->registerUser();
		
		if(isset($theResult) && $theResult === true){
		  header("Location: " . $httpsVersion . "://" . $_SERVER['SERVER_NAME'] . "/account");
		  //echo "<h1>YES, YOU ARE LOGGED IN</h1>";
		  die;
		}else{
		  $theUser = [];
		  $theUser['FirstName'] = $_POST['firstname'];
		  $theUser['LastName'] = $_POST['lastname'];
		  $theUser['Address1'] = $_POST['address1'];
		  $theUser['Address2'] = $_POST['address2'];
		  $theUser['City'] = $_POST['city'];
		  $theUser['ZipCode'] = $_POST['zipcode'];
		  $theUser['Phone'] = $_POST['phone'];
		  $theUser['SecondaryPhone'] = $_POST['secondaryPhone'];
		  $theUser['Birthday'] = $_POST['birthdate'];
		  $theUser['Email'] = $_POST['email'];
		  $theUser['UserEmailSubscriptions'] = $_POST['optOutEmail'];
		  $theUser['OptOutEmail'] = $_POST['optOutEmail'];
		  
		  $securityQuestions = $brdataObj->getSecurityQuestions();
		  $stores = $brdataObj->getStores();
		  
		  $theError = true;
		  
		  if(isset($theResult['errorCode']) && isset($theResult['reason'])){
			if($theResult['errorCode'] == 14){
			  //User already created
			  
			  header("Location: " . $httpsVersion . "://" . $_SERVER['SERVER_NAME'] . "/login?user=y");
			}else{
			  $errorMessage = $theResult['reason'];
			}
		  }else{
			$errorMessage = "Unknown error occured.";
		  }
		}
	  }
	}else{
		$theError = false;
		$securityQuestions = $brdataObj->getSecurityQuestions();
		$stores = $brdataObj->getStores();
	}
  }
  
  
  
?>
<?php
  $pageTitle = "User Registration";
  $pageDescription = "Signup for our Peterson's Fresh Market's Plus";
  $pageKeywords = "About Us, Utah, Fresh Foods, Grocery Store, Supermarket, Local, Low Price, Great Service, Weekly Specials";
?>
<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/header.php"); 
?>

<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="/Kickstrap/js/jquery-ui-1.9.0.custom.min.js"></script>


<style>
	  body #contentWrapper #sf-wrapper #bodyPadding #trueContentWrapper #mainContent .span12{
			width: 95%;
	  }
	  
	  @media (max-width: 780px) {
		.datepicker.dropdown-menu {
		  right:70px !important;
		  left: auto !important;
		}
		
		.datepicker:before, .datepicker:after {
		  left: auto !important;
		  right: 6px;
		}
	  }
</style>

<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/mainNav.php'); ?>
	<div id="registrationLoadingContain" class="hideObject" style="background: rgba(0,0,0,.75);position: fixed;top:0;bottom:0;left:0;right:0;z-index:100;text-align: center;">
		<i class="fa fa-spinner fa-spin" style="font-size:70px;color:#fff;margin: 15% auto 0;display: block;"></i>
	</div>
    <section class="container">
      <div id="blankBuffer"></div>
      <section class="row" id="mainContent">
			<div class="loginBox">
				<div class="span6" style="margin:0 auto;float:none">
						<div class="alert alert-info">
						  We have made exciting changes to our website to bring you more savings! Register today to use our digital savings and Plus program.
						</div>
						<?php
						  if($theError){
						?>
							<div class="alert alert-error">
								<a class="close" data-dismiss="alert" href="#">x</a><?php echo $errorMessage; ?>
								<?php
								  if(isset($theResult['badInputs'])){
									foreach($theResult['badInputs'] as $inputName){
								?>
								  <span><?php echo $inputName; ?></span><br>
								<?php
									}
								  }
								?>
							</div>
						<?php
						  }//end if($theError)
						  
						  if($update){
						?>
						  <form method="POST" action="user-update" name="updateform" id="updateform" class="cf" accept-charset="UTF-8">
							<legend style="text-align: center;">Update User Information</legend>
							<input type="hidden" name="whichForm" id="whichForm" value="update"/>
							<input type="hidden" name="frqShopperNo" id="frqShopperNo" value="<?php echo $theUser['FrqShopperNo']; ?>" />
						<?php
						  }else{
						?>
						  <form method="POST" action="register" name="registerform" id="registerform" class="cf" accept-charset="UTF-8">
							<legend style="text-align: center;">User Registration</legend>
							<input type="hidden" name="whichForm" id="whichForm" value="register"/>
							<input type="hidden" name="acceptedTerms" id="acceptedTerms" value="false"/>
						<?php
						  }
						?>
						
							<div class="g-recaptcha"
							  data-sitekey="6LcRFl4UAAAAACF2Y1995KsAGU8HR2WAaNC7hJD1"
							  data-callback="registerRecaptcha"
							  data-size="invisible">
							</div>
							<fieldset>
							  <div class="well">
								<h3>Personal Information</h3>
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="firstname">
									First Name* <span class="hideObject text-error" id="firstnameErrorMsg"> - Provide a first name</span>
								  </label>
								  <div class="controls">
									<input id="firstname" name="firstname" type="text" placeholder="First Name" class="input-xlarge required" value="<?php echo isset($theUser['FirstName']) ? htmlspecialchars($theUser['FirstName']) : ''; ?>">
									
								  </div>
								</div>
								
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="lastname">
									Last Name* <span class="hideObject text-error" id="lastnameErrorMsg"> - Provide a last name</span>
								  </label>
								  <div class="controls">
									<input id="lastname" name="lastname" type="text" placeholder="Last Name" class="input-xlarge required" value="<?php echo isset($theUser['LastName']) ? htmlspecialchars($theUser['LastName']) : ''; ?>">
									
								  </div>
								</div>
								
								<!-- Select Basic -->
								<div class="control-group">
								  <label class="control-label" for="mystore">
									My Store <?php echo $update ? '' : '*'; ?> <span class="hideObject text-error" id="mystoreErrorMsg"> - Choose a store</span>
								  </label>
								  <div class="controls">
									<select id="mystore" name="mystore" class="input-xlarge <?php echo $update ? '' : 'required'; ?>">
									  <option value="0">Choose Your Store</option>
									  <?php
										echo $stores;
									  ?>
									</select>
								  </div>
								</div>
								
								<!-- Text input-->
								<!--<div class="control-group">
								  <label class="control-label" for="birthdate">Birth Date (mm/dd/yyyy)</label>
								  <div class="controls">
									<input id="birthdate" name="birthdate" type="date" class="input-xlarge" value="<?php echo isset($theUser['Birthday']) ? htmlspecialchars($theUser['Birthday']) : ''; ?>">
									
								  </div>
								</div>-->
								
								<div class="control-group">
								  <?php
									$useDate = date("m/d/Y");
									$setDate = false;
									if(isset($theUser['Birthday'])){
									  $useDate = $theUser['Birthday'];
									  $setDate = true;
									}
								  ?>
								  <label class="control-label" for="birthdate">Birth Date (mm/dd/yyyy)</label>
								  <div id="datepicker_birthday" class="input-append date datepicker controls" data-date-format="mm/dd/yyyy" data-date="<?php echo $useDate; ?>" data-date-viewmode="years">
									<input type="text" id="birthdate" name="birthdate" value="<?php echo $setDate === true ? $useDate : ""; ?>" readonly="readonly" required/>
									<span class="add-on" id=><i class="icon-calendar"></i></span>
								  </div>
								  <?php
									if(!$update){
								  ?>
									<div class="alert alert-info">
									  Receive a special offer during your birthday month through Plus!
									</div>
								  <?php
									}
								  ?>
								</div>
								
							  </div>
							  
							  <div class="well">
								<h3>Contact Information</h3>
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="phone">
									Phone Number* (xxx-xxx-xxxx) <span class="hideObject text-error" id="phoneErrorMsg"> - Provide a phone number</span>
								  </label>
								  <div class="controls">
									<input id="phone" name="phone" type="tel" placeholder="000-000-0000" maxlength="12" class="input-xlarge required" value="<?php echo isset($theUser['Phone']) ? htmlspecialchars($theUser['Phone']) : ''; ?>">
									
								  </div>
								</div>
								
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="secondaryPhone">
									Secondary Phone Number (xxx-xxx-xxxx) <span class="hideObject text-error" id="secondaryPhoneErrorMsg"> - Provide a phone number</span>
								  </label>
								  <div class="controls">
									<input id="secondaryPhone" name="secondaryPhone" type="tel" placeholder="000-000-0000" maxlength="12" class="input-xlarge" value="<?php echo isset($theUser['SecondaryPhone']) ? htmlspecialchars($theUser['SecondaryPhone']) : ''; ?>">
									
								  </div>
								</div>
								
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="email">
									Email Address* <span class="hideObject text-error" id="emailErrorMsg"> - Provide an email</span>
								  </label>
								  <div class="controls">
									<input id="email" name="email" type="text" placeholder="example@example.com" class="input-xlarge required" value="<?php echo isset($theUser['Email']) ? htmlspecialchars($theUser['Email']) : ''; ?>">
									
								  </div>
								</div>
								
								<?php
								  if(!$update){
								?>
								  <div class="alert alert-info">
									Your email address is your new username.
								  </div>
								<?php
								  }
								?>
								
								<?php
									if(!$update){
								?>
									<div class="control-group">
									  <p>Email Subscriptions</p>
									  <!--
									  <label class="checkbox">
										<input type="checkbox" name="optOutEmail" id="optOutEmail" value="false" <?php echo $checkedStatus; ?>> I want to receive email about members-only deals, special offers and savings events.
									  </label>
									  -->

									  <?php
										foreach($availableSubscriptions as $subscription){
											if(isset($theUser)){
												$checkedStatus = false;

												foreach($theUser['UserEmailSubscriptions'] as $userSubscription){
													if(isset($userSubscription['EmailSubscriptionID']) && $userSubscription['EmailSubscriptionID'] == $subscription['EmailSubscriptionID']){
														$checkedStatus = true;
													}
												}
											}else{
												$checkedStatus = true;
											}
									  ?>
										<label class="checkbox">
											<input type="checkbox" name="optOutEmail[]" id="optOutEmail_<?php echo $subscription['EmailSubscriptionID']; ?>" value="<?php echo $subscription['EmailSubscriptionID']; ?>" <?php echo $checkedStatus ? "checked" : "" ; ?> > <?php echo $subscription['EmailSubscriptionProgram']; ?>
										</label>
									  <?php
										}
									  ?>

									</div>
								<?php
									}
								?>
							  </div>
							  
							  <?php
								if(!$update){
							  ?>
								<div class="well">
								  <h3>Account Security</h3>
									<!-- Password input-->
									<div class="control-group">
									  <label class="control-label" for="password">
										Password* <span class="hideObject text-error" id="passwordErrorMsg"> - Provide a password</span>
									  </label>
									  <div class="controls">
										<input id="password" name="password" type="password" placeholder="" class="input-xlarge required">
										
									  </div>
									</div>

									<!-- Confirm Password input-->
									<div class="control-group">
									  <label class="control-label" for="confirmPassword">
										Confirm Password* 
									  </label>
									  <div class="controls">
										<input id="confirmPassword" name="confirmPassword" type="password" placeholder="" class="input-xlarge required">
										
									  </div>
									</div>

									<div class="alert alert-danger hideObject"  id="confirmPasswordErrorMsg"><span>The passwords do not match</span></div>
								  
									<!-- Select Basic -->
									<div class="control-group">
									  <label class="control-label" for="securityquestion">Security Question</label>
									  <div class="controls">
										<select id="securityquestion" name="securityquestion" class="input-xlarge">
										  <?php echo $securityQuestions; ?>
										</select>
									  </div>
									</div>
									
									<!-- Text input-->
									<div class="control-group">
									  <label class="control-label" for="securityanswer">
										Security Answer* <span class="hideObject text-error" id="securityanswerErrorMsg"> - Provide a security answer</span>
									  </label>
									  <div class="controls">
										<input id="securityanswer" name="securityanswer" type="text" placeholder="" class="input-xlarge required">
										
									  </div>
									</div>
								</div>
							  <?php
								}
							  ?>
							  
							  <div class="well">
								<h3>Address Information</h3>
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="address1">Street Address *  <span class="hideObject text-error" id="address1ErrorMsg"> - Provide a street address</span></label>
								  <div class="controls">
									<input id="address1" name="address1" type="text" placeholder="Address" class="input-xlarge required" value="<?php echo isset($theUser['Address1']) ? htmlspecialchars($theUser['Address1']) : ''; ?>">
									
								  </div>
								</div>
								
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="address2">Apartment / Building</label>
								  <div class="controls">
									<input id="address2" name="address2" type="text" placeholder="" class="input-xlarge" value="<?php echo isset($theUser['Address2']) ? htmlspecialchars($theUser['Address2']) : ''; ?>">
									
								  </div>
								</div>
								
								<div class="control-group">
								  <label class="control-label" for="city">City </label>
								  <div class="controls">
									<input id="city" name="city" type="text" placeholder="City" class="input-xlarge" value="<?php echo isset($theUser['City']) ? htmlspecialchars($theUser['City']) : ''; ?>">
									
								  </div>
								</div>
								
								<!-- Text input-->
								<div class="control-group">
								  <label class="control-label" for="zipcode">Zip Code*  <span class="hideObject text-error" id="zipcodeErrorMsg"> - Provide a 5 Digit Zip Code</span></label>
								  <div class="controls">
									<input id="zipcode" name="zipcode" type="text" placeholder="Zip Code" class="input-xlarge required" value="<?php echo isset($theUser['ZipCode']) ? htmlspecialchars($theUser['ZipCode']) : ''; ?>">
									
								  </div>
								</div>
							  </div>
							  
							  <?php
								if(!$update){
							  ?>
								<!-- Button -->
								<div id="termsBtnContainer" class="control-group">
								  <span class="hideObject text-error" id="termsErrorMsg">You must accept the terms to register.</span>
								  <div class="controls">
									<a href="#termsModal" id="termsBtn" name="termsBtn" class="btn btn-primary btn-block btn-large" data-toggle="modal" role="button">View Terms</a>
								  </div>
								</div>
							  <?php
								}
							  ?>
							  <div class="control-group">
								<div class="controls">
								  <button id="submitBtn" name="submitBtn" class="btn btn-default btn-block btn-large <?php $update === true ? "disabled" : "" ?>">Submit</button>
								</div>
							  </div>
							
							</fieldset>
							
						</form>
					<div id="termsModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
					  <div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
						<h3 id="myModalLabel">Terms and Conditions</h3>
					  </div>
					  <div class="modal-body">
						<?php include($_SERVER['DOCUMENT_ROOT'] . '/includes/termsConditions.php'); ?>
					  </div>
					  <div class="modal-footer">
						<!--<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>-->
					  </div>
					</div>
				</div>
				
        </section>
      
    </section>
  
  <script>
	ks.ready(function(){
	  var nowTemp = new Date();
	  var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
	  
	  var birthday = $("#datepicker_birthday").datepicker().on('changeDate', function(ev){
		
		if (ev.viewMode == "days") {
		  birthday.hide();
		}
	  }).data('datepicker');
	  
	  $("#birthdate").on("touch click", function(e){
		$("#datepicker_birthday i").click();
	  });
	});

	function validatePassword() {
	  var password1 = $("#registerform #password").val();
	  var password2 = $("#registerform #confirmPassword").val();

	    if(password1 == password2) {
			$("#registerform #confirmPasswordErrorMsg").hide(); 
			return true;       
	    }
	    else {
	        $("#registerform #confirmPasswordErrorMsg").show();  
	        return false;
	    }
	    
	}

	$(document).ready(function() {
	  $("#registerform #password, #registerform #confirmPassword").keyup(validatePassword);

	  var numLocations = $("#mystore option").length;
	  
	  if(numLocations == 2){
	  	$("#mystore option").eq(1).attr("selected", true);
	  }
	});
	
	function registerRecaptcha(token){
	  if ($("#registerform").length > 0) {
		$("#registerform").unbind("submit").submit();
	  }else{
		$("#updateform").unbind("submit").submit();
	  }
	}
	
	function validateForm($form){
	  //check if phone number or email is provided
	  var phone = $("#phone", $form).val();
	  var email = $("#email", $form).val();
	  var zipCode = $("#zipcode", $form).val();
	  var acceptedTerms = $("#registerform #acceptedTerms").val();
	  var homeStore = $("#mystore option:selected").val();
	  
	  var isUpdate = "<?php echo $update ? 'true' : 'false'; ?>";
	  
	  if(isUpdate == "false"){
	  	var passwordsMatch = validatePassword();
	  	
	  	if(passwordsMatch === false){
	  		$('html, body').animate({
				scrollTop: $("#registerform #password").offset().top - 100
			}, 1000);
			
			$("#registrationLoadingContain").addClass('hideObject');

	  		return false;
	  	}
	  }

	  if (homeStore == "0" && isUpdate == "false") {
		$("#mystoreErrorMsg").removeClass("hideObject");
		
		$('html, body').animate({
			scrollTop: $("#mystoreErrorMsg").offset().top - 100
		}, 1000);
		
		$("#registrationLoadingContain").addClass('hideObject');

		return false;
	  }
	  
	  if (acceptedTerms == "false") {
		$("#termsErrorMsg, #termsBtnContainer").removeClass("hideObject");
		$("#registrationLoadingContain").addClass('hideObject');

		return false;
	  }
	  
	  $("#termsErrorMsg, #termsBtnContainer").addClass("hideObject");
	  
	  validForm = true;
	  
	  var $requiredFields = $(".required", $form);
	  
	  $requiredFields.each(function(){
		$this = $(this);
		if (!$this.val() || $.trim($this.val()) === "") {
		  $("#" + $this.attr("id") + "ErrorMsg").removeClass("hideObject");
		  validForm = false;
		}else{
		  $("#" + $this.attr("id") + "ErrorMsg").addClass("hideObject");
	    }
	  });
	  
	  if (zipCode.length != 5){
		$("#" + $this.attr("id") + "ErrorMsg").removeClass("hideObject");
		validForm = false;
	  }
	  
	  if (validForm) {
		grecaptcha.execute();
		return true;
	  }else {
		$("#registrationLoadingContain").addClass('hideObject');
		return false;
	  }
	  
	}
	
	$(".required").on('blur', function(){
	  if ($(this).val()) {
		$("#" + $(this).attr('id') + "ErrorMsg").addClass("hideObject");
	  }
	});
	
	$("#submitBtn").on('touch click', function(e){
	  e.preventDefault();
	  $("#registrationLoadingContain").removeClass('hideObject');
	  var theForm = $(this).closest("form");
	  validateForm(theForm);
	});
	
	$("#acceptTermsBtn").on('touch click', function(e){
	  e.preventDefault();
	  $("#registerform #acceptedTerms").val("true");
	  $("#submitBtn").removeClass("disabled btn-default").addClass("btn-primary");
	  $("#termsModal").modal("hide");
	  $("#termsBtnContainer").addClass("hideObject");
	});
	
	$("#rejectTermsBtn").on('touch click', function(e){
	  e.preventDefault();
	  $("#registerform #acceptedTerms").val("false");
	  alert("You must accept the terms of conditions in order to create an account");
	  $("#termsModal").modal("hide");
	});
	
	$(document).ready(function(){
	  var selectedStore = '<?php echo isset($theUser['MyStore']['MyStoreNumber']) ? trim($theUser['MyStore']['MyStoreNumber']) : "false"; ?>';
	  
	  if (selectedStore != "false") {
		$("#mystore option[value='" + selectedStore + "']").prop('selected','selected');
	  }
	  
	  if ($("#submitBtn").hasClass("disabled")) {
		$("#termsBtnContainer").removeClass("hideObject");
	  }
	});
  </script>
    
    
    
  
<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/footer.php'); ?>
