<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php
  $libraryPath = 'admin/lib/viewer_functions.php';
  $dirsToCheck = array('/home/content/a/i/r/airliftweb/html/','','../','../../','../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

  // user login check
  if (!$CURRENT_USER) { websiteLogin_redirectToLogin("login.php"); }

  // process form
  if (@$_REQUEST['save']) {

    // error checking
    $errorsAndAlerts = "";
    if (!@$_REQUEST['fullname'])                { $errorsAndAlerts .= "You must enter your name<br/>\n"; $nameerror="yes"; }
    if (!@$_REQUEST['email'])                   { $errorsAndAlerts .= "You must enter an email address<br/>\n"; $emailerror="yes";}
    else if(!isValidEmail(@$_REQUEST['email'])) { $errorsAndAlerts .= "Please enter a valid email (example: user@example.com)<br/>\n"; $emailerror="yes";}
    // if (!@$_REQUEST['username'])                { $errorsAndAlerts .= "You must choose a username!<br/>\n"; }

    // new password checking
    if (@$_REQUEST['oldPassword'] || $_REQUEST['newPassword1'] || $_REQUEST['newPassword2']) {
      if (!@$_REQUEST['oldPassword'])                                 { $errorsAndAlerts .= "Please enter a value for \"Current Password\"<br/>\n"; $passworderror="yes"; }
      elseif (@$_REQUEST['oldPassword'] != $CURRENT_USER['password']) { $errorsAndAlerts .= "Current password isn't correct!<br/>\n"; $passworderror="yes"; }
      elseif (!@$_REQUEST['newPassword1'])                            { $errorsAndAlerts .= "Please enter a value for \"New Password\"<br/>\n"; $passworderror="yes"; }
      elseif (!@$_REQUEST['newPassword2'])                            { $errorsAndAlerts .= "Please enter a value for \"Confirm New Password\"<br/>\n"; $passworderror="yes"; }
      elseif ($_REQUEST['newPassword1'] != $_REQUEST['newPassword2']) { $errorsAndAlerts .= "New passwords don't match<br/>\n"; $passworderror="yes"; }
    }

    // check for duplicate usernames and emails
    if (@$_REQUEST['username'] != $CURRENT_USER['username']) {
      $count = mysql_select_count_from('accounts', "`username` = '".mysql_escape(@$_REQUEST['username'])."'");
      if ($count > 0 && @$_REQUEST['username']) { $errorsAndAlerts .= "That username is already in use, please choose another!<br/>\n"; }
    }
    if (@$_REQUEST['email'] != $CURRENT_USER['email']) {
      $count = mysql_select_count_from('accounts', "'".mysql_escape($_REQUEST['email'])."' IN (email, username)");
      if ($count > 0) { $errorsAndAlerts .= "That email is already in use, please choose another!<br/>\n"; $emailerror="yes"; }
    }

    // update user
    if (!$errorsAndAlerts) {
      mysqlStrictMode(false);   // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
      if (@$_REQUEST['newPassword2']) { $CURRENT_USER['password'] = $_REQUEST['newPassword2']; } // update password
      $query = "UPDATE `{$TABLE_PREFIX}accounts` SET
                      fullname         = '".mysql_escape( $_REQUEST['fullname'] )."',
                      email            = '".mysql_escape( $_REQUEST['email'] )."',
                      username         = '".mysql_escape( $_REQUEST['email'] )."',
                      password         = '".mysql_escape( $CURRENT_USER['password'] )."',

                      address_1        = '".mysql_escape( $_REQUEST['address_1'] )."',
                      address_2        = '".mysql_escape( $_REQUEST['address_2'] )."',
                      city             = '".mysql_escape( $_REQUEST['city'] )."',
                      state            = '".mysql_escape( $_REQUEST['state'] )."',
                      zipcode          = '".mysql_escape( $_REQUEST['zipcode'] )."',
                      phone            = '".mysql_escape( $_REQUEST['phone'] )."',

                      updatedByUserNum = '".mysql_escape( $CURRENT_USER['num'] )."',
                      updatedDate      = NOW()
                 WHERE num = '".mysql_escape( $CURRENT_USER['num'] )."'";
      mysql_query($query) or die("MySQL Error:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      $userNum = mysql_insert_id();

      // on success
      unset($_REQUEST['oldPassword'], $_REQUEST['newPassword1'], $_REQUEST['newPassword2']); // clear password fields
      $errorsAndAlerts = "Your account has been updated.";
    }
  }

  // prepopulate form with current user values
  foreach ($CURRENT_USER as $name => $value) {
    if (array_key_exists($name, $_REQUEST)) { continue; }
    $_REQUEST[$name] = $value;
  }

  // delete account
  if (@$_POST['deleteAccount']) {
    if ($CURRENT_USER['isAdmin']) { die("Error: Deleting admin accounts is not permitted!"); }

    // delete uploads
    $GLOBALS['tableName'] = 'accounts';
    eraseRecordsUploads( $CURRENT_USER['num'] );

    // delete account
    $query = mysql_escapef("DELETE FROM `{$TABLE_PREFIX}accounts` WHERE num = ?", $CURRENT_USER['num']);
    mysql_query($query) or die("MySQL Error:<br/>\n". htmlspecialchars(mysql_error()) . "\n");

    // redirect to login
    websiteLogin_redirectToLogin();
  }

	include("../includes/header.inc.php");
?>


		<?php include("includes/sidebar-left.inc.php"); ?>

		<div id="col_sub">

			<div id="col2">

				<h2>Update Your Account</h2>

				<?php if (@$errorsAndAlerts): ?>
					<div class="alerts">
						<?php echo $errorsAndAlerts; ?>
					</div>
				<?php endif ?>


				<form method="post" action="?" class="profile">
					<input type="hidden" name="save" value="1" />

					<div class="section">
						<div<?php if(@$nameerror=="yes") echo " class='error'"; ?>>
							<label>Name</label>
							<input type="text" name="fullname" value="<?php echo htmlspecialchars(@$_REQUEST['fullname']); ?>" />
						</div>
						<div<?php if(@$emailerror=="yes") echo " class='error'"; ?>>
							<label>Email Address</label>
							<input type="text" name="email" value="<?php echo htmlspecialchars(@$_REQUEST['email']); ?>" />
						</div>
					</div>


					<div class="section">
						<h4>Contact Information</h4>
						<div>
							<label>Address 1</label>
							<input type="text" name="address_1" value="<?php echo htmlspecialchars(@$_REQUEST['address_1']); ?>" />
						</div>
						<div>
							<label>Address 2</label>
							<input type="text" name="address_2" value="<?php echo htmlspecialchars(@$_REQUEST['address_2']); ?>" />
						</div>
						<div>
							<label>City</label>
							<input type="text" name="city" value="<?php echo htmlspecialchars(@$_REQUEST['city']); ?>" />
						</div>
						<div>
							<label>State</label>
							<input type="text" name="state" value="<?php echo htmlspecialchars(@$_REQUEST['state']); ?>" />
						</div>
						<div>
							<label>Zip Code</label>
							<input type="text" name="zipcode" value="<?php echo htmlspecialchars(@$_REQUEST['zipcode']); ?>" />
						</div>
						<div>
							<label>Phone</label>
							<input type="text" name="phone" value="<?php echo htmlspecialchars(@$_REQUEST['phone']); ?>" />
						</div>
					</div>


					<div class="section">
						<h4>Password</h4>
						<div<?php if(@$passworderror=="yes") echo " class='error'"; ?>>
							<label>Current Password</label>
							<input type="password" name="oldPassword" value="" />
						</div>
						<div<?php if(@$passworderror=="yes") echo " class='error'"; ?>>
							<label>New Password</label>
							<input type="password" name="newPassword1" value="<?php echo htmlspecialchars(@$_REQUEST['newPassword1']); ?>" />
						</div>
						<div<?php if(@$passworderror=="yes") echo " class='error'"; ?>>
							<label>Confirm New Password</label>
							<input type="password" name="newPassword2" value="<?php echo htmlspecialchars(@$_REQUEST['newPassword2']); ?>" />
						</div>
					</div>

					<div>
						<input class="button" type="submit" name="submit" value="Update" /> <a href="./">Cancel</a>
					</div>

				</form>


			</div><!-- /col2-->

			<div id="col3">
			</div><!-- /col3-->

		</div><!-- /col_sub-->

<?php include("../includes/footer.inc.php"); ?>
