<?php 

$min_username = 2;
$max_username = 20;
$min_email = 5;
$max_email = 100;
$min_password = 6;
$max_password = 20;

$dir = '../';

require_once $dir.'includes/main.php';

$errors = array();

$username = clean($_POST['username']);
$email = clean($_POST['email']);
$password = clean($_POST['password']);
$repassword = clean($_POST['repassword']);

// check username
if(empty($username)){
   $errors[] = "Username is required";
}

if(strlen($username) < $min_username){
   $errors[] = "Username must be more than $min_username characters";
}

if(strlen($username) > $max_username){
   $errors[] = "Username must be less than $max_username characters";
}

if(fetch_rows("SELECT id FROM users WHERE username = '{$username}' LIMIT 1") > 0){
   $errors[] = "Username already exists in the database";
}

// check email
if(empty($email)){
    $errors[] = "Email address is required";
}

if(strlen($email) < $min_email){
    $errors[] = "Email address must be more than $min_email characters";
}

if(strlen($email) > $max_email){
    $errors[] = "Email address must be less than $max_email characters";
}

if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $errors[] = "Email address is invalid";
}

if(fetch_rows("SELECT id FROM users WHERE email = '{$email}' LIMIT 1") > 0){
    $errors[] = "Email address already exists in the database";
}

// check password
if(empty($password)){
    $errors[] = "Password is required";
}

if(empty($repassword)){
    $errors[] = "You must retype password";
}

if(strlen($password) < $min_password){
    $errors[] = "Password must be more than $min_password characters";
}

if(strlen($password) > $max_password){
    $errors[] = "Password must be less than $max_password characters";
}

if($password !== $repassword){
    $errors[] = "Passwords do not match";
}

$errors = array_filter($errors);

// check errors
if(!empty($errors)){

   ex_messages($errors);

}else{

   $password = sha1($password);

   if(query("INSERT INTO users (username, email, password, last_seen, date_created) VALUES ('{$username}', '{$email}', '{$password}', '{$t}', '{$t}')")){

      $x = fetch_records("SELECT * FROM users WHERE username = '{$username}' ORDER BY id DESC LIMIT 1");

      query("INSERT INTO stats (user_id, date_created) VALUES ('{$x['id']}', '{$t}')");

      query("UPDATE _stats SET users = users + 1 ORDER BY id DESC LIMIT 1");

      setcookie('email', $email, $t + (60*60*24*30*12), '/');
      setcookie('password', $password, $t + (60*60*24*30*12), '/');

      ex_redirect("dashboard");

   }else{

      ex_messages([ERROR_DATABASE]);

   }

}

?>