<?
function db_update_116_post()
{
	global $config;

	/* Fix the users that have a 0 year */
	$q = $pdo->prepare("UPDATE `users` SET year={$config['FAIRYEAR']} WHERE year=0");
	$q->execute();
	echo $pdo->errorInfo();

	/* Fix users without a username */
	$stmt = $pdo->prepare("UPDATE `users` SET `username`=`email` WHERE `username`=''");
	$stmt->execute();

	/*randomize usernames for any user that doesnt have a username at this point */
	$q=$pdo->prepare("SELECT id FROM `users` WHERE username=''");
	$q->execute();

	//this is ripped from user.inc.php's generate passsword function.
	//yes there's a chance of collisions, but i think highly unlikely enough that we
	//dont need to worry about it.
  	$available="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
   	$len=strlen($available) - 1;
	while($r=$q->fetch(PDO::FETCH_OBJ)) {
		$username="";
	  	for($x=0;$x<16;$x++)
	   		$username.=$available{rand(0,$len)};
		$stmt = $pdo->prepare("UPDATE users SET username='$username' WHERE id='$r->id'");
		$stmt->execute();
	}

	
	//okay now finally, there's a chance of duplicates from 
	//committee/volunteer that were in here before, so we need to merge 
	//them
	$q = $pdo->prepare("SELECT * FROM `users` WHERE types LIKE '%committee%'");
	$q->execute();
	while($r = $q->fetch(PDO::FETCH_ASSOC)) {
		$orig_r = $r;
		$qq = $pdo->prepare("SELECT * FROM `users` WHERE
					(`username`='{$r['username']}' OR `email`='{$r['email']}')
					AND `id`!={$r['id']}");
		$qq->execute();
		if($qq->rowCount() == 0) continue;

		echo "User id {$r['id']} ({$r['username']} {$r['email']}) has multiple users, merging...\n";

		/* Now, there should only be two types, because the system is 
		 * only supposed to let committee members and volunteers be
		 * created, and it has only been in use for one year without 
		 * year stamps., but we'll handle any number */

		/* However, we will make the committee the record that sticks 
		 * */
		$delete_ids = array();
		$delete_userids = array();
		while($rr = $qq->fetch(PDO::FETCH_ASSOC)) {
			$delete_ids[] = "`id`={$rr['id']}";
			$delete_userids[] = "`users_id`={$rr['id']}";
			$keys = array_keys($rr);
			foreach($keys as $k) {
				switch($k) {
				case 'id':
					/* Skip */
					break;
				case 'types':
					/* Merge types */
					if(strstr($r['types'], $rr['types']) == false) {
						$r['types']= $r['types'].','.$rr['types'];
						echo "   New type: {$r['types']}\n";
					}
					break;
				default:
					/* Save data */
					if(trim($r[$k]) == '' && trim($rr[$k]) != '') {
						$r[$k] = $rr[$k];
					}
					break;
				}
			}
		}



		/* Construct SQL for a SET clause */
		$set = array();
		$keys = array_keys($r);
		foreach($keys as $k) {
			if($r[$k] != $orig_r[$k]) {
				$set[] = "`$k`='{$r[$k]}'";
			}
		}
		if(count($set)) {
			$query = join(',',$set);
			$stmt = $pdo->prepare("UPDATE `users` SET $query WHERE id={$r['id']}");
			$stmt->execute();
			echo "Update query: UPDATE `users` SET $query WHERE id={$r['id']}\n";
		}

		/* Join together the WHERE commands */
		$where_id = "WHERE ".join(" OR ", $delete_ids);
		$where_users_id = "WHERE ".join(" OR ", $delete_userids);

		echo "Merged... Deleting duplicate and adjusting volunteer tables...\n";
		/* Delete the dupe */
		$stmt = $pdo->prepare("DELETE FROM `users` $where_id");
		$stmt->execute();
		/* Update volunteer linkage */
		$stmt = $pdo->prepare("UPDATE `users_volunteer` SET `users_id`={$r['id']} $where_users_id");
		$stmt->execute();
		$stmt = $pdo->prepare("UPDATE `volunteer_positions_signup` SET `users_id`={$r['id']} $where_users_id");
$stmt->execute();

		echo "done with this user.\n";

	}
	
	/* Create volunteer database entries for any that don't exist */
	$q = $pdo->prepare("SELECT * FROM users WHERE types LIKE '%volunteer%'");
	$q->execute();
	while($i = $q->fetch(PDO::FETCH_OBJ)) {
		$stmt = $pdo->prepare("INSERT INTO users_volunteer(`users_id`,`volunteer_active`,`volunteer_complete`)
				VALUES ('{$i->id}','yes','{$i->complete}')");
	
		$stmt->execute();}

	/* Update any remaining volunteer entries  */
	$q = $pdo->prepare("SELECT * FROM users WHERE types LIKE '%volunteer%'");
	$q->execute();
	while($i = $q->fetch(PDO::FETCH_OBJ)) {
		$stmt = $pdo->prepare("UPDATE users_volunteer 
				SET volunteer_complete='{$i->complete}' 
				WHERE users_id='{$i->id}'");
		$stmt->execute();
		echo $pdo->errorInfo();
	}

	/* Every committee member role should be activated */
	$q = $pdo->prepare("SELECT * FROM users WHERE types LIKE '%committee%'");
	$q->execute();
	while($i = $q->fetch(PDO::FETCH_OBJ)) {
		$stmt = $pdo->prepare("UPDATE users_committee
				SET committee_active='yes' 
				WHERE users_id='{$i->id}'");
		$stmt->execute();
		echo $pdo->errorInfo();
	}

	/* Convert Judges */
	$map = array();
	$jtl = array();
	$jsal = array();

	/* Select all judges, duplicate rows for each year */
	$jq = $pdo->prepare("SELECT * FROM judges
				LEFT JOIN judges_years ON judges_years.judges_id=judges.id
				ORDER BY year");
	$jq->execute();

	while($j = $jq->fetch(PDO::FETCH_OBJ)) {

		if(!is_array($map[$j->id])) {
			$map[$j->id] = array('uid' => '');
		}

		$u = array( 'id' => '',
			'uid' => $map[$j->id]['uid'],
			'types' => 'judge',
			'firstname' => $j->firstname,
			'lastname' => $j->lastname,
			'username' => $j->email,
			'email' => $j->email,
			'sex' => '',
			'password' => $j->password,
			'passwordset' => $j->lastlogin, 
			'oldpassword' => '',
			'year' => $j->year,
			'phonehome' => $j->phonehome,
			'phonework' => $j->phonework.($j->phoneworkext=='') ? '' : " x{$j->phoneworkext}",
			'phonecell' => $j->phonecell,
			'fax' => '',
			'organization' => $j->organization,
			'lang' => '',  /* FIXME, or unused for judges?, this is preferred communication language, not judging languages */
			'created' => $j->created,
			'lastlogin' => $j->lastlogin,
			'address' => $j->address,
			'address2' => $j->address2,
			'city' => $j->city,
			'province' => $j->province,
			'postalcode' => $j->postalcode,
			'firstaid' => 'no',
			'cpr' => 'no',
			'deleted' => $j->deleted,
			'deleteddatetime' => $j->deleteddatetime );

		$updateexclude=array("id","uid","types","username","password","passwordset","oldpassword","year","created","lastlogin","firstaid","cpr","deleted","deleteddatetime");

		//check if a user already exists with this username
		$uq=$pdo->prepare("SELECT * FROM users WHERE (username='".$j->email."' OR email='".$j->email."') AND year='$j->year'");
		$uq->execute();
		if($j->email && $ur=$uq->fetch(PDO::FETCH_OBJ) {
			$id=$ur->id;
			 echo "Using existing users.id=$id for judges.id=$j->id because email address/year ($j->email/$j->year) matches\n";

			$sqlset="";
			foreach($u AS $f=>$v) {
				if(!$ur->$f && $j->$f && !in_array($f,$updateexclude)) {
					$sqlset.="`$f`='".$j->$f."', ";
				}
			}
			$sql="UPDATE users SET $sqlset `types`='{$ur->types},judge',`username`='".$j->email."' WHERE id='$id'";
			$stmt = $pdo->prepare($sql);
			$stmt->execute();
			echo $pdo->errorInfo();
			echo "   Updated user record with judge info, but only merged:\n";
			echo "   ($sqlset)\n";

		}
		else
		{
			/* Insert the judge */
			$fields = '`'.join('`,`', array_keys($u)).'`';
			$vals = "'".join("','", array_values($u))."'";
			$q = $pdo->prepare("INSERT INTO users ($fields) VALUES ($vals)");
			$q->execute();
			$id = $pdo->lastInsertId();

			if($map[$j->id]['uid'] == '') {
				$map[$j->id]['uid'] = $id;
				$q = $pdo->prepare("UPDATE users SET `uid`='$id' WHERE id='$id'");
				$q->execute();
			}
		}

		$uj = array( 'users_id' => "$id",
			'judge_active' => 'yes',
			'highest_psd' => $j->highest_psd,
			'special_award_only' => ($j->typepref == 'speconly') ? 'yes' : 'no',
			'expertise_other' => (($j->professional_quals != '')?($j->professional_quals."\n"):'').
						$j->expertise_other,
			/* These need to get pulled from the questions */
			'years_school' => $j->years_school,
			'years_regional' => $j->years_regional,
			'years_national' => $j->years_national,
			'willing_chair' => $j->willing_chair,
			'judge_complete' => $j->complete,
			);
//			$j->attending_lunch,

		/* catprefs */
		$q = $pdo->prepare("SELECT * FROM judges_catpref WHERE judges_id='{$j->id}' AND year='{$j->year}'");
		$q->execute();
		$catpref = array();
		while($i = $q->fetch(PDO::FETCH_OBJ)) {
			$catpref[$i->projectcategories_id] = $i->rank;
		}
		$uj['cat_prefs'] = serialize($catpref);

		/* divprefs and subdivision prefs */
		$q = $pdo->prepare("SELECT * FROM judges_expertise WHERE judges_id='{$j->id}' AND year='{$j->year}'");
		$q->execute();
		$divpref = array();
		$divsubpref = array();
		while($i = $q->fetch(PDO::FETCH_OBJ)) {
			if($i->projectdivisions_id) 
				$divpref[$i->projectdivisions_id] = $i->val;
			else if ($i->projectsubdivisions_id) 
				$divsubpref[$i->projectsubdivisions_id] = $i->val;
		}
		$uj['div_prefs'] = serialize($divpref);
		$uj['divsub_prefs'] = serialize($divsubpref);

		/* languages */
		$q = $pdo->prepare("SELECT * FROM judges_languages WHERE judges_id='{$j->id}'");
		$q->execute();
		$langs = array();
		while($i = $q->fetch(PDO::FETCH_OBJ)) {
			$langs[] = $i->languages_lang;
		}
		$uj['languages'] = serialize($langs);

		/* Map judges questions back to the profile.  We're going to keep questions we need for
		 * judge scheduling as hard-coded questions so users can't erase them. 
		 * "Years School" "Years Regional" "Years National" "Willing Chair" */
		$qmap = array('years_school' => 'Years School',
				'years_regional' => 'Years Regional',
				'years_national' => 'Years National',
				'willing_chair' => 'Willing Chair');
		foreach($qmap as $field=>$head) {
			/* Find the question ID */
			$q = $pdo->prepare("SELECT id FROM questions WHERE year='{$j->year}' AND db_heading='{$head}'");
			$q->execute();
			if($q->rowCount() == 0) {
				echo "Warning: Question '$head' for judge {$j->id} doesn't exist in year '{$j->year}', cannot copy answer.\n";
				continue;
			}

			$i = $q->fetch(PDO::FETCH_OBJ);

			/* Now find the answer */
			$q = $pdo->prepare("SELECT * FROM question_answers WHERE 
					year='{$j->year}' AND 
					registrations_id='{$j->id}' AND
					questions_id='{$i->id}'");
			$q->execute();
			echo $pdo->errorInfo();
			if($q->rowCount() == 0) {
				echo "Warning: Judge {$j->id} did not answer question '$head' in year '{$j->year}', cannot copy answer.\n";
				continue;
			}
			$i = $q->fetch(PDO::FETCH_ASSOC)
			$uj[$field] = $i['answer'];
		}

//		print_r($uj);

		$fields = '`'.join('`,`', array_keys($uj)).'`';
		$vals = "'".join("','", array_values($uj))."'";
		$q = $pdo->prepare("INSERT INTO users_judge ($fields) VALUES ($vals)");
		$q->execute();
		echo $pdo->errorInfo();

		/* FIXUP all the judging tables (but don't write back yet, we don't want to 
		 * accidentally create a duplicate judges_id and overwrite it later) */

		/* judges_teams_link */
		$q = $pdo->prepare("SELECT * FROM judges_teams_link WHERE judges_id='{$j->id}' AND year='{$j->year}'");

$q->execute();
		while($i = $q->fetch(PDO::FETCH_OBJ))
			$jtl[$i->id] = $id;

		/* judges_specialawards_sel */
		$q = $pdo->prepare("SELECT * FROM judges_specialaward_sel WHERE judges_id='{$j->id}' AND year='{$j->year}'");

$q->execute();
		echo $pdo->errorInfo();
		while($i = $q->fetch(PDO::FETCH_OBJ)) 
			$jsal[$i->id] = $id;

		/* question_answers */
		$q = $pdo->prepare("SELECT * FROM question_answers WHERE registrations_id='{$j->id}' AND year='{$j->year}'");

$q->execute();
		echo $pdo->errorInfo();
		while($i = $q->fetch(PDO::FETCH_OBJ)) 
			$qa[$i->id] = $id;
	}

	/* Now write back the judge ids */
	if(count($jtl)) {
	foreach($jtl as $id=>$new_id) 
		$q = $pdo->prepare("UPDATE judges_teams_link SET judges_id='$new_id' WHERE id='$id' ");

$q->execute();
	}
	if(count($jsal)) {
	foreach($jsal as $id=>$new_id) 
		$q = $pdo->prepare("UPDATE judges_specialaward_sel SET judges_id='$new_id' WHERE id='$id' ");

$q->execute();
	}
	if(count($qa)) {
	foreach($qa as $id=>$new_id)
		$q = $pdo->prepare("UPDATE question_answers SET registrations_id='$new_id' WHERE id='$id' ");

$q->execute();
	}
}
?>
