<?php 

$max_username = 30;
$max_email = 100;

$dir = '../';

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

$errors = array();

// check login
if(!isset($user_id)){
   $errors[] = LOG_IN;
}

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

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

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

if($username != $u['username']){
   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) > $max_email){
   $errors[] = "Email address cannot be more than $max_email characters";
}

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

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

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

   ex_messages($errors);

}else{

   if(query("UPDATE users SET username = '{$username}', email = '{$email}' WHERE id = '{$user_id}' LIMIT 1")){

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

      ex_messages(['Your information has been updated successfully']);

   }else{

      ex_messages([ERROR_DATABASE]);

   }

}

?>