<?php 
	require("functions/config.php");
	// CSRF Protection
	require 'functions/CSRF_Protect.php';
	$csrf = new CSRF_Protect();
	
	// Error Reporting Active
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>FLY CMS</title>
    <meta name="description" content="">
    <meta name="author" content="">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<link rel="shortcut icon" href="assets/images/favico.ico" type="image/x-icon" >
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="assets/js/sweetalert.min.js"></script> 
	<link rel="stylesheet" type="text/css" href="assets/css/sweetalert.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" media="screen">
	<link rel="stylesheet" href="assets/css/font-awesome.min.css">
	<link href="assets/css/styles.css" rel="stylesheet" media="screen">
</head>

<body id="bg">

<div class="container hero-unit form-signin">
    <p><i class="fa fa-paper-plane-o" aria-hidden="true"></i> Create your new account</p>
    <form action="register.php" method="post"> 
		<select class="form-control" name="lang">
		  <option value="en">English</option>
		  <option value="pt">Português</option>
		  <option value="fr">Français</option>
		</select>
		 <?php $csrf->echoInputField(); ?>
        <input type="text" name="username" class="form-control" placeholder="Username" required value="" /> 
        <input type="text" name="email" class="form-control" placeholder="youremail@here.com" required value="" /> 
        <input type="password" name="password" class="form-control" placeholder="Password" required value="" />
		<br/>
        <input type="submit" class="btn btn-info btn-flat" value="Register" />			
    </form>
	<span><a href="index.php">Go back to login area</a></span>
</div>
<?php 

	$username = "";

	if(isset($_POST['username'])){
		$username = $_POST['username'];
	}

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $username))
{
   echo "<script type='text/javascript'>sweetAlert('REALLY?!', 'Using special characters?!', 'error');</script>";	
			echo '<META HTTP-EQUIV=REFRESH CONTENT="100"; '.$url.'">'; 
			die; 
}
	
	function simpleRegexpValidation($email) {
		$regex = '/([a-z0-9_]+|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i';
		return preg_match($regex, $email);
	}
	
	if(!empty($_POST)){ 
		$email = $_POST['email'];
	}
	else{
		$email = "";
	}
	
	$url = $_SERVER['PHP_SELF'];
	
    if(!empty($_POST)) 
    { 
        // Ensure that the user fills out fields 
        if(empty($_POST['username'])) 
        { 
			echo "<script type='text/javascript'>sweetAlert('Oops...', 'Username already in use!', 'error');</script>";
			echo '<META HTTP-EQUIV=REFRESH CONTENT="100"; '.$url.'">'; 
			die; 
		} 
        if(empty($_POST['password'])) 
        {
			echo "<script type='text/javascript'>sweetAlert('Oops...', 'Password already in use!', 'error');</script>";	
			echo '<META HTTP-EQUIV=REFRESH CONTENT="100"; '.$url.'">'; 
			die; 
		} 
        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) 
        { 
			echo "<script type='text/javascript'>sweetAlert('Oops...', 'Incorrect email format!', 'error');</script>";	
			echo '<META HTTP-EQUIV=REFRESH CONTENT="100"; '.$url.'">'; 
			die; 
		} 
         
        // Check if the username is already taken
        $query = " 
            SELECT 
                1 
            FROM users 
            WHERE 
                username = :username 
        "; 
        $query_params = array( ':username' => $_POST['username'] ); 
        try { 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } 
        $row = $stmt->fetch(); 
        if($row){
					echo "<script type='text/javascript'>sweetAlert('Oops...', 'This username is already in use!', 'error');</script>";
					echo '<META HTTP-EQUIV=REFRESH CONTENT="100"; '.$url.'">'; 
					die; 
				} 
        $query = " 
            SELECT 
                1 
            FROM users 
            WHERE 
                email = :email 
        "; 
        $query_params = array( 
            ':email' => $_POST['email'] 
        ); 
        try { 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage());} 
        $row = $stmt->fetch(); 
        if($row){ 		
					echo "<script type='text/javascript'>swal('Oops...', 'This email address is already registered!', 'error');</script>";
					echo '<META HTTP-EQUIV=REFRESH CONTENT="100"; '.$url.'">'; 
					die; 
				} 
         
        // Add row to database 
        $query = " 
            INSERT INTO users ( 
                username, 
                password, 
                salt, 
                email,
				lang
            ) VALUES ( 
                :username, 
                :password, 
                :salt, 
                :email,
				:lang
            ) 
        "; 
         
        // Security measures
        $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); 
        $password = hash('sha256', $_POST['password'] . $salt); 
        for($round = 0; $round < 65536; $round++){ $password = hash('sha256', $password . $salt); } 
        $query_params = array( 
            ':username' => htmlentities(stripslashes($_POST['username']), ENT_QUOTES), 
            ':password' => $password, 
            ':salt' => $salt, 
            ':email' => $_POST['email'],
			':lang' => $_POST['lang']
        ); 
        try {  
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } 
					echo "<script type='text/javascript'>swal('Good job!', 'You Are Now Registered!', 'success');</script>";
					echo '<meta http-equiv="refresh" content="2; index.php">'; 
					die(); 
    } 
?>
</body>
</html>