/*

To use this, create a new resource (doesn't matter where) with Hide from Menus and Published both checked.
Also, toggle the wysiwyg editor and go to the settings tab, turn OFF Searchable, Cacheable, and Rich Text,
and set the Content Type to text.

Place this in the content box (replacing the placeholders with actual credentials):

[[!importWPUsers?
	&hostname=`localhost`
	&username=`WORDPRESS_USERNAME`
	&password=`WORDPRESS_PASSWORD`
	&database=`WORDPRESS_DATABASE`
]]

Save the resource, then click "View" and it should take you to the resource where this script will do it's thing.
After you visit the page (do NOT hit refresh), you should probably unpublish the resource or delete it, although
I'm pretty sure if you try to visit the page again all the imports will fail due to duplicate email addresses.

*/

function array_set(&$arr, $path, $value, $separator = '.') {
	if ( ! is_array($arr)) {
		return NULL;
	}
	if ( ! is_string($separator)) {
		$separator = '.';
	}
	
	$path = preg_split('/(?<!\\\\)' . preg_quote($separator) .'/', is_string($path) ? $path : ((string) $path) );
	
	$item =& $arr;
	while ( ($key = array_shift($path)) !== NULL) {
		if ( ! array_key_exists($key, $item) || ! is_array($item[$key])) {
			$item[$key] = array();
		}
		
		$item =& $item[$key];
	}
	
	$item = $value;
	
	return $arr;
}

function array_expand($arr) {
	$array = array();

	foreach ($arr as $path => $value) {
		array_set($array, $path, $value);
	}

	return $array;
}

function array_assoc($arr, $key = NULL, $val = NULL) {
	$assoc = array();
	
	if((is_string($val) && $val != '') || (is_int($val) && $val >= 0)) {
		foreach($arr as $i=>$item) {
			$k = (is_string($key) || is_int($key)) && isset($item[$key]) ? $item[$key] : $i;
			$v = isset($item[$val]) ? $item[$val] : NULL;
			
			$assoc[$k] = $v;
		}
	}
	else if(is_array($val) && count($val) > 0) {
		foreach($val as $ofield=>$nfield) {
			if(is_int($ofield)) {
				$val[$nfield] = $nfield;
				unset($val[$ofield]);
			}
		}
		foreach($arr as $i=>$item) {
			$k = (is_string($key) || is_int($key)) && isset($item[$key]) ? $item[$key] : $i;
			$v = array();
			
			foreach($val as $ofield=>$nfield) {
				$v[$nfield] = isset($item[$ofield]) ? $item[$ofield] : NULL; // Change to if statement to not "fill" values that weren't there originally
			}
			
			$assoc[$k] = $v;
		}
	}
	else {
		foreach($arr as $i=>$item) {
			$k = (is_string($key) || is_int($key)) && isset($item[$key]) ? $item[$key] : $i;
			$v = $item;
			
			$assoc[$k] = $v;
		}
	}
	
	return $key === FALSE ? array_values($assoc) : $assoc;
}

function array_subset($arr, $sub) {
	return array_assoc($arr, NULL, $sub);
}

function array_group_assoc($arr, $gkey, $key = NULL, $val = NULL) {
	$grouped = array();
	
	foreach($arr as $k=>$v) {
		if(isset($v[$gkey]) && (is_numeric($v[$gkey]) || is_string($v[$gkey]))) {
			$grouped[$v[$gkey]][$k] = $v;
		}
	}
	
	// array_assoc is called after grouping so that if the group key is "erased" via the $val arg, grouping still works
	if($key === FALSE || is_string($key) || is_string($val) || is_array($val)) {
		foreach($grouped as $k=>$group) {
			$grouped[$k] = array_assoc($group, $key, $val);
		}
	}
	
	return $grouped;
}

function getWPUsers($config) {
	$db = new PDO('mysql:host=' . $config['hostname'] . ';dbname=' . $config['database'], $config['username'], $config['password']);

	if ( ! $db) {

	}

	$users =
	"SELECT
		`ID` AS `profile.extended.wp_id`,
		`user_login` AS `user.username`,
		`user_email` AS `profile.email`,
		`user_url` AS `profile.website`

	FROM `wp_users`
	WHERE `ID` != 1
	ORDER BY `ID` ASC;";
	$users = $db->prepare($users);
	$users->execute();
	$users = $users->fetchAll(PDO::FETCH_ASSOC);

	$users = array_assoc($users, 'profile.extended.wp_id');


	$usermeta = 
	"SELECT
		`user_id`,
		`meta_key`,
		`meta_value`
	FROM `wp_usermeta`
	WHERE `user_id` != 1
	ORDER BY `user_id` ASC;";
	$usermeta = $db->prepare($usermeta);
	$usermeta->execute();
	$usermeta = $usermeta->fetchAll(PDO::FETCH_ASSOC);

	$usermeta = array_group_assoc($usermeta, 'user_id', 'meta_key', 'meta_value');
	$usermeta = array_subset($usermeta, array(
		'sb_we_plaintext_pass' => 'user.password',

		'first_name' => 'profile.extended.first_name',
		'last_name' => 'profile.extended.last_name',
		
		'entry_id' => 'profile.extended.entry_id',

		'Telephone 1' => 'profile.phone',

		'Address' => 'profile.extended.address_street',
		'City' => 'profile.extended.address_city',
		'Province' => 'profile.extended.address_province',
		'Postal Code' => 'profile.extended.address_postalcode',

		'investor' => 'profile.extended.accredited_investor',
		'Canadian Resident' => 'profile.extended.canadian_resident',
		'How did you heard about Luxus?' => 'profile.extended.referral_source',
	));


	foreach ($usermeta as $wp_id => $metas) {
		$user = array_merge($users[$wp_id], $metas);
		$user = array_expand($user);

		$user['class_key'] = 'modUser';

		$user['profile']['extended']['first_name'] = html_entity_decode($user['profile']['extended']['first_name']);
		$user['profile']['extended']['last_name'] = html_entity_decode($user['profile']['extended']['last_name']);
		$user['profile']['fullname'] = trim(implode(' ', array_intersect_key($user['profile']['extended'], array_flip(array('first_name', 'last_name')))));
		$user['profile']['address'] = $user['profile']['extended']['address_street'];
		$user['profile']['city'] = $user['profile']['extended']['address_city'];
		$user['profile']['state'] = $user['profile']['extended']['address_province'];
		$user['profile']['zip'] = $user['profile']['extended']['address_postalcode'];

		$users[$wp_id] = $user;
	}

	return $users;
}

function importWPUsers(&$modx, $users) {
	$results = array();
	$group = $modx->getObject('modUserGroup', array('name' => 'LVPGuestPass'));
	$role = $modx->getObject('modUserGroupRole', array('name' => 'Member'));

	foreach ($users as $fields) {
		$user = $modx->newObject('modUser');
		$profile = $modx->newObject('modUserProfile');

		$user->fromArray($fields['user']);
		$user->set('username', $fields['user']['username']);
		$user->set('active', 1);
		$user->set('password', $fields['user']['password']);

		$profile->fromArray($fields['profile']);
		$profile->set('email', $fields['profile']['email']);
		$profile->set('extended', $fields['profile']['extended']);
		$user->addOne($profile, 'Profile');

		$member = $modx->newObject('modUserGroupMember');
		$member->set('member', 0);
		$member->set('user_group', $group->get('id'));
		$member->set('role', $role->get('id'));
		$user->addMany($member, 'UserGroupMembers');

		if ( ! $user->save()) {
			$modx->log(modX::LOG_LEVEL_ERROR, '[importWPUsers] Could not import WP user: ' . $user->get('id') . ' with username: ' . $user->get('username'));
			$results[] = 'ERROR: ' . $user->get('username');
		}
		else {
			$modx->log(modX::LOG_LEVEL_INFO, '[importWPUsers] Successfully imported WP user: ' . $user->get('id') . ' with username: ' . $user->get('username'));
			$results[] = 'SUCCESS: ' . $user->get('username');
		}

		unset($user, $profile);
	}

	unset($group, $role);

	return $results;
}

$users = getWPUsers($scriptProperties);

if ($users === FALSE) {
	$modx->log(modX::LOG_LEVEL_ERROR, '[importWPUsers] Could not load WP users.');
	return 'ERROR';
}

return implode("\n", importWPUsers($modx, $users));