<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 2/15/2015
 * Time: 5:46 PM
 */

require('../../inc/db.php');
include('../../inc/functions.php');

$output                     =   array(
    'status'                =>  1
);
$params                     =   getParams();

if( !isReady( $params, array("username", "email", "pass1", "pass2") ) ){
    $output['message']      =   "Please fill in all fields!";
    dj($output);
}

if($settings['registration'] == 2){
    $output['message']      =   "Registration Disabled!";
    dj($output);
}

$username                   =   secure($params['username']);
$email                      =   secure($params['email']);
$pass1                      =   secure($params['pass1'], true);
$pass2                      =   secure($params['pass2'], true);
$upl_dir                    =   substr($username, 0, 1) . "/" . mt_rand(1,10) . "/" . $username;
$header_img                 =   "headers/" .  mt_rand(1,14) . ".jpg";

if($pass1 !== $pass2){
    $output['message']      =   "Passwords don't match";
    dj($output);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $output['message']      =   "The email you entered was invalid.";
    dj($output);
}

if(!ctype_alnum($username) || strtolower($username) == "system" ){
    $output['message']      =   "Invalid username. Alphanumeric characters only!";
    dj($output);
}

$usernameCheckQuery         =   $db->prepare("SELECT * FROM users WHERE username = :username");
$usernameCheckQuery->execute(array(":username" =>  $username));
if($usernameCheckQuery->rowCount() > 0){
    $output['message']      =   "Username taken!";
    dj($output);
}

$emailCheckQuery            =   $db->prepare("SELECT * FROM users WHERE email = :email");
$emailCheckQuery->execute(array(":email" =>  $email));
if($emailCheckQuery->rowCount() > 0){
    $output['message']      =   "E-mail taken!";
    dj($output);
}

if(!mkdir("../../uploads/" . $upl_dir, 0777, true)){
    $output['message']      =   "Could not create account. Try again later.";
    dj($output);
}

$insertUserQuery            =   $db->prepare("INSERT INTO users(username,email,pass,upl_dir,time_created,header_img)
                                              VALUES( :u, :e, :p, :ud, :tc, :hi )");
$insertUserQuery->execute(array(
    ":u"                    =>  $username,
    ":e"                    =>  $email,
    ":p"                    =>  $pass1,
    ":ud"                   =>  $upl_dir,
    ":tc"                   =>  time(),
    ":hi"                   =>  $header_img
));

$output['status']           =   2;
$_SESSION['loggedin']       =   true;
$_SESSION['uid']            =   $db->lastInsertId();
$_SESSION['username']       =   $username;
dj($output);