<?php 

$max_username = 30;
$max_email = 100;

$dir = '../../';

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

$errors = array();

$id = (int)$_GET['id'];

$points = (int)$_POST['points'];
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

$sql = "SELECT * FROM users WHERE id = '{$id}' LIMIT 1";
if(fetch_rows($sql) < 1){
    $errors[] = "User could not be found";
}else{
    $x = fetch_records($sql);
}

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

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

// 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";
}

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

    $_SESSION['messages'] = $errors;

}else{

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

        $_SESSION['messages'][] = "User info has been updated successfully";

    }else{

        // on error
        $_SESSION['messages'][] = "MySQL Error: Cannot update user record";

    }

}

header("Location: ../user/{$id}/edit");
exit;

?>