<?php
function db_update_195_pre(){
}

function db_update_195_post(){
	// build a list of fields that we'll be migrating for the various user_<role> tables
	$fields['committee'] = array('emailprivate','ord','displayemail','access_admin',
			'access_config','access_super');
	$fields['judge'] = array('years_school','years_regional','years_national',
			'willing_chair','special_award_only',
			'cat_prefs','div_prefs','divsub_prefs',
			'expertise_other','languages', 'highest_psd');
	$fields['student'] = array('schools_id');
	$fields['fair'] = array('fairs_id');
	$fields['sponsor'] = array('sponsors_id','primary','position','notes');

	$max_id = 0;

	// let's do some data massaging
	mysql_query("BEGIN");
	try{
		mysql_query("ALTER TABLE accounts ADD COLUMN `year` INT COMMENT 'Temporary field, delete when finished migration'");
		$uidQuery = mysql_query("SELECT DISTINCT(uid) FROM users");
		while($uidDat = mysql_fetch_assoc($uidQuery)){
			$uid = $uidDat['uid'];
			$userQuery = "SELECT users.*, users_committee.access_super AS super FROM users" .
				     " LEFT JOIN users_committee ON users_committee.users_id = users.id" .
				     " WHERE uid=$uid ORDER BY year DESC";
			$userResults = mysql_query($userQuery); 
			$userRecord = mysql_fetch_assoc($userResults);

			// get the data that we need from this record
			// start with determining what username we'll be using
			$username = $userRecord['username'];
			if(trim($username) == '') $username = $userRecord['email'];
			if(trim($username) == '') $username = $userRecord['firstname'] . ' ' . $userRecord['lastname'];
			if(trim($username) == ''){
				echo "Can't find a username for user id $uid\n";
				continue;
			}
			$username = mysql_real_escape_string($username);
			$password = mysql_real_escape_string($userRecord['password']);
			$email = mysql_real_escape_string($userRecord['email']);
			$pendingemail = "";

			// find out if they're a superuser
			if($userRecord['super'] == 'yes'){
				$superuser = 'yes';
			}else{
				$superuser = 'no';
			}

			// get the year
			$year = $userRecord['year'];


			// check to see if we already have a record with this username in place
			$checkCount = mysql_fetch_assoc(mysql_query("SELECT count(*) as tally FROM accounts WHERE username='$username'"));
			if($checkCount['tally'] > 0){
				// there is already an account with this username let's find out if it's a newer
				// or older copy
				$data = mysql_fetch_assoc(mysql_query("SELECT * FROM accounts WHERE username='$username'"));
				$accounts_id = $data['id'];
				if($data['year'] < $year){
					echo "switching to newer data for username \"$username\".\n";
					// this is a later record, so let's replace the old one
					$updateQuery = "UPDATE accounts SET " .
							"`password` = '$password', " .
							"`email` = '$email', " .
							"`superuser` = '$superuser', " .
							"`year` = $year " .
							"WHERE username = '$username'";
					//echo $query . "\n";
					if(!mysql_query($updateQuery)){
						throw new Exception("Error on query \"$updateQuery\":\n\n" . mysql_error());
					}

				}

			}else{
				echo "Creating a new record for uid $uid ($username)\n";
				$accounts_id = $uid;

				$newAccountQuery = "INSERT INTO accounts (`id`, `username`, `password`, `email`, `pendingemail`, `superuser`, `year`) ";
				$newAccountQuery .= "VALUES ('$accounts_id', '$username', '$password', '$email', '$pendingemail', '$superuser', $year)";
				//echo $newAccountQuery . "\n";
				if(!mysql_query($newAccountQuery)){
//					$accounts_id = mysql_insert_id();
//				}else{
					throw new Exception("Error on query \"$newAccountQuery\":\n\n" . mysql_error());
				}
			}
			if($accounts_id > $max_id) $max_id = $accounts_id;

			/**************************************************
				Now that we have an account created,
				let's deal with the other tables.
			**************************************************/
			do{
				// let's set the uid in this record to be the new ID in our accounts table
				$query = "UPDATE users SET uid = $accounts_id WHERE id=" . $userRecord['id'];
				//echo $query . "\n";
				if(!mysql_query($query)){
					throw new Exception("Failed on updating users table for userid {$userRecord['id']}");
				}

				if($userRecord['year'] != 0){
					$confQuery = mysql_query("SELECT * FROM conferences WHERE year = " . $userRecord['year']);
					if($confQuery != false){
						$confDat = mysql_fetch_assoc($confQuery);
						$confId = $confDat['id'];

						// update the user_roles table
						$roles = explode(',', $userRecord['types']);
						$q = "SELECT * FROM roles WHERE roletype IN ('" . implode("','", $roles) . "')";
						$roleQuery = mysql_query($q);
						while($roleData = mysql_fetch_assoc($roleQuery)){
							$roleId = $roleData['id'];
							$tally = 0;
							$roletype = $roleData['roletype'];

							$roleInfoQuery = mysql_query("SELECT * FROM users_" . $roletype . " WHERE users_id = " . $userRecord['id']);
							$roleInfo = mysql_fetch_assoc($roleInfoQuery);
							// we now have their role info

							$active = $roleInfo[$roletype . '_active'];
							$complete = $roleInfo[$roletype . '_complete'];
							// build our insert on the user_roles table
							$params = array(
								'conferences_id' => $confId,
								'active' => $active,
								'complete' => $complete,
								'roles_id' => $roleId,
								'users_id' => $userRecord['id'],
								'accounts_id' => $accounts_id
							);
							$query = "INSERT INTO user_roles";
							$query .= ' (' . implode(', ', array_keys($params)) . ')';
							$query .= ' VALUES ("' . implode('", "', array_values($params)) . '")';
							//echo $query . "\n";
							mysql_query($query);

							// now we need to take all of their role data and insert it into users:
							if(array_key_exists($roletype, $fields)){
								$query = "UPDATE users SET";
								$doneOne = false;
								foreach($fields[$roletype] as $fieldName){
									if($doneOne) $query .= ", ";
									else $doneOne = true;
									$query .= " `$fieldName` = '";
									$query .= mysql_real_escape_string($roleInfo[$fieldName]);
									$query .= "'";
								}
								$query .= " WHERE id = " . $userRecord['id'];
								//echo $query . "\n";
								if(!mysql_query($query)){
									throw new exception("ERROR with query:\n$query\n");
								}
							}
						}

					}else{
						echo "No conference found with the year \"" . $userRecord['year'] . "\"\n";
					}

				}else{
					echo "No conference year specified for user '$username'\n";
				}

				
			}while($userRecord = mysql_fetch_assoc($userResults));
			
		}

		// now that the account records have all been created, we can delete any user records that have a year of zero
		mysql_query("DELETE FROM users WHERE year = 0");
		mysql_query("ALTER TABLE accounts AUTO_INCREMENT = " . ($max_id + 1));

		mysql_query("COMMIT");
	}catch(Exception $e){
		mysql_query("ROLLBACK");
		echo $e->getMessage();
	}
}