<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php include("_insertGlobalViewers.php"); ?>
<?php
  // Individual Page Viewers
  // load records
  list($general_contentRecords, $general_contentMetaData) = getRecords(array(
    'tableName'   => 'general_content',
    'where'       => 'num=2',
  ));
  $general_contentRecord = @$general_contentRecords[0]; // get first record

  // show error message if no matching record is found
  if (!$general_contentRecord) { dieWith404("Record not found!"); }?>
<?php

  $showSignupForm = true;

  // error checking
  if (@$CURRENT_USER) {
    $errorsAndAlerts = "You are already signed up! <a href='{$GLOBALS['WEBSITE_LOGIN_POST_LOGIN_URL']}'>Click here to continue</a>.";
    $showSignupForm = false;
  }

  // process form
  if (@$_REQUEST['save']) {
  $friend_of = "\t".join("\t",@$_REQUEST['friend_of'])."\t";

    // error checking
    $errorsAndAlerts = "";
    if (!@$_REQUEST['fullname'])                { $errorsAndAlerts .= "You must enter your full name!<br/>\n"; }
    if (!@$_REQUEST['email'])                   { $errorsAndAlerts .= "You must enter your email!<br/>\n"; }
    else if(!isValidEmail(@$_REQUEST['email'])) { $errorsAndAlerts .= "Please enter a valid email (example: user@example.com)<br/>\n"; }
	if (!@$_REQUEST['friend_of'])              { $errorsAndAlerts .= "You must select your team!<br/>\n"; }
	if (!@$_REQUEST['mobile'])                  { $errorsAndAlerts .= "You must enter your mobile number!<br/>\n"; }
if (!@$_REQUEST['password'])                { $errorsAndAlerts .= "You must enter a password!<br/>\n"; } 
    elseif (@$_REQUEST['password'] != @$_REQUEST['password2']) { $errorsAndAlerts .= "Your passwords don't match! <br/>\n";} 
	
    // check for duplicate usernames and emails
    if (!$errorsAndAlerts) {
      $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"; }

      $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"; }
    }

    // turn off strict mysql error checking for: STRICT_ALL_TABLES
    mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)

// Mobile Number Format 
// converts a "04" mobile number to a "614" mobile number 
    function format_mobile_number($mobile){ 
       
      //strip out spaces  
      $tmpPhone = str_replace(" ","",$mobile);  
      $tmpPhone = str_split($tmpPhone); 
       
      if(@$tmpPhone[1]==4){ //number is in the local format.  Convert it to international format 
         
        $tmpPhone[0]=61; 
         
        $phone=implode($tmpPhone);  
      } 
      elseif(@$tmpPhone[0]==6 && @$tmpPhone[1]==1 && @$tmpPhone[2]==4){ //number is in international format.  Return it as is. 
         
        $phone = implode($tmpPhone); 
      } 
      else{ //error.  The number is in an invalid format. 
         
        return false;  
      } 
       
      return $phone;  
    }

    //format mobile number. 
    $mobile = format_mobile_number(@$_REQUEST['mobile']); 
    if(!$mobile){ $errorsAndAlerts .= "You must enter a valid mobile number! <br/>\n";} 

    // turn off strict mysql error checking for: STRICT_ALL_TABLES
    mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)

    // add user
    if (!$errorsAndAlerts) {

      // generate password
      $password = @$_REQUEST['password2'];
	  if (@$SETTINGS['advanced']['encryptPasswords']) { $passwordHash = getPasswordDigest($password); }
      else                                            { $passwordHash = $password; }

      //
      mysql_query("INSERT INTO `{$TABLE_PREFIX}" . @$GLOBALS['WSM_ACCOUNTS_TABLE'] . "` SET
                      fullname         = '".mysql_escape( $_REQUEST['fullname'] )."',
                      email            = '".mysql_escape( $_REQUEST['email'] )."',
                      username         = '".mysql_escape( $_REQUEST['email'] )."',
                      password         = '".mysql_escape( $passwordHash )."',

                      friend_of       = '".mysql_escape( $friend_of )."',
					  mobile           = '".mysql_escape($mobile)."',

                      disabled         = '0',
                      isAdmin          = '0',
                      expiresDate      = '0000-00-00 00:00:00',
                      neverExpires     = '1',
                      createdDate      = NOW(),
                      updatedDate      = NOW(),
                      createdByUserNum = '0',
                      updatedByUserNum = '0'")
      or die("MySQL Error Creating Record:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      $userNum = mysql_insert_id();

      // If a table other than the standard accounts table has been set for this
      // plugin, do not update the accesslist table
      if (@$GLOBALS['WSM_ACCOUNTS_TABLE']=="accounts") {
        // create accesslist entry
        // replace '_sample' with the table you want the user to access
        // replace '6' with the access level they should have: 0=none, 6=author, 9=editor
        // replace '1' with the max listings they are allowed
        mysql_query("INSERT INTO `{$TABLE_PREFIX}_accesslist`
                                 (userNum,  tableName,        accessLevel, maxRecords, randomSaveId)
                          VALUES ($userNum, 'all',            '1',         NULL,       '1234567890'),
                                 ($userNum, '_sample',        '6',         1,          '1234567890'),
                                 ($userNum, '_sample',        '6',         1,          '1234567890'),
                                 ($userNum, '_sample',        '6',         1,          '1234567890')") or die("MySQL Error Creating Access List:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      }

      // send message
      $emailTemplate = "emails/user-new-signup.php";
      $emailHeaders  = emailTemplate_load(array(
                        'template'     => websiteLogin_pluginDir() . "/$emailTemplate",
                        'subject'      => '', // set in template
                        'from'         => '', // set in template
                        'to'           => $_REQUEST['email'],
                        'placeholders' => array(
                          'username' => array_key_exists('username', $_REQUEST) ? $_REQUEST['username'] : $_REQUEST['email'], // if using email as username then show that instead
                          'password' => $password,
                          'loginUrl' => "http://" . $_SERVER['HTTP_HOST'] . $GLOBALS['WEBSITE_LOGIN_LOGIN_FORM_URL'],
                        ),
                      ));
      $mailErrors   = sendMessage($emailHeaders);
      if ($mailErrors) { die("Mail Error: $mailErrors"); }

      // show thanks
      $errorsAndAlerts  = "Thanks, We've created an account for you and emailed you your password.<br/><br/>\n";
      $errorsAndAlerts .= "If you don't receive an email from us within a few minutes check your spam filter for messages from {$emailHeaders['from']}<br/><br/>\n";
      $errorsAndAlerts .= "<a href='{$GLOBALS['WEBSITE_LOGIN_LOGIN_FORM_URL']}'>Click here to login</a>.";

      $_REQUEST        = array(); // clear form values
      $showSignupForm  = false;
    }
  }

?>
<?php include("_insertGlobalViewers.php"); ?>
<!doctype html>
<html>
<head>
<title><?php if ($general_contentRecord['seo_title']): ?><?php echo $general_contentRecord['seo_title'] ?><?php else: ?><?php echo $home_pageRecord['seo_title'] ?><?php endif ?></title>
<meta charset="utf-8" />

<meta name="keywords" content="<?php if ($general_contentRecord['seo_keywords']): ?><?php echo $general_contentRecord['seo_keywords'] ?><?php else: ?><?php echo $home_pageRecord['seo_keywords'] ?><?php endif ?>" />
<meta name="description" content="<?php if ($general_contentRecord['seo_description']): ?><?php echo $general_contentRecord['seo_description'] ?><?php else: ?><?php echo $home_pageRecord['seo_description'] ?><?php endif ?>" />

<?php include("_insertGlobalCode.php"); ?>
<?php include("_insertTop.php"); ?>
  <div id="wrapper" class="clearfix body">
		<?php include("_insertRightCol.php"); ?>
        <div id="maincol">
          <div class="padded">
              <!-- PAGE CONTENT -->
              <?php echo $general_contentRecord['content'] ?>
              <!-- MODULE CONTENT -->
              <?php if ($general_contentRecord['insert_module']) { include "_module" .$general_contentRecord['insert_module:label']. ".php"; } ?>
             
              <?php if (@$errorsAndAlerts): ?>
                <div id="alert">
                  <?php echo $errorsAndAlerts; ?>
                </div>
              <?php endif ?>
            
            <!-- USER SIGNUP FORM -->
            
            <?php if ($showSignupForm): ?>
                              <form method="post" action="?">
                              <input type="hidden" name="save" value="1" />
                            
                              <table class="formTable">
                               <tr>
                                <td>Name</td>
                                <td><input type="text" name="fullname" value="<?php echo htmlspecialchars(@$_REQUEST['fullname']); ?>" class="textBoxA"  /></td>
                               </tr>
                               <tr>
                                <td>Email</td>
                                <td><input type="text" name="email" value="<?php echo htmlspecialchars(@$_REQUEST['email']); ?>" class="textBoxA"  /></td>
                               </tr>
                               <tr>
                                <td>Mobile</td>
                                <td><input type="text" name="mobile" value="<?php echo htmlspecialchars(@$_REQUEST['mobile']); ?>" class="textBoxA"  /></td>
                               </tr>
                               <tr>
                                <td colspan="2"><p>Place a tick in the team boxes to indicate your current participation (i) as a player; and/ or (ii) as a parent/parent substitute</p></td>
                               </tr>
<tr> 
    <td>Password</td> 
    <td><input type="password" name="password" value="<?php echo htmlspecialchars(@$_REQUEST['password']); ?>"  class="textBoxA"  /></td> 
   </tr> 
   <tr> 
    <td>Re-enter your password</td> 
    <td><input type="password" name="password2" value="<?php echo htmlspecialchars(@$_REQUEST['password2']); ?>"  class="textBoxA"  /></td> 
   </tr>
                                 <tr> 
                                   <td valign="top"></td> 
                                   <td> 
                                     <?php $fieldname = 'friend_of'; ?> 
                                     <?php 
                                        if(is_array(@$_REQUEST[$fieldname])){ 
                                          $fieldValues = $_REQUEST[$fieldname]; 
                                        } 
                                        else{ 
                                          $fieldValues = explode("\t",trim(@$_REQUEST[$fieldname],"\t")); 
                                        } 
                                      ?> 
                                     <?php $idCounter = 0; ?> 
                                                 <ul class="noList">
                                                 <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?> 
                                                   <?php $id = "$fieldname." . ++$idCounter; ?>
                                                   <li> 
                                                   <input type="checkbox" name="<?php echo $fieldname ?>[]" id="<?php echo $id ?>" 
                                                         value="<?php echo htmlspecialchars($value) ?>" <?php if(in_array($value,$fieldValues)):?> checked="checked" <?php endif ?> style="height:auto;"/> 
                                                   <label for="<?php echo $id ?>"><?php echo htmlspecialchars($label) ?></label>
                                                   </li>
                                                 <?php endforeach ?>
                                                 </ul>
                                   </td> 
                                  </tr>
                               <tr>
                                <td colspan="2" align="center">
                                  <br/><input type="submit" name="submit" value="Register" />
                                </td>
                               </tr>
                              </table>
                            
                              </form>
            <?php endif ?>
          </div>
        </div>
        <div id="leftcol">
        </div>
<?php include("_insertBottom.php"); ?>