<?
ob_start();

include("header.php");
include("user-helper.php");
include("util.php");

$color_array = array('dddddd', 'ffffff');

$pref_page = array_key_exists("id", $_GET);
$own_page = $pref_page && $_s_user_id == $_GET['id'];
$error_msg = false;

// First make sure that the required fields have something in them.
if ($_POST)
{
  $user = array();

  $error_msg = false;
  if (!$_s_user_id)
  {
    if (!array_key_exists('name', $_POST) || !$_POST['name'])
      $error_msg = "Please enter a name.";
    else if (!array_key_exists('username', $_POST) || !$_POST['username'])
      $error_msg = "Please select a user name.";
    else if (!array_key_exists('password', $_POST) || !$_POST['password'])
      $error_msg = "Please enter a password.";
    else if (!array_key_exists('confirm_password', $_POST) || !$_POST['confirm_password'])
      $error_msg = "Please enter your password again.";
    else if ($_POST['password'] != $_POST['confirm_password'])
      $error_msg = "Your password did not match your confirmation password.";
    else if (get_user_by_username($username = $_POST['username']))
      $error_msg = "Someone already signed up with email: '$username'";
  }
  else
  {
    if (array_key_exists('new_pword', $_POST))
    {
      if (strcmp($_POST['new_pword'],$_POST['confirm_new_pword']))
        $error_msg = "New password does not match confirmation.";
      else
      {
        if (array_key_exists('new_pword', $_POST))
          $_POST['password'] = $_POST['new_pword'];
        unset($_POST['new_pword']);
        unset($_POST['confirm_new_pword']);
      }
    }
  }

  // Copy everything to the $user array, because the values represent a user.
  foreach ($_POST as $key => $val)
  {
    // Strip slashes (prevent injection attacks) for non-numbers.
    if (!is_numeric($key))
      if (is_numeric($val))
        $user[$key] = $val;
      else
        $user[$key] = stripslashes($val);
  }

  if (!$error_msg)
  {
    // Check if we're updating or creating.
    if ($pref_page)
    {
      // Make sure the logged in user is an admin or the same as the 
      // user whose information is being changed.
      if ($_s_user_id != $_GET['id'] && !user_is_admin($_s_user_id))
      {
        header("Location:home.html");
      }
      else
      {
        $user['id'] = $_GET['id'];

        // If the signed-in user is an adimin, he could be changing 
        // this user to be an admin or captain.
        if (!user_is_admin($_s_user_id) && $user['status'])
          unset($user['status']);

        if (!strcmp($_POST['reset-password'], "true"))
        {
          if (!reset_user_password($user))
            $error_msg = 'Could not reset password!';
        }
        else
        {
          if (!update_user($user))
            $error_msg = 'Could not update user info ...';
        }

        // Get the user again, because the updating process kind of eliminates
        // some of the fields in the array.
        $user = get_user_by_id($_GET['id']);
      }
    }
    else  // Creating a new user.
    {
      // Create a new place for this guy.
      $id = add_user_to_team($user);

      if (!$id)
      {
        $error_msg = "Internal error (whoops). Sorry for the inconvenience,
                                                      but please try again.";
      }
      else
      {
        $_SESSION['user_id'] = $id;
        session_write_close();
//        echo '<div>User ID: "'.$id.'"</div>';
//        echo '<div>Session user ID: "'.$_SESSION['user_id'].'"</div>';
        header("Location:quote.html");
      }
    }
  }
}
// If this is an "edit preferences" page for neither an admin nor the 
// user him/herself, just redirect to this user's team's page.
else if ($pref_page)
{
  $user = get_user_by_id($_GET['id']);
  if ($_GET['id'] != $_s_user_id && !user_is_admin($_s_user_id))
    header("Location:team".$user['team_id'].'.html');
}

ob_flush();
?>

<? if ($frozen && !$pref_page) { ?>

<h1> The Olympics are over! </h1>

<div class="info">
Sorry, but the Olympics are over, so you can't register for a new account.  They ended on <?=$olympics_end_string?>, <?=$year?>, so check back around Janurary <?=($year+1)?> for the <?=($year+1)?> CSAIL Olympics!
</div>

<? } else { ?>

<script type="text/javascript" src="javascript/user-util.js"></script>
<form id="user-form" action="user<? if (array_key_exists('id', $_GET)) { echo $_GET['id']; } ?>.html" method="post">
  <div align="center">
<?   if ($error_msg) { ?>
    <div class="error"><?=$error_msg?></div>
<?   } else if ($_POST) { ?>
    <div id="notification" class="info">Preferences successfully updated!</div>
<?   } else if (!$pref_page) { ?>
    <b>Thank you for registering!</b>
    <br><br>
    Please answer the questions below.
    <br>
    We will use your answers to pick your team and introduce you to your
    teammates.
<?   } else if ($frozen) {?>
    <div class="info">
      NOTE: The Olympics are over, so certain
      things cannot be changed anymore.
    </div>
<?   } ?>
  </div>

  <table cellpadding="5">

<?   if (!$frozen) { ?>
    <tr bgcolor="#dddddd">
      <td>
        <span class="normal">What is your name?</span>
      </td>
      <td>
        <span class="normal">
          <input type="text" name="name" size="50"
                 value="<?=$user['name']?>">
        </span>
      </td>
    </tr>
<?   } ?>

    <tr bgcolor="#ffffff">
      <td>
        <span class="normal">
<?   if ($pref_page) { ?>
          Image URL for yourself:
<?   } else { ?>
          Please enter a URL that points to a small picture of you.
          (optional)
<?   } ?>
        </span>
      </td>
      <td>
        <span class="normal">
          <input type="text" size="50" name="image"
                 value="<?=$user['image']?>">
        </span>
      </td>
    </tr>

    <tr bgcolor="#dddddd">
      <td>
        <span class="normal">
          Your email (user name):
        </span></td>
      <td>
        <span class="normal">
          <input type="text" name="username" size="50"
<?     if ($pref_page) { ?>
                 disabled="disabled"
<?     } else { ?>
                 onblur="email_addr.ensure_valid(this)"
                 onmouseout="email_addr.ensure_valid(this)"
<?     } ?>
                 value="<?=$user['username']?>">
        </span>
      </td>
    </tr>

<?   if (!$pref_page || $own_page) { ?>
    <tr bgcolor="#ffffff">
      <td>
        <span class="normal">
<?     if ($pref_page) { ?>
          Change password:
<?     } else { ?>
          Please choose a password (not secure):
<?     } ?>
        </span>
      </td>
      <td>
        <span class="normal">
          <input name="<?=$_s_user_id ? 'new_pword' : 'password'?>"
                 type="password" value="" size="50">
        </span>
      </td>
    </tr>

    <tr bgcolor="#dddddd">
      <td>
        <span class="normal">
          Confirm <?=$_s_user_id ? 'changed' : 'your'?> password:
        </span>
      </td>
      <td>
        <span class="normal">
          <input name="confirm_<?=$_s_user_id ? 'new_pword' : 'password'?>"
                 type="password" value="" size="50">
        </span>
      </td>
    </tr>
<?   } ?>

<?   if (!$frozen) { ?>
    <tr bgcolor="#ffffff">
      <td>What is your gender?</td>
      <td>
        <span class="normal">
          Female <input type="radio" name="gender" value="0"
                 <? if ($user['gender'] == 0 ) { echo 'checked'; }?>>
          &nbsp; &nbsp; &nbsp;
          Male <input type="radio" name="gender" value="1"
               <? if ($user['gender'] == 1 ) { echo 'checked'; } ?>>
        </span>
      </td>
    </tr>
<?   } ?>

<?   if (!$frozen) { ?>
    <tr bgcolor="#dddddd">
      <td>
        <span class="normal">
<?     if ($_s_user_id) { ?>
          Participation:
<?     } else { ?>
          Approximately what fraction of events do you plan to participate in?
<?     } ?>
        </span>
      </td>
      <td>
<?   generate_participation_table($user); ?>
      </td>
    </tr>

    </tr><tr bgcolor="#ffffff">
      <td>Shirt size:</td>
      <td><? generate_size_options($user) ?></td>
    </tr>
<?   } ?>

    <tr bgcolor="#<?=$frozen ? 'ffffff' : 'dddddd'?>">
<?   if ($_s_user_id) { ?>
<?     if (!$frozen) { ?>
      <td>Quote:</td>
      <td><input size="50" type="text" name="quote" value="<?=$user['quote']?>"></td>
    </tr>

    <tr bgcolor="#ffffff">
<?     } ?>
<?     if (user_is_admin($_s_user_id)) { ?>
      <td>User status:</td>
      <td>
        <table>
          <tr><? generate_status_radio($user) ?></tr>
        </table>
      </td>
    </tr>

    <tr bgcolor="#dddddd">
      <td>
        <input type="button" value="Reset Password"
               name="reset-password"
               onclick="password.double_check_reset(this)">
      </td>
<?     } else { ?>
      <td></td>
<?     } ?>
<?   } else { ?>
      <td></td>
<?   } ?>
      <td>
        <span class="normal">
          <input type="submit" value="Submit">
        </span>
      </td>
    </tr>

  </table>
</form>

<script type="text/javascript">
  // Gives the name field focus.
  document.getElementsByName('name')[0].focus();
</script>

<? } ?>
<? include("footer.php"); ?>

