<?php

include("config.php");
session_start();

if(isset($_SESSION["user_login"])){
		header("location: index.php");
	}

	$fullName = $_POST["fullName"];
	$username = $_POST["username"];
	$email = $_POST["email"];
	$password = $_POST["password"];
	
	//Get Referral ID if user was referred
	if(!empty($_POST["ref"])){
	$refID = "?ref=".htmlspecialchars(strip_tags($_POST["ref"]));
	}else{
		$refID = "";
	}



		function validate($str){
			return trim(htmlspecialchars(strip_tags(($str))));
		}
		

			$username = validate($_POST["username"]);
			if(!preg_match('/^[a-zA-Z0-9-_\s]+$/', $username)){
				$errorMsg[] = "Only letters with numbers, hyphen or underscore allowed";
			}else{
				$stmt = "SELECT userid FROM users WHERE username=:username";
				$stmt=$pdo->prepare($stmt);
				$stmt->bindParam(":username", $username, PDO::PARAM_STR);
				$stmt->execute();
				if($stmt->rowCount()>0){
					$errorMsg[] = "Username already taken. <br> Try: '" . $username . "20', '" . $username . "10', '" . $username . "5'";
				}
			}
		
	
			$fullName = validate($_POST["fullName"]);
            if(!preg_match('/^.+$/', $fullName)){
              $errorMsg[] = "Invalid name!";
                }
		
		
			$email = validate($_POST["email"]);
			if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
				$errorMsg[]  = "Invalid email supplied, must contain @.com";
			}else{
				$stmt=$pdo->prepare("SELECT userid FROM users WHERE email=:email");
				$con = array(":email"=>$email);
				$stmt->execute($con);
				if($stmt->rowCount() >0){
					$errorMsg[] = "A user with this email already exist";
				}
			}
		
				$password = validate($_POST["password"]);
				if(strlen($_POST["password"])<6){
					$errorMsg[] = "Password must be upto 6 characters";
				}
		
			
		if(empty($errorMsg)){
			
			try{
				$type = "user";
				
				$stmt=$pdo->prepare("INSERT INTO users (fullName, username, email, password) VALUES(:fullName, :username, :email, :password)");
				$password = password_hash($password, PASSWORD_DEFAULT);
				$stmt->bindParam(":fullName", $fullName, PDO::PARAM_STR);
				$stmt->bindParam(":username", $username, PDO::PARAM_STR);
				$stmt->bindParam(":email", $email, PDO::PARAM_STR);
				$stmt->bindParam(":password", $password, PDO::PARAM_STR);
				$stmt->execute();
				
				if($stmt){
				$success = "Registered Successfully &nbsp;&nbsp;<i class='fa fa-check-circle'></i>";
				}
				
				if(isset($success)){
					$stmt=$pdo->prepare("SELECT * FROM users WHERE username=:username OR email=:email");
					$stmt->bindParam(":username", $username, PDO::PARAM_STR);
					$stmt->bindParam(":email", $email, PDO::PARAM_STR);
					$stmt->execute();
					$row=$stmt->fetch();
					}
					
				$_SESSION["user_login"] = $row["userid"];
				$userid = intval($_SESSION["user_login"]);
				
				
				//Update user unique ref link
				
				//create a unique key for referral program for every signed up user
				$unique = "aAbBcCDdEeFf123456";
				$custom = str_shuffle($unique);
				$key = substr($custom,0,5)."_".$userid;
				
					$stmt=$pdo->prepare("UPDATE users SET invite_ref = :invite_ref WHERE userid=:userid");
					$stmt->bindParam(":invite_ref", $key, PDO::PARAM_STR);
					$stmt->bindParam(":userid", $userid, PDO::PARAM_STR);
					$stmt->execute();
				
				
				
		//Update Account Balance Table to 0!
		$balance = 0;
		$deposit = 0;
		$profits = 0;
		
		$stmt = $pdo->prepare("INSERT INTO account (balance,deposit,profits,userid) 
								VALUES (:balance,:deposit,:profits,:userid)");
		$stmt->bindParam(":balance",$balance,PDO::PARAM_STR);
		$stmt->bindParam(":deposit",$deposit,PDO::PARAM_STR);
		$stmt->bindParam(":profits",$profits,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->execute();	
				
				
			
		//Add Mailer Script to send user info to their mail
		require_once("mails/confirmReg.php");
				
				
				
				
			}catch(PDOException $e){
				echo "Error in connection " . $e->getMessage();
			}
			
			
		}
	
	
	// END REGISTER CODE
	


?>

<script>
var close = document.getElementsByClassName("closebtn");
var i;
for (i = 0; i < close.length; i++) {
  close[i].onclick = function(){
    var div = this.parentElement;
    div.style.opacity = "0";
    setTimeout(function(){ div.style.display = "none"; }, 600);
  }
}
</script>

<?php 

if(isset($success)){
	echo "<div class='alert success'><span class='closebtn'>&times;</span>  
  <strong>" . $success . "</strong></div>";
  
  echo "<center>
			<h4 class='logs' style='margin:10px;'>Preparing Your Account</h4>
		</center> 
  <div class='coversoverlay'>
	<center><img src='img/loader.gif' style='width:60px; margin-top:20%;'></center>
	</div>
  
  <script>
  
		//redirect after 3sec
		//setTimeout(function(){location.href='verify.php?mail=sent'},3000);
		
		setTimeout(function(){location.href='dashboard/account.php$refID'},3000);
  </script>
  ";
}?>



<!-- ERROR IF WRONG CREDENTIALS-->
<?php
if(isset($errorMsg)){
	foreach($errorMsg as $error){
	
	echo "<div class='error-alert errors'><span class='closebtn'>&times;</span>  
  <strong>" . $error . "</strong></div>";
  
	}
}
?>