<?php
// Include config file
require_once "config.php";
// include 'menu.php';
include 'header.php';

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

// Define variables and initialize with empty values
$username = $password = $confirm_password = $City = $State = $Email = $ZipCode ="";
$username_err = $password_err = $confirm_password_err = $Email_err = $ZipCode_err = $State_err = $City_err ="";


// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
	// echo "<pre>";	
	// print_r($_POST);
	// exit;
	// Validate Email
	if(empty(trim($_POST["Email"]))){
		$Email_err = "This field is required.";
	} else{

		if(strpos(trim($_POST["Email"]), ' ') !== false)
		{
			$Email_err = "Your Email Cannot Contain Spaces";
		}
				// Prepare a select statement
		$sql1 = "SELECT id FROM users WHERE email = ?";

		if($stmt1 = $mysqli->prepare($sql1)){
						// Bind variables to the prepared statement as parameters
			$stmt1->bind_param("s", $param_Email);

						// Set parameters
			$param_Email = trim($_POST["Email"]);
			
			// Attempt to execute the prepared statement
			if($stmt1->execute()){
								// store result
				$stmt1->store_result();

				if($stmt1->num_rows > 0){
					$Email_err = "This email is already taken.";
				} else{
					$Email = trim($_POST["Email"]);
				}
			} else{
				echo "Oops! Something went wrong. Please try again later.";
			}

			// Close statement
			$stmt1->close();
		}
	}

	// Validate username
	if(empty(trim($_POST["username"]))){
		$username_err = "This field is required.";
	} else{
		if(strpos(trim($_POST["username"]), ' ') !== false || strpos(trim($_POST["username"]), '_') !== false || strpos(trim($_POST["username"]), ':') !== false || strpos(trim($_POST["username"]), '-') !== false)
		{
			$username_err = "Your Username Cannot Contain Spaces, Underscores, Colons, Or Dashes";
		}
		if(strlen(trim($_POST["username"])) > 20){
			$username_err = "Your username cannot be greater than 20 characters.";
		}
			// Prepare a select statement
		$sql = "SELECT id FROM users WHERE username = ?";

		if($stmt = $mysqli->prepare($sql)){
					// Bind variables to the prepared statement as parameters
			$stmt->bind_param("s", $param_username);

					// Set parameters
			$param_username = trim($_POST["username"]);

					// Attempt to execute the prepared statement
			if($stmt->execute()){
							// store result
				$stmt->store_result();

				if($stmt->num_rows == 1){
					$username_err = "This username is already taken.";
				} else{
					$username = trim($_POST["username"]);
				}
			} else{
				echo "Oops! Something went wrong. Please try again later.";
			}

					// Close statement
			$stmt->close();
		}
	}


	// Validate password
	if(empty(trim($_POST["password"]))){
		$password_err = "This field is required.";
	} elseif(strlen(trim($_POST["password"])) < 6){
		$password_err = "Password must have atleast 6 characters.";
	} else{
		$password = trim($_POST["password"]);

		$City = trim($_POST["City"]);
		$State = trim($_POST["State"]);

	}

	// Validate confirm password
	if(empty(trim($_POST["confirm_password"]))){
		$confirm_password_err = "This field is required.";
	} else{
		$confirm_password = trim($_POST["confirm_password"]);
		if(empty($password_err) && ($password != $confirm_password)){
			$confirm_password_err = "Password did not match.";
		}
	}

	//country 
	if(empty(trim($_POST["country"]))){
		$Country_err = "This field is required.";
	}else{
		$Country = trim($_POST["country"]);
	}
	
	//State 
	if(empty(trim($_POST["State"]))){
		$State_err = "This field is required.";
	}else{
		$State = trim($_POST["State"]);
	}

	//City Code
	if(empty(trim($_POST["City"]))){
		$City_err = "This field is required.";
	}else{
		$City = trim($_POST["City"]);
	}

	//Zip Code
	if(empty(trim($_POST["ZipCode"]))){
		$ZipCode_err = "Please enter a Zip Code.";
	}else{
		$ZipCode = trim($_POST["ZipCode"]);
	}

	// Check input errors before inserting in database
	if(empty($username_err) && empty($Country_err) && empty($password_err) && empty($confirm_password_err) && empty($Email_err) && empty($ZipCode_err) && empty($State_err) && empty($City_err) ){

			// Prepare an insert statement
		$sql = "INSERT INTO users (username, password, zip_code, country, city, state, email, verification_code) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)";

		if($stmt = $mysqli->prepare($sql)){
					// Bind variables to the prepared statement as parameters
			$stmt->bind_param("ssssssss", $param_username, $param_password, $param_ZipCode, $param_Country, $param_City, $param_State, $param_Email, $param_VerificationCode);

					// Set parameters
			$param_ZipCode = $ZipCode;
			$param_username = $username;


			$param_Country = $Country;
			$param_State = $State;
			$param_City = $City;
			$param_Email = $Email;
			$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
			$param_VerificationCode = md5(rand());
			// Attempt to execute the prepared statement
			if($stmt->execute()){
			// 	$sqladduseroldscores = "INSERT INTO oldscores(username) VALUES ('$username')";
			// 	$stmt2 = $mysqli->prepare($sqladduseroldscores);
			// 	$stmt2->execute();
			// 		// Redirect to login page
				echo "<script type='text/javascript'> document.location = 'EmailVerification.php?usernamecurrent=$username'; </script>"; 
			} else{
				echo "Something went wrong. Please try again later.";
			}

				// Close statement
			$stmt->close();
			$mysqli->close();
		}
	}
	// Close connection
	
}
?>
<div class="container">
	<div class="row">
		<div class="col-md-12">
			<div class="st-register-title text-center">
				<h2>JOIN THE RESILIENCE REVOLUTION</h2>
			</div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-4">
			<div class="st-register-boxs text-center">
				<img src="./public/images/Picture11.png" alt="Picture11">
				<h3>TRACK</h3>
				<p>Assess your stress</p>
			</div>
		</div>
		<div class="col-md-4">
			<div class="st-register-boxs text-center">
				<img src="./public/images/Picture12.png" alt="Picture11">
				<h3>UNDERSTAND</h3>
				<p>Gain insight</p>
			</div>
		</div>
		<div class="col-md-4">
			<div class="st-register-boxs text-center">
				<img src="./public/images/Picture13.png" alt="Picture11">
				<h3>ADDRESS</h3>
				<p>Improve your health</p>
			</div>
		</div>
	</div>
	<div class="row justify-content-center">
		<div class="col-md-6">
			<div class="inner-con"> 
				<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="register-form" method="post">
					<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">

						<input type="text" name="username" id="username" class="form-control" placeholder="USERNAME (something your friends will know)"  value="<?php echo $username; ?>">

						<span class="help-block" id="err_username"></span>
					</div>


					<div class="form-group">

						<input type="text" name="Email" id="email" class="form-control" placeholder="EMAIL" value="<?php echo $Email; ?>">
					</div>
					<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">

						<input type="password" name="password" id="password" placeholder="PASSWORD" class="form-control" value="<?php echo $password; ?>">
					</div>

					<div class="form-group ">
						<input type="password" name="confirm_password" id="cpassword" class="form-control" placeholder="CONFIRM PASSWORD" value="<?php echo $confirm_password; ?>">
					</div>

					<div class="form-group">
						<div class="st-rg-sub-title text-center">
							<h3>TO PUT YOU ON THE MAP…</h3>
						</div>
					</div>
					<?php
					$sqlcountries= "SELECT * FROM countries";
					$countries = mysqli_query($mysqli,$sqlcountries);
					?>
					<div class="form-group <?php echo (!empty($State_err)) ? 'has-error' : ''; ?>">
						<select id="selectcountry" name="country" class="form-control get-states"  value="">
							<option value="">COUNTRY</option>
							<?php  
							while ($c = mysqli_fetch_assoc($countries)) {
								echo "<option value=".$c['id'].">".$c['name']."</option>";
							}

							?>
						</select>
					</div>

					<div class="form-group ">
						<select id="selectStates" name="State" class="form-control get-cities"  value="<?php echo $State; ?>">
							<option value="">STATE</option>
						</select>
					</div>

					<div class="form-group ">
						<select id="selectCities" name="City" class="form-control"  value="<?php echo $City; ?>">
							<option value="">CITY</option>
						</select>
					</div>
					<div class="form-group <?php echo (!empty($ZipCode_err)) ? 'has-error' : ''; ?>">
						<input type="text" name="ZipCode" id="zip_code" class="form-control" placeholder="ZIP" value="<?php echo $ZipCode; ?>">
					</div>
					<div class="form-group text-center 456">
						<input type="submit" class="btn btn-primary" value="SUBMIT" id="submit">
					</div>
					<div class="form-group text-center">
						<p>ALREADY HAVE AN ACCOUNT? <a href="<?php echo $baseurl; ?>">LOGIN</a></p>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>
</div>
<?php
include 'footer.php';
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js" ></script>
<script>
	function isEmail(email) {
	  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	  return regex.test(email);
	}

	$.validator.addMethod("uniqueUsername", function (value, element) {
	    let result = false;
	    $.ajax({
	        type: "POST",
	        url:"ajaxQry.php",
	        dataType: "JSON",
	        data: {action: "check_user_name", username:value },
	        success: function (data) {

	            if (data === 1) {
	                result = false;
	            } else {
	                result = true;
	            }
	        },
	        async: false
	    });
	    return result;
	});
	$.validator.addMethod("customemail", 
	    function(value, element) {
	        return  /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i.test(value);
	    }, 
	    "Please enter a valid email address."
	);
	$.validator.addMethod("uniqueEmail", function (value, element) {
	    let result = false;
	    $.ajax({
	        type: "POST",
	        url:"ajaxQry.php",
	        dataType: "JSON",
	        data: {action: "check_user_email", email:value },
	        success: function (data) {

	            if (data === 1) {
	                result = false;
	            } else {
	                result = true;
	            }
	        },
	        async: false
	    });
	    return result;
	});

	$(function()
	{
	    $("#register-form").validate(
	      {
	        rules: 
	        {
	          username: 
	          {
	            required: true,
	            uniqueUsername: true,
	           
	          },
	          Email: 
	          {
	            required: true,
	            email: true,
	            customemail: true,
	            uniqueEmail:true
	          },
	          password: 
	          {
	            required: true,
	            minlength: 6
	          },
	          confirm_password: 
	          {
	            required: true,
	            minlength: 6,
            	equalTo: "#password"
	          },
	          country: 
	          {
	            required: true
	          },
	          State: 
	          {
	            required: true
	          },
	          City: 
	          {
	            required: true
	          },
	          ZipCode: 
	          {
	            required: true
	          },
	        },
		      messages: {
	            username: { 
	                uniqueUsername:"This username already taken.",
	            },
	            Email: { 
	                uniqueEmail:"This email already taken.",
	            },
	            confirm_password: { 
	                equalTo:"Password and confirm password don\'t match."
	            }
		    },
	      });	
	});
	$(document).on('change','.get-states',function() {
		var country = $(this).val();
		$.ajax({
	        url:"ajaxQry.php",    //the page containing php script
	        type: "post",    //request type,
	        dataType : 'html',
	        data: {action: "getStateData", country_id:country },
	        success:function(result){
	        	var result = jQuery.parseJSON(result);
	        	$('#selectStates').html(result.html);
	        	$('#selectCities').html('<option value="">CITY</option>');
	        }
	    });

	});
	$(document).on('change','.get-cities',function() {
		var state = $(this).val();
		$.ajax({
	        url:"ajaxQry.php",    //the page containing php script
	        type: "post",    //request type,
	        dataType : 'html',
	        data: {action: "getCityData", state_id:state },
	        success:function(result){
	        	var result = jQuery.parseJSON(result);
	        	$('#selectCities').html(result.html);
	        }
	    });

	});
			// });
			
		</script>