<?php 
    session_start();
	if ( !empty($_SESSION['login']) ) {
        header( 'Location: /' );
        die;
	}

    include 'include/header.php';    
?>

    <div class="wrap">
<?php
    include 'include/database.php';
    
    $added = False;
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
    
        if ( !empty($_POST['user']) && !empty($_POST['pass']) &&
             !empty($_POST['confirm']) && !empty($_POST['email']) ) {
             
            if ( $_POST['pass'] === $_POST['confirm'] ) {
                $connection = connect($database);
                $added = add_user($connection, $_POST['user'], $_POST['pass'], $_POST['email']);
                $connection = null;
            } else {
                echo '<strong class="warning center block">Passwords do not match!</strong>';
            }
            
        } else {
            echo '<strong class="warning center block">All fields must be completed!</strong>';
        }
        
    }
    
    if ($added) {
        echo '
        <strong class="pad center block info">Please check your email for validation instructions!</strong>
        <strong class="pad center block info">Thanks for registering!</strong>
        ';
    } else {
        $user = ( empty($_POST['user']) ? '' : htmlspecialchars($_POST['user']) );
        $email = ( empty($_POST['email']) ? '' : htmlspecialchars($_POST['email']) );
        
        echo '
        <h1 class="pad-top">New User</h1>
        
        <form id="new_user" method="post" action="">
            <div>
                <label class="block" for="user">username:</label>
                <input id="user" type="text" name="user" value="'.$user.'" />
            </div>
            
            <div class="pad">
                <label class="block" for="pass">password:</label>
                <input id="pass" type="password" name="pass" autocomplete="off" />
            </div>
            
            <div>
                <label class="block" for="confirm">confirm password:</label>
                <input id="confirm" type="password" name="confirm" autocomplete="off" />
            </div>
            
            <div class="pad">
                <label class="block" for="email">email:</label>
                <input id="email" type="text" name="email" value="'.$email.'" />
            </div>
            
            <input type="submit" value="register" />
        </form>
        
        <div class="center">
            <a href="login.php">Already registered?</a>
        </div>
        ';
    }
?>
    
    </div>

<?php include 'include/footer.php'; ?>