<?php

include('init.php');
include('libs/functions.php');


if (checklogin($userID, "menu.php")) {

$fname = scrub_sql(scrub_white_list(trim($_POST['fname']),'USER'), 20);
$lname = scrub_sql(scrub_white_list(trim($_POST['lname']),'USER'), 30);
$email = scrub_sql(scrub_white_list(trim($_POST['email']),'USER'), 150);
$phone = scrub_sql(scrub_white_list(trim($_POST['phone']),'USER'), 20);
$ext = scrub_sql(scrub_white_list(trim($_POST['ext']),'USER'), 10);

$PWDQ = "";

$password = trim($_POST['password']);

$errors=0;

if ($fname == "" || $lname == "" || $email == "" || $phone == "") {
$errors = 1;
$message = "Incomplete Form. Please fill out all required fields.";
}

else if (strlen($fname) < 1 || strlen($lname) < 1 || strlen($email) < 4 || strlen($phone) < 10 || strlen($ext) > 10 || strlen($fname) > 20 || strlen($lname) > 30 || strlen($email) > 120 || strlen($phone) > 20) {
$errors = 1;
$message = "One or more fields are incorrect length.";
}


else if (check_bad_char($email)) {
$errors = 1;
$message = "Email contains invalid characters.";
}

else if ($password <> "" && strlen($password) > 7 && strlen($password) < 21 && check_password($password)) {
$password = md5("gingerbreadcookies".$password);
$currentpassword = $_POST['currentpassword'];
$currentpasswordenc = md5("gingerbreadcookies".$currentpassword);
$sql = "SELECT count(user_id) AS cnt FROM tb_user WHERE user_id=$userID AND password='$currentpasswordenc'";
$rs = $db->Execute($sql);
$cnt = $rs->fields('cnt');
if ($cnt != 1) {
$errors = 1;
$message = "Incorrect current password";
}
else {
$PWDQ = ", password='$password'";
$sql = "UPDATE tb_password_update SET last_password_change=getdate() WHERE user_id=$userID";
$rs = $db->Execute($sql);

$sql_FLA = "UPDATE tb_user SET failed_login_attempt=0 WHERE user_id=$userID";
$rs_FLA = $db->Execute($sql_FLA);

}
}


// check if email exists
if ($errors == 0) {
$sql = "SELECT count(email) AS cnt FROM tb_user WHERE email='$email' AND email<>(SELECT email FROM tb_user WHERE user_id=$userID)";
$rs = $db->Execute($sql);
$cnt = $rs->fields('cnt');
if ($cnt > 0) {
$errors = 1;
$message = "Email address already exists.";
}
}


if ($errors == 0) {
$sql = "UPDATE tb_user SET fname='$fname', lname='$lname', email='$email', ext='$ext', phone='$phone'$PWDQ WHERE user_id=$userID";
$rs = $db->Execute($sql);

$sql = "INSERT INTO tb_audit (user_id, event, event_date) VALUES ($userID, 'User updated profile', getdate())";
$rs = $db->Execute($sql);


print_header();
print ("

<table width=800 align=center>
<tr><td>
<BR>
<HR>
<H1 align=center>Thank You!</H1>
<BR>
<HR>
<H3 align=center>Your account has been updated. <A HREF=./apps/index.php>Click here to continue</A></H3>
<BR>
<HR>
</td></tr></table>
");
print_footer();
} // end if no errors


// display error message
else {
print_header();
print "<br><hr><h1 align=center>$message</h1><hr><h3 align=center>Please press the Back button to return to previous page</h3>";
print_footer();
}


} // end check login

?>