<?
/* 
   This file is part of the 'Science Fair In A Box' project
   SFIAB Website: http://www.sfiab.ca

   Copyright (C) 2005 Sci-Tech Ontario Inc <info@scitechontario.org>
   Copyright (C) 2005 James Grant <james@lightbox.org>
   Copyright (C) 2007 David Grant <dave@lightbox.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation, version 2.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/
?>
<?
 require_once("common.inc.php");
 require_once("user.inc.php");
 user_auth_required();

 // grab data for the available role types
 $roleDat = array();
 $q = mysql_query("SELECT * FROM roles");
 while($row = mysql_fetch_assoc($q)){
 	$roleDat[$row['type']] = array(
		'id' => $row['id'],
		'name' => $row['name']
	);
 }


 $u = user_load($_SESSION['users_id']);

if(array_key_exists('action', $_GET)){
	switch($_GET['action']){
		case 'register':
			register_new_role();
			break;
		default:
			break;
	}
	exit;
}


 send_header("Main Page", array());
?>
<script type="text/javascript">
	function register(role){
		//alert($('#' + role + '_password').val());
		$.post('user_main.php?action=register',
			{
				'role' : role,
				'password' : $('#' + role + '_password').val()
			},
			function(result){
				alert(result);
			}
		);
	}
</script>
<?php
 //only display the named greeting if we have their name
 echo i18n("Hello <b>%1</b>",array($_SESSION['name']));
 echo "<br />";
 echo "<br />";

 echo "This is a placeholder for the main user page until all the specific user-role pages are removed.  For now, heres your roles: ";
 echo "<br />";
 echo "<br />";

 // get a list of all roles that this user can potentially sign up for
 $rlist = array();
 $q = mysql_query("SELECT * FROM roles");
 $available = array();
 $registered = array();
 while($row = mysql_fetch_assoc($q)){
 	$roleid = $row['type'];
 	$idx = $roleid . "_registration_type";
 	if(array_key_exists($idx, $config)){
 		// this is a role that can potentially be registered for
 		if(is_array($u['roles']) && array_key_exists($row['type'], $u['roles'])){
 			$registered[$row['type']] = $row['name'];
 		}else{
 			$available[$row['type']] = $row['name'];
 		}
 	}
 }

 if(count($registered) > 0){
 	echo "<h4>You are currently registered for the following roles:</h4>";
 	foreach($registered as $type => $title){
 		echo "$title<br/>";
 	}
 	echo "<br/>";
 }

 if(count($available) > 0){
 	echo "<h4>The following roles are available:</h4>";
	$rowNumber = 0;
	echo "<table class=\"summarytable\">";
 	foreach($available as $type => $title){
		echo '<tr class="';
		if(($rowNumber++) % 2) echo 'odd';
		else echo 'even';
		echo '">';
 		echo "<td><strong>$title</strong></td><td>";
		draw_signup_form($type);
		echo "</td></tr>";
 	}
	echo "</table>";
 }

 echo "<br />";
 echo i18n('Other Options and Things To Do').':<br />';
 echo '<ul>';
 echo '<li><a href="user_edit.php">'.i18n('Change Password').'</a> - '.i18n('Change your email, username, and password').'</li>';
 echo '<li><a href="user_edit.php">'.i18n('Activate/Deactivate Roles').'</a> - '.
		i18n('Activate/Deactiate/Remove/Delete roles or your entire account').
		'</li>';
 echo '<li>'.i18n('To logout, use the "Logout" link in the upper-right of the page').'</li>';
 echo '</ul>';

/*
echo "<pre>";
echo htmlentities(print_r($u, true));
echo htmlentities(print_r($config, true));
echo "</pre>";
*/

 send_footer();

function draw_signup_form($type){
	global $config;
	global $roleDat;
	switch($type) {
		case 'volunteer':
			// returns "notopenyet", "closed", or "open"
			$reg_open = user_volunteer_registration_status(); 
			$reg_mode = $config['volunteer_registration_type'];
//			$reg_single_password = $config['volunteer_registration_singlepassword'];
//			$password_expiry_days = $config['volunteer_password_expiry_days'];
//			$welcome_email = "volunteer_welcome";
			break;
		/*case 'committee':
		
			$reg_open = 'notpermitted';
			$reg_mode = 'closed';
			$reg_single_password = '';
			$password_expiry_days = 0;
			$welcome_email = false;
			break;
		*/
		case 'judge':
			$reg_open = user_judge_registration_status();
			$reg_mode = $config['judge_registration_type'];
//			$reg_single_password = $config['judge_registration_singlepassword'];
//			$password_expiry_days = $config['judges_password_expiry_days'];
//			$welcome_email = "judge_welcome";
			break;
		/*
		case 'student':
			$reg_open = 'closed';
			//	$reg_mode = $config['judge_registration_type'];
			//	$reg_single_password = $config['judge_registration_singlepassword'];
			$password_expiry_days = 0;
			$welcome_email = "register_students_welcome";
			break;
		*/
		default:
			echo "Not handled";
			return;
	}
	if($reg_open == 'open'){
		switch($reg_mode){
			case 'open':
				echo "\"$reg_mode\" registration is not yet handled";
				break;
			case 'singlepassword':
				echo '<p>';
				echo i18n("{$roleDat[$type]['name']} Registration is protected by a password.  You must know the <b>{$roleDat[$type]['name']} Registration Password</b> in order to create an account.  Please contact the committee to obtain the password if you wish to register.");
				echo "</p><p>";
				echo i18n("{$roleDat[$type]['name']} Password").":<input type=\"password\" size=\"20\" id=\"{$type}_password\" />";
				echo "<button onclick=\"register('" . $type . "');\">Register</button>";
				echo "</p>";
				break;
			case 'schoolpassword':
				echo "\"$reg_mode\" registration is not yet handled";
				break;
			case 'invite':
				output_page_text("register_{$type}_invite");
				break;
			case 'openorinvite':
				echo "\"$reg_mode\" registration is not yet handled";
				break;
			default:
				echo "Unhandled registration mode: $reg_mode";
		}
	}else{
		echo i18n("{$roleDat[$type]['name']} registration is not open");
	}
/*
	echo "<hr/>\$reg_mode = $reg_mode<br/>";
	echo "\$reg_open = $reg_open<br/>";
	echo "<pre>";
//	print_r($config);
	echo "</pre>";
*/

}

function register_new_role(){
	global $config, $roleDat, $u;
	$password = $_POST['password'];
	$uid = $_SESSION['users_id'];
	$roleId = $_POST['role'];
	$typekey = $roleId . '_registration_type';
	$accounts_id = $u['accounts_id'];
	if(array_key_exists($typekey, $config)){
		$regtype = $config[$typekey];
	}else{
		return false;
	}

	// see if the registration is allowed for this role with the information provided
	$canRegister = true;
	$role = $_POST['role'];
	switch($regtype){
		case 'open':
		case 'openorinvite':
			// ok, we can allow these
			break;
		case 'singlepassword':
			if($password != $config[$role . '_registration_singlepassword']){
				$canRegister = false;
			}
			break;
		case 'schoolpassword':
			// FIXME: not yet implemented.
			// this is only used for students, who are not yet registered through the "user" system
			$canRegister = false;
			break;
		case 'invite':
			$canRegister = false;
			break;
		default:
//			echo "[\$regtype = \"$regtype\"]";
			$canRegister = false;
	}
	if(!$canRegister) return false;


	// ok, they meet the conditions to register for this role
	// see if they're already registered for it
	$role_index = $roleDat[$role]['id'];
	$query = "SELECT COUNT(*) FROM user_roles WHERE users_id = $uid AND roles_id=$role_index";
	$results = mysql_fetch_array(mysql_query($query));
	if($results[0] != 0){
		return false;
	}

	// not already regiseterd, let's go ahead and hook 'em up
	$query = "INSERT INTO user_roles (accounts_id, users_id, roles_id, active, complete)";
	$query .= " VALUES($accounts_id, $uid, $role_index, 'yes', 'no')";
	echo $query;
	return true;
	/*
	if(mysql_query($query)){
		return true;
	}else{
		return false;
	}
	*/
}