<?
require_once('db.update.129.user.inc.php');

function db_update_129_pre()
{
	/* Load all external award sources */
	$source_map = array();
	$q = $pdo->prepare("SELECT * FROM award_sources");
	$q->execute();
	while($r = m$q->fetch(PDO::FETCH_ASSOC) {

		/* Make a user, use the password generator to get 
		 * a random username */
		$u = db129_user_create('fair', db129_user_generate_password());

		/* Add a Fair Entry */
		$name = $r['name'];
		$url = $r['url'];
		$website = $r['website'];
		$username = $r['username'];
		$password = $r['password'];
		$en = ($r['enabled'] == 'no') ? 'no' : 'yes';

		$stmt = $pdo->prepare("INSERT INTO fairs (`id`,`name`,`abbrv`,`type`,
		`url`,`website`,`username`,`password`,`enable_stats`,
		`enable_awards`,`enable_winners`) VALUES (
			'', '$name', '', 'ysf', '$url', '$web',
			'$username','$password','no','$en','$en')");
		$stmt->execute();

		/* Link the fair to the user */
		$u['fairs_id'] = $pdo->lastInsertId();

		/* Record the old sources_id to new sources_id mapping */
		$source_map[$r['id']] = $u['fairs_id'];

		db129_user_save($u);
	}

	/* Map all awards to their new source IDs */
	$q = $pdo->prepare("SELECT * FROM award_awards");
	$q->execute();
	$keys = array_keys($source_map);
	while($r = m$q->fetch(PDO::FETCH_ASSOC)) {
		$old_id = $r['award_sources_id'];
		if(!in_array($old_id, $keys)) continue;

		$qq = $pdo->prepare("UPDATE award_awards SET award_sources_id='{$source_map[$old_id]}'
					WHERE id='{$r['id']}'");
		$qq->execute();
	}

	
}

?>
