<?
function db_update_116_post()
{
	global $config, $pdo;

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

	/* 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=? WHERE id=?");
		$stmt->execute([$username,$r->id]);
	}

	// 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`=? OR `email`=?)
					AND `id`!=?");
		$qq->execute([$r['username'],$r['email'],$r['id']]);
		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 ? WHERE id=?");
			$stmt->execute([$query,$r['id']]);
			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` ?");
		$stmt->execute([$where_id]);
		/* Update volunteer linkage */
		$stmt = $pdo->prepare("UPDATE `users_volunteer` SET `users_id`=? ?");
		$stmt->execute([$r['id'],$where_users_id]);
		$stmt = $pdo->prepare("UPDATE `volunteer_positions_signup` SET `users_id`=? ?");
		$stmt->execute([$r['id'],$where_users_id]);

		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 (?,'yes',?)");

		$stmt->execute([$i->id,$i->complete]);
	}

	/* 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=? 
				WHERE users_id=?");
		$stmt->execute([$i->complete,$i->id]);
		show_pdo_errors_if_any($pdo);
	}

	/* 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=?");
		$stmt->execute([$i->id]);
		show_pdo_errors_if_any($pdo);
	}

	/* 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? OR email=?) AND year=?");
		$uq->execute([$j->email,$j->email,$j->year]);
		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 ? `types`=?,judge',`username`=? WHERE id=?";
			$stmt = $pdo->prepare($sql);
			$stmt->execute([$sqlset,$ur->types,$j->email,$id]);
			show_pdo_errors_if_any($pdo);
			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 (?) VALUES (?)");
			$q->execute([$fields,$vals]);
			$id = $pdo->lastInsertId();

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

		$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=? AND year=?");
		$q->execute([$j->id,$j->year]);
		$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=? AND year=?");
		$q->execute([$j->id,$j->year]);
		$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=?");
		$q->execute([$j->id]);
		$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=? AND db_heading=?");
			$q->execute([$j->year,$head]);
			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=? AND 
					registrations_id=? AND
					questions_id=?");
			$q->execute([$j->year,$j->id,$i->id]);
			show_pdo_errors_if_any($pdo);
			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 (?) VALUES (?)");
		$q->execute([$fields,$vals]);
		show_pdo_errors_if_any($pdo);

		/*
		 * 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=? AND year=?");

		$q->execute([$j->id,$j->year]);
		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=? AND year=?");

		$q->execute([$j->id,$j->year]);
		show_pdo_errors_if_any($pdo);
		while ($i = $q->fetch(PDO::FETCH_OBJ))
			$jsal[$i->id] = $id;

		/* question_answers */
		$q = $pdo->prepare("SELECT * FROM question_answers WHERE registrations_id=? AND year=?");

		$q->execute([$j->id,$j->year]);
		show_pdo_errors_if_any($pdo);
		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=? WHERE id=? ");

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

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

		$q->execute([$new_id,$id]);
	}
}
?>