<?php
/**
 * DateBook Migrate
 * Transfer profiles from other themes using BuddyPress
 *
 * @class DateBook_Migrate
 * @author Pagick Themes
 * @since 4.4
 */

class DateBook_Migrate {


	/**
	 * Hook actions and filters.
	 * 
	 * @since 4.4
	 * @access public
	 */
	public static function init() {

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'datebook_install_script' ) );

		add_action( 'wp_ajax_datebookprofilesinserted', array( __CLASS__, 'datebook_ajax_profiles_inserted' ) );

		add_action( 'wp_ajax_datebookmigrateprofiles', array( __CLASS__, 'migrate_profiles_datebook_to_buddypress' ) );

	}


	/**
	 * Insert inline CSS style for Install and Notify Box
	 *
	 * @access public
	 */
	public static function datebook_install_script() {

		wp_enqueue_script( 'jquery-ui-progressbar', OPTIONS_FRAMEWORK_DIRECTORY . 'js/jquery.ui.progressbar.min.js', array( 'jquery-ui-core', 'jquery-ui-widget' ), '1.12.1' );

	}


	/**
	 * Helper function to escape quotes in strings for use in Javascript
	 *
	 * @access private
	 */
	private static function datebook_esc_quotes( $string ) {

		return esc_attr(str_replace( '"', '\"', $string ));

	}


	/**
	 * Simple function that validates data and retrieve bool on success
	 * and error message(s) on error
	 *
	 * @param $item
	 * @return bool|string
	 */
	static function datebook_validate($item) {

		$data = array();
		$messages = array();

		if(is_array($item)) {
			
			$data['form_fields'] = $item;

			if (is_array($data)) {

				$data['success'] = true;
				
			} else {

				$data['success'] = false;
				$data['error_message'] = esc_html__( 'Oops! Something went wrong.', 'datebook' );

			}

		} else {

			$data['success'] = false;
			$data['error_message'] = esc_html__( 'Oops! Something went wrong.', 'datebook' );

		}

		return $data;

	}


	/**
	 * The user interface
	 *
	 * @access public
	 */
	public static function datebook_interface() {

		global $wpdb, $allowedposttags;

		$table_users = strtolower($wpdb->prefix) . 'users';
		$table_bp_xprofile_fields = strtolower($wpdb->prefix) . 'bp_xprofile_fields';
		
		?>

		<div id="message" class="updated fade" style="display:none"></div>
		
		<div class="wrap">

			<h1><?php echo esc_html__('Migrate Tool', 'datebook'); ?></h1>
			
			<p><?php echo esc_html__('You can migrate all profiles from BuddyPress to DateBook', 'datebook'); ?>.</p>
			<p><?php echo esc_html__('Attention: BuddyPress and rtMedia plugins must be installed and activated', 'datebook'); ?>.</p>
			
			<hr class="wp-header-end">

			<?php

			if (!empty($_POST['datebook_start_again'])) {

				delete_option('datebook_migrated_users');

				echo '<div id="message" class="updated">';
				echo '<p>' . esc_html__( "Cleaned! You can start migrating all users again.", 'datebook' ) . '</p>';
				echo '</div>';

			}

			?>

            <div class="welcome-panel datebook-dummy-notify-box">
				<div class="welcome-panel-content">

					<h2><?php echo esc_html__('Start migrating', 'datebook'); ?></h2>

					<p><?php echo esc_html__('Press the START button to migrate all profiles from BuddyPress to DateBook', 'datebook'); ?>.</p>
					<p><?php echo esc_html__('Do not worry if the process is interrupted. You can continue again. Just reload this page and click on the START button', 'datebook'); ?>.</p>
					<p><?php echo esc_html__('The migrate process may take long depending on the quantity of users. Thus, you may stop and continue at any time.', 'datebook'); ?>.</p>
					
					<?php

					// If the button was clicked
					if ( ! empty( $_POST['datebook_migrate_start'] ) || ! empty( $_REQUEST['ids'] ) ) {

						// Form nonce check
						check_admin_referer( 'datebook_migrate_start' );
						
						$ids_array = array();

						// Create the list of country IDs
						if ( !empty( $_REQUEST['ids'] ) ) {

							$user_datas = $ids_array = array_map( 'intval', explode( ',', trim( $_REQUEST['ids'], ',' ) ) );
							$ids = implode( ',', $user_datas );

						} else {

							$check_buddypress_table = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_bp_xprofile_fields));

							if ( $check_buddypress_table != $table_bp_xprofile_fields ) {

								echo '<div id="notice" class="datebook-error" style="margin: 5px 0 15px;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #fb0707">';

								echo '<p>' . esc_html__( "BuddyPress is not installed yet.", 'datebook' ) . '</p>';

								echo '</div>';

								return;

							} else if ( ! $user_datas = $wpdb->get_results($wpdb->prepare("SELECT ID FROM $table_users WHERE ID > %d ORDER BY id ASC", 1 ) ) ) {

								// Directly querying the database is normally frowned upon, but all
								// of the API functions will return the full post objects which will
								// suck up lots of memory. This is best, just not as future proof.

								echo '<div id="message" class="updated error">';

								echo '<p>' . esc_html__( "No users have been found in the database", 'datebook' ) . '</p>';

								echo '</div>';

								echo '</div>';

								return;

							}
							
							// Generate the list of IDs
							$pre_ids_array = $pre_ids_array = array();
							foreach($user_datas as $key => $country_data){
								$pre_ids_array[] = $country_data->ID;
							}

							// Select users to be migrated
							$datebook_migrated_users = get_option('datebook_migrated_users');
							if(empty($datebook_migrated_users)){
								update_option('datebook_migrated_users', $pre_ids_array);
								$datebook_migrated_users = $pre_ids_array;
							}

							// Add a user to the migrated users list
							foreach($pre_ids_array as $key => $value){
								if (($findID = array_search($value, $datebook_migrated_users)) !== false) {
									$ids_array[] = $value;
								}
							}

							$ids = isset($ids_array) && is_array($ids_array) && !empty($ids_array) ? implode( ',', $ids_array ) : 0;

						}


						$message_failures = sprintf(esc_html__( 'Almost success! %1$s profiles have been successfully migrated. But %2$s profiles are not migrated.', 'datebook' ),
						'" + datebooktool_successes + "', 
						'" + datebooktool_errors + "' 
						);

						$message_success = sprintf( esc_html__( 'All %1$s profiles have been successfully migrated.', 'datebook' ), '" + datebooktool_successes + "' );

						$count = count($ids_array);

					?>

					<noscript>
						<p><?php echo esc_html__( 'You must enable Javascript in order to proceed!', 'datebook' ) ?></p>
					</noscript>

					<div id="datebook-bar" style="position:relative;height:25px;">
						<div id="datebook-bar-percent" style="position:absolute;left:50%;top:30%;width:300px;margin-left:-150px;height:25px;margin-top:-9px;text-align:center;"></div>
					</div>

					<p><input type="button" class="button hide-if-no-js" name="datebook-stop" id="datebook-stop" value="<?php echo esc_html__( 'Stop', 'datebook' ) ?>" /></p>

					<table class="datebook-countries-statistics" width="100%" cellpadding="20" cellspacing="4">
						<tr>
							<td><?php echo esc_html__( 'All profiles:', 'datebook' ); ?> <span style="width:100%;padding: 2%;font-size: 24px"> <?php printf( '%s', $count ); ?> </span></td>
							<td><?php echo esc_html__( 'Profiles migrated:', 'datebook' ); ?> <span style="width:100%;padding: 2%;font-size: 24px"> <?php printf( '%s', '<span id="datebook-debug-successcount">0</span>' ); ?> </span></td>
							<td><?php echo esc_html__( 'Migrate failures:', 'datebook' ); ?> <span style="width:100%;padding: 2%;font-size: 24px"> <?php printf( '%s', '<span id="datebook-debug-failurecount">0</span>' ); ?> </span></td>
						</tr>
					</table>

					<ol id="datebook-debuglist">
						<li style="display:none"></li>
					</ol>

					<?php
						
						wp_add_inline_script( 'jquery-ui-progressbar', '

						// <![CDATA[
						jQuery(document).ready(function($){
							var i;
							var datebooktool_countries = [' . esc_js($ids) . '];
							var datebooktool_total = datebooktool_countries.length;
							var datebooktool_count = 1;
							var datebooktool_percent = 0;
							var datebooktool_successes = 0;
							var datebooktool_errors = 0;
							var datebooktool_failedlist = "";
							var datebooktool_resulttext = "";
							var datebooktool_timestart = new Date().getTime();
							var datebooktool_timeend = 0;
							var datebooktool_totaltime = 0;
							var datebooktool_continue = true;

							// Create the progress bar
							$("#datebook-bar").progressbar();
							$("#datebook-bar-percent").html( "0%" );

							// Stop button
							$(document).on("click", "#datebook-stop", function() {
								datebooktool_continue = false;
								$("#datebook-stop").val("' . self::datebook_esc_quotes( esc_html__( "Stopping...", "datebook" ) ) . '");
							});

							// Clear out the empty list element that is there for HTML validation purposes
							$("#datebook-debuglist li").remove();
							
							// Send request that all countries inserted
							function DateBookCountriesInserted() {
								$.ajax({
									type: "POST",
									url: ajaxurl,
									dataType: "json",
									data: { action: "datebookprofilesinserted" },
									success: function( response ) {}
								});
							}


							// Called after each resize. Updates statistics information and the progress bar.
							function DateBookCountriesUpdateStatus( id, success, response ) {
								$("#datebook-bar").progressbar( "value", ( datebooktool_count / datebooktool_total ) * 100 );
								$("#datebook-bar-percent").html( Math.round( ( datebooktool_count / datebooktool_total ) * 1000 ) / 10 + "%" );
								datebooktool_count = datebooktool_count + 1;

								if ( success ) {
									datebooktool_successes = datebooktool_successes + 1;
									$("#datebook-debug-successcount").html(datebooktool_successes);
									$("#datebook-debuglist").append("<li>" + response.success + "</li>");
									DateBookCountriesInserted();
								} else {
									datebooktool_errors = datebooktool_errors + 1;
									datebooktool_failedlist = datebooktool_failedlist + "," + id;
									$("#datebook-debug-failurecount").html(datebooktool_errors);
									$("#datebook-debuglist").append("<li>" + response.error + "</li>");
								}
							}

							// Called when all countries have been processed. Shows the results and cleans up.
							function DateBookCountriesFinishUp() {
								datebooktool_timeend = new Date().getTime();
								datebooktool_totaltime = Math.round( ( datebooktool_timeend - datebooktool_timestart ) / 1000 );

								$("#datebook-stop").hide();

								if ( datebooktool_errors > 0 ) {
									datebooktool_resulttext = "' . wp_kses($message_failures, $allowedposttags) . '";
								} else {
									datebooktool_resulttext = "' . wp_kses($message_success, $allowedposttags) . '";
								}

								$("#message").html("<p>" + datebooktool_resulttext + "</p>");
								$("#message").show();
							}

							// Insert a specified country via AJAX
							function DateBookInstalling( id ) {
								$.ajax({
									type: "POST",
									url: ajaxurl,
									dataType: "json",
									data: { action: "datebookmigrateprofiles", id: id },
									success: function( response ) {
										if ( response !== Object( response ) || ( typeof response.success === "undefined" && typeof response.error === "undefined" ) ) {
											response = new Object;
											response.success = false;
											response.error = "' . sprintf( esc_js( esc_html__( "The migrating request was abnormally terminated (ID %s). This is likely due to the proccess exceeding available memory or some other type of fatal error.", "datebook" ) ), '" + id + "' ) . '";
										}

										if ( response.success ) {
											DateBookCountriesUpdateStatus( id, true, response );
										} else {
											DateBookCountriesUpdateStatus( id, false, response );
										}

										if ( datebooktool_countries.length && datebooktool_continue ) {
											DateBookInstalling( datebooktool_countries.shift() );
										} else {
											DateBookCountriesFinishUp();
										}
									},
									error: function( response ) {
										DateBookCountriesUpdateStatus( id, false, response );

										if ( datebooktool_countries.length && datebooktool_continue ) {
											DateBookInstalling( datebooktool_countries.shift() );
										} else {
											DateBookCountriesFinishUp();
										}
									}
								});
							}

							DateBookInstalling( datebooktool_countries.shift() );

						});
						// ]]>

						');

				} else {

					if(class_exists('BuddyPress')) {

						$check_buddypress_table = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_bp_xprofile_fields));

						if ( $check_buddypress_table != $table_bp_xprofile_fields ) {

							echo '<div id="notice" class="datebook-error" style="margin: 5px 0 15px;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #fb0707">';
							echo '<p>' . esc_html__( "BuddyPress is not installed yet.", 'datebook' ) . '</p>';
							echo '</div>';

						} else {
							
							//Get entire array
							$item = get_option('datebook_migrate');
							$item = isset($item['bp_migrate_options']) ? $item['bp_migrate_options'] : '';
							
							if (!$item) {
								
							?>
							
								<div style="margin: 5px 0 15px;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #fb0707">
									<p><?php echo esc_html__( 'Attention: Fields have not been saved yet', 'datebook' ); ?></p>
								</div>
								
							<?php } else { ?>

								<form method="post" action="">

								<?php wp_nonce_field('datebook_migrate_start') ?>

								<p style="float:left;"><input type="submit" class="button button-primary button-hero hide-if-no-js" name="datebook_migrate_start" value="<?php echo esc_html__( 'Start', 'datebook' ) ?>" /></p>
								
								<p style="float:right; width: 30%"><?php echo esc_html__( 'If you want to migrate all users from the beginning, you must clean the cache first.', 'datebook' ) ?> <input type="submit" class="button hide-if-no-js" name="datebook_start_again" value="<?php echo esc_html__( 'Clean', 'datebook' ) ?>" /></p>

								</form>
								
							<?php
							
							}
						}

					} else { ?>
				
						<div style="margin: 5px 0 15px;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #fb0707">
							<p><?php echo esc_html__( 'BuddyPress is not activated yet', 'datebook' ); ?></p>
						</div>
					
					<?php } ?>

				<?php } ?>

				</div>
			</div>
            


			<?php if (!isset($_POST['datebook_migrate_start'])){ ?>

            <div class="welcome-panel datebook-dummy-notify-box">
				<div class="welcome-panel-content">

					<h2><?php echo esc_html__('BuddyPress Fields', 'datebook'); ?></h2>

					<?php
					
					// If the button was clicked
					$message = '';
					$notice = '';

					// here we are verifying does this request is post back and have correct nonce
					if (isset($_POST['datebook_migrate_options']) && wp_verify_nonce($_POST['nonce'], basename(__FILE__))) {

						// validate data, and if all ok save item to database
						// if id is zero insert otherwise update
						$item_data = self::datebook_validate($_POST);

						if ($item_data['success'] === true) {

							$migrate_options = get_option('datebook_migrate');

							$item = $item_data['form_fields'];
							
							//Update entire array
							$migrate_options['bp_migrate_options'] = $item;

							$result = update_option( 'datebook_migrate', $migrate_options );

							if( $result === FALSE){
								$notice = esc_html__('Oops! Something went wrong. Data has NOT been saved.', 'datebook');
							} else {
								$message = esc_html__('Fields have been saved successfully', 'datebook');
							}

						} else {

							// if $item_data not true it contains error message(s)
							$notice = $item_data['error_message'];

						}
			
					} else {

						// if this is not post back we load item to edit or give new one to create
						$item = array();

						//Get entire array
						$item = get_option('datebook_migrate');
						$item = isset($item['bp_migrate_options']) ? $item['bp_migrate_options'] : '';
						
						if (!$item) {

							$notice = esc_html__('Attention: Fields have not been saved yet', 'datebook');

						}
					
					}

					if (!empty($notice)):

					?>

					<div id="notice" class="datebook-error" style="margin: 15px 0;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #fb0707">
						<p><?php echo esc_attr($notice); ?></p>
					</div>

				<?php

				endif;


				if (!empty($message)):

				?>

					<div id="message" class="datebook-updated" style="margin: 15px 0;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #46b450">
						<p><?php echo esc_attr($message) ?></p>
					</div>

				<?php

				endif;

				
				
					$custom_field_array = array();

					//Get profile form array
					$get_profile_form_fields = get_option('datebook_profile_form');
					$get_profile_form_fields = isset($get_profile_form_fields['profile_form']) ? $get_profile_form_fields['profile_form'] : ($get_profile_form_fields ? $get_profile_form_fields : array());

					if(is_array($get_profile_form_fields)){

						$datebook_alert_error_exists = isset($datebook_alert_error) ? 1 : 0;

						$get_profile_custom_fields = get_option('datebook_profile_custom_fields');

						foreach($get_profile_form_fields as $key => $value){

							if(isset($value['name']) && $value['name'] == 'row') {

								foreach($get_profile_custom_fields as $key => $field){

									if (isset($field['type']) && $field['type'] != 'title') continue;

									if (isset($field['active']) && $field['active'] == 1) {

										if (isset($value['children'][0]['rowTitle']) && $value['children'][0]['rowTitle'] == $key) {

											// if foreign language do not exist, then show title in English (en_US)
											$field['name'] = isset($field['name_' . DATEBOOK_WPLANG]) ? $field['name_' . DATEBOOK_WPLANG] : $field['name_en_US'];

										}
									}
								}

								$align_column_right = '';
								$key = 0;

								foreach ( $value['children'] as $key => $columns ) {

									if(isset($columns['name']) && $columns['name'] == 'column'){

										if(isset($columns['children'])){

											foreach ( $columns['children'] as $key => $column ) {

												if(isset($get_profile_custom_fields[$column['slug']])) {

													$custom_field_data = $get_profile_custom_fields[$column['slug']];

													// if foreign language do not exist, then show title in English (en_US)
													$custom_field_data['name'] = isset($custom_field_data['name_' . DATEBOOK_WPLANG]) ? $custom_field_data['name_' . DATEBOOK_WPLANG] : $custom_field_data['name_en_US'];
												
													$custom_field_array[$column['slug']] = array($custom_field_data['name'], $custom_field_data['type']);

												}
											}
										}
									}
								}
							}
						}
					}


					$databook_profile_fields = array(
						'profile_name' => array(esc_html__( 'Name', 'datebook' ), 'textbox'),
						'aboutme' => array(esc_html__( 'About me', 'datebook' ), 'textarea'),
						'country_id' => array(esc_html__( 'Country', 'datebook' ), 'selectbox'),
						'region_id' => array(esc_html__( 'Region', 'datebook' ), 'selectbox'),
						'city_id' => array(esc_html__( 'City', 'datebook' ), 'selectbox'),
						'birthday' => array(esc_html__( 'Birthday', 'datebook' ), 'textbox'),
						'gender' => array(esc_html__( 'I am (Gender)', 'datebook' ), 'selectbox'),
						'sexualorientation' => array(esc_html__( 'Sexual orientation', 'datebook' ), 'selectbox'),
						'phone' => array(esc_html__( 'Phone', 'datebook' ), 'textbox'),
						'website' => array(esc_html__( 'Website', 'datebook' ), 'textbox')
					);

					$databook_profile_fields_array = $databook_profile_fields + $custom_field_array;

					global $wpdb;
					
					$check_buddypress_table = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_bp_xprofile_fields));

					if ( $check_buddypress_table != $table_bp_xprofile_fields ) {
						
						echo '<div id="notice" class="datebook-error" style="margin: 5px 0 15px;box-shadow: 0 1px 1px rgba(0,0,0,.04); padding: 1px 12px; border: 2px solid #fb0707">';

						echo '<p>' . esc_html__( "BuddyPress table does not exist in MySQL database", 'datebook' ) . ': '. $table_bp_xprofile_fields . '</p>';

						echo '</div>';

					} else {

						$count_fields = 0;

						$results = $wpdb->get_results("SELECT * FROM $table_bp_xprofile_fields WHERE parent_id = 0");

						if($results){

							?>

							<p><?php echo esc_html__('You must select the fields from "From Here" that match the fields "To here"', 'datebook'); ?></p>

							<form method="post" action="">

							<?php wp_nonce_field('datebook_migrate_options'); ?>

							<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>

							<input type="hidden" name="datebook_migrate_options" value="1" />

							<table class="widefat striped" width="100%" cellpadding="20" cellspacing="4">
								<thead>
									<tr>
										<th><?php echo esc_html__( 'From here (BuddyPress fields)', 'datebook' ); ?> </th>
										<th><?php echo esc_html__( 'To here (DateBook fields)', 'datebook' ); ?> </th>
									</tr>
								</thead>

								<tbody>

								<?php

								foreach ($results as $field) {

									$count_fields++;

									$field_id = $field->id;
									$field_title = $field->name;
									$field_type = $field->type;

									echo '<tr>';

									//echo '<td>' . esc_attr($field_title) . '</td>';

									echo '<td>';
								
									$from = 'from';
								
									$selected_field_id = isset($item['datebook_bp_field'][$from][$field_id]) && $item['datebook_bp_field'][$from][$field_id] >= 0 ? $item['datebook_bp_field'][$from][$field_id] : $field_id;

									echo '<input type="hidden" name="datebook_bp_field[' . $from . '][' . esc_attr($field_id) . ']" value="' . esc_attr($field_id) . '" />';
									echo '<strong>' . esc_attr($field_title) . '</strong> (' . esc_attr($field_type) . ')';
								
									/*echo '<select name="datebook_bp_field_from_' . esc_attr($field_id) . '">';

									echo '<option value="0">' . esc_html__( 'Select', 'datebook' ) . '</option>';

									foreach ($results as $subfield) {

										$sub_id = $subfield->id;
										$sub_title = $subfield->name;
										$sub_type = $subfield->type;

										$selected_field_id = isset($item['datebook_bp_field_from_' . esc_attr($field_id)]) && $item['datebook_bp_field_from_' . esc_attr($field_id)] >= 0 ? $item['datebook_bp_field_from_' . esc_attr($field_id)] : $field_id;

										$selected = selected($selected_field_id, $sub_id, false);

										echo '<option value="' . esc_attr($sub_id) . '"' . $selected . '>' . esc_attr($sub_title . ' ('. $sub_type . ')') . '</option>';

									}

									echo '</select>';*/
								
									echo '</td>';

									echo '<td>';

									$to = 'to';

									echo '<select name="datebook_bp_field[' . $to . '][' . esc_attr($field_id) . ']">';

									echo '<option value="">' . esc_html__( 'Select', 'datebook' ) . '</option>';

									foreach ($databook_profile_fields_array as $key => $sub_custom_field) {

										$selected = selected($item['datebook_bp_field'][$to][$field_id], $key, false);

										echo '<option value="' . esc_attr($key) . '"' . $selected . '>' . esc_attr($sub_custom_field[0] . ' ('. $sub_custom_field[1] . ')') . '</option>';

									}

									echo '</select>';

									echo '</td>';

									echo '</tr>';

								}

								?>

								</tbody>
							</table>

							<p><input id="datebook" type="submit" class="button button-primary button-hero hide-if-no-js" value="<?php echo esc_html__( 'Save', 'datebook' ); ?>" /></p>

						</form>

					<?php } ?>
				<?php } ?>

				</div>
			</div>
			
			
			<div class="welcome-panel datebook-dummy-notify-box">
				<div class="welcome-panel-content">

					<h2><?php echo esc_html__('Measures', 'datebook'); ?></h2>
					
					<p><?php echo esc_html__('You can use one of measures below in the custom fields Height and Weight', 'datebook'); ?>: WordPress -> DateBook -> Custom Fields</p>
					<p><?php echo esc_html__('Copy one of three columns of Height/Weight and paste in the custom field Height/Weight', 'datebook'); ?></p>

					<table class="widefat striped" width="100%" cellpadding="20" cellspacing="4" style="border: none">
						<tbody>
						<tr>
								<td><?php echo esc_html__( 'Height', 'datebook' ); ?></td>
								<td><?php echo esc_html__( 'Weight', 'datebook' ); ?></td>
							</tr>
							<tr>
								<td>
								
								<table class="widefat striped" width="100%" cellpadding="20" cellspacing="4">
						<thead>
							<tr>
								<th><?php echo esc_html__( 'Centimeters', 'datebook' ); ?></th>
								<th><?php echo esc_html__( 'Centimeters and Feet', 'datebook' ); ?></th>
								<th><?php echo esc_html__( 'Feet', 'datebook' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>150 cm<br>151 cm<br>152 cm<br>153 cm<br>154 cm<br>155 cm<br>156 cm<br>157 cm<br>158 cm<br>159 cm<br>160 cm<br>161 cm<br>162 cm<br>163 cm<br>164 cm<br>165 cm<br>166 cm<br>167 cm<br>168 cm<br>169 cm<br>170 cm<br>171 cm<br>172 cm<br>173 cm<br>174 cm<br>175 cm<br>176 cm<br>177 cm<br>178 cm<br>179 cm<br>180 cm<br>181 cm<br>182 cm<br>183 cm<br>184 cm<br>185 cm<br>186 cm<br>187 cm<br>188 cm<br>189 cm<br>190 cm<br>191 cm<br>192 cm<br>193 cm<br>194 cm<br>195 cm<br>196 cm<br>197 cm<br>198 cm<br>199 cm<br>200 cm</td>
								<td>150 cm (4.92 feet)<br>151 cm (4.95 feet)<br>152 cm (4.99 feet)<br>153 cm (5.02 feet)<br>154 cm (5.05 feet)<br>155 cm (5.09 feet)<br>156 cm (5.12 feet)<br>157 cm (5.15 feet)<br>158 cm (5.18 feet)<br>159 cm (5.22 feet)<br>160 cm (5.25 feet)<br>161 cm (5.28 feet)<br>162 cm (5.31 feet)<br>163 cm (5.35 feet)<br>164 cm (5.38 feet)<br>165 cm (5.41 feet)<br>166 cm (5.45 feet)<br>167 cm (5.48 feet)<br>168 cm (5.51 feet)<br>169 cm (5.54 feet)<br>170 cm (5.58 feet)<br>171 cm (5.61 feet)<br>172 cm (5.64 feet)<br>173 cm (5.68 feet)<br>174 cm (5.71 feet)<br>175 cm (5.74 feet)<br>176 cm (5.77 feet)<br>177 cm (5.81 feet)<br>178 cm (5.84 feet)<br>179 cm (5.87 feet)<br>180 cm (5.91 feet)<br>181 cm (5.94 feet)<br>182 cm (5.97 feet)<br>183 cm (6 feet)<br>184 cm (6.04 feet)<br>185 cm (6.07 feet)<br>186 cm (6.1 feet)<br>187 cm (6.14 feet)<br>188 cm (6.17 feet)<br>189 cm (6.2 feet)<br>190 cm (6.23 feet)<br>191 cm (6.27 feet)<br>192 cm (6.3 feet)<br>193 cm (6.33 feet)<br>194 cm (6.36 feet)<br>195 cm (6.4 feet)<br>196 cm (6.43 feet)<br>197 cm (6.46 feet)<br>198 cm (6.5 feet)<br>199 cm (6.53 feet)<br>200 cm (6.56 feet)</td>
								<td>4.92 feet<br>4.95 feet<br>4.99 feet<br>5.02 feet<br>5.05 feet<br>5.09 feet<br>5.12 feet<br>5.15 feet<br>5.18 feet<br>5.22 feet<br>5.25 feet<br>5.28 feet<br>5.31 feet<br>5.35 feet<br>5.38 feet<br>5.41 feet<br>5.45 feet<br>5.48 feet<br>5.51 feet<br>5.54 feet<br>5.58 feet<br>5.61 feet<br>5.64 feet<br>5.68 feet<br>5.71 feet<br>5.74 feet<br>5.77 feet<br>5.81 feet<br>5.84 feet<br>5.87 feet<br>5.91 feet<br>5.94 feet<br>5.97 feet<br>6 feet<br>6.04 feet<br>6.07 feet<br>6.1 feet<br>6.14 feet<br>6.17 feet<br>6.2 feet<br>6.23 feet<br>6.27 feet<br>6.3 feet<br>6.33 feet<br>6.36 feet<br>6.4 feet<br>6.43 feet<br>6.46 feet<br>6.5 feet<br>6.53 feet<br>6.56 feet</td>
							</tr>
						</tbody>
					</table>
								</td>
								<td>
								
								<table class="widefat striped" width="100%" cellpadding="20" cellspacing="4">
						<thead>
							<tr>
								<th><?php echo esc_html__( 'Kilograms', 'datebook' ); ?></th>
								<th><?php echo esc_html__( 'Kilograms and Pounds', 'datebook' ); ?></th>
								<th><?php echo esc_html__( 'Pounds', 'datebook' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>40 kg<br>41 kg<br>42 kg<br>43 kg<br>44 kg<br>45 kg<br>46 kg<br>47 kg<br>48 kg<br>49 kg<br>50 kg<br>51 kg<br>52 kg<br>53 kg<br>54 kg<br>55 kg<br>56 kg<br>57 kg<br>58 kg<br>59 kg<br>60 kg<br>61 kg<br>62 kg<br>63 kg<br>64 kg<br>65 kg<br>66 kg<br>67 kg<br>68 kg<br>69 kg<br>70 kg<br>71 kg<br>72 kg<br>73 kg<br>74 kg<br>75 kg<br>76 kg<br>77 kg<br>78 kg<br>79 kg<br>80 kg<br>81 kg<br>82 kg<br>83 kg<br>84 kg<br>85 kg<br>86 kg<br>87 kg<br>88 kg<br>89 kg<br>90 kg<br>91 kg<br>92 kg<br>93 kg<br>94 kg<br>95 kg<br>96 kg<br>97 kg<br>98 kg<br>99 kg<br>100 kg<br>101 kg<br>102 kg<br>103 kg<br>104 kg<br>105 kg<br>106 kg<br>107 kg<br>108 kg<br>109 kg<br>110 kg<br>111 kg<br>112 kg<br>113 kg<br>114 kg<br>115 kg<br>116 kg<br>117 kg<br>118 kg<br>119 kg<br>120 kg</td>
								<td>40 kg (88.2 lb)<br>41 kg (90.4 lb)<br>42 kg (92.6 lb)<br>43 kg (94.8 lb)<br>44 kg (97.0 lb)<br>45 kg (99.2 lb)<br>46 kg (101.4 lb)<br>47 kg (103.6 lb)<br>48 kg (105.8 lb)<br>49 kg (108.0 lb)<br>50 kg (110.2 lb)<br>51 kg (112.4 lb)<br>52 kg (114.6 lb)<br>53 kg (116.8 lb)<br>54 kg (119.0 lb)<br>55 kg (121.3 lb)<br>56 kg (123.5 lb)<br>57 kg (125.7 lb)<br>58 kg (127.9 lb)<br>59 kg (130.1 lb)<br>60 kg (132.3 lb)<br>61 kg (134.5 lb)<br>62 kg (136.7 lb)<br>63 kg (138.9 lb)<br>64 kg (141.1 lb)<br>65 kg (143.3 lb)<br>66 kg (145.5 lb)<br>67 kg (147.7 lb)<br>68 kg (149.9 lb)<br>69 kg (152.1 lb)<br>70 kg (154.3 lb)<br>71 kg (156.5 lb)<br>72 kg (158.7 lb)<br>73 kg (160.9 lb)<br>74 kg (163.1 lb)<br>75 kg (165.4 lb)<br>76 kg (167.6 lb)<br>77 kg (169.8 lb)<br>78 kg (172.0 lb)<br>79 kg (174.2 lb)<br>80 kg (176.4 lb)<br>81 kg (178.6 lb)<br>82 kg (180.8 lb)<br>83 kg (183.0 lb)<br>84 kg (185.2 lb)<br>85 kg (187.4 lb)<br>86 kg (189.6 lb)<br>87 kg (191.8 lb)<br>88 kg (194.0 lb)<br>89 kg (196.2 lb)<br>90 kg (198.4 lb)<br>91 kg (200.6 lb)<br>92 kg (202.8 lb)<br>93 kg (205.0 lb)<br>94 kg (207.2 lb)<br>95 kg (209.4 lb)<br>96 kg (211.6 lb)<br>97 kg (213.9 lb)<br>98 kg (216.1 lb)<br>99 kg (218.3 lb)<br>100 kg (220.5 lb)<br>101 kg (222.7 lb)<br>102 kg (224.9 lb)<br>103 kg (227.1 lb)<br>104 kg (229.3 lb)<br>105 kg (231.5 lb)<br>106 kg (233.7 lb)<br>107 kg (235.9 lb)<br>108 kg (238.1 lb)<br>109 kg (240.3 lb)<br>110 kg (242.5 lb)<br>111 kg (244.7 lb)<br>112 kg (246.9 lb)<br>113 kg (249.1 lb)<br>114 kg (251.3 lb)<br>115 kg (253.5 lb)<br>116 kg (255.7 lb)<br>117 kg (257.9 lb)<br>118 kg (260.1 lb)<br>119 kg (262.4 lb)<br>120 kg (264.6 lb)</td>
								
								<td>90 lb<br>91 lb<br>92 lb<br>93 lb<br>94 lb<br>95 lb<br>96 lb<br>97 lb<br>98 lb<br>99 lb<br>110 lb<br>111 lb<br>112 lb<br>113 lb<br>114 lb<br>115 lb<br>116 lb<br>117 lb<br>118 lb<br>119 lb<br>120 lb<br>121 lb<br>122 lb<br>123 lb<br>124 lb<br>125 lb<br>126 lb<br>127 lb<br>128 lb<br>129 lb<br>130 lb<br>131 lb<br>132 lb<br>133 lb<br>134 lb<br>135 lb<br>136 lb<br>137 lb<br>138 lb<br>139 lb<br>140 lb<br>141 lb<br>142 lb<br>143 lb<br>144 lb<br>145 lb<br>146 lb<br>147 lb<br>148 lb<br>149 lb<br>150 lb<br>151 lb<br>152 lb<br>153 lb<br>154 lb<br>155 lb<br>156 lb<br>157 lb<br>158 lb<br>159 lb<br>160 lb<br>161 lb<br>162 lb<br>163 lb<br>164 lb<br>165 lb<br>166 lb<br>167 lb<br>168 lb<br>169 lb<br>170 lb<br>171 lb<br>172 lb<br>173 lb<br>174 lb<br>175 lb<br>176 lb<br>177 lb<br>178 lb<br>179 lb<br>180 lb<br>181 lb<br>182 lb<br>183 lb<br>184 lb<br>185 lb<br>186 lb<br>187 lb<br>188 lb<br>189 lb<br>190 lb<br>191 lb<br>192 lb<br>193 lb<br>194 lb<br>195 lb<br>196 lb<br>197 lb<br>198 lb<br>199 lb<br>200 lb<br>201 lb<br>202 lb<br>203 lb<br>204 lb<br>205 lb<br>206 lb<br>207 lb<br>208 lb<br>209 lb<br>210 lb<br>211 lb<br>212 lb<br>213 lb<br>214 lb<br>215 lb<br>216 lb<br>217 lb<br>218 lb<br>219 lb<br>220 lb<br>221 lb<br>222 lb<br>223 lb<br>224 lb<br>225 lb<br>226 lb<br>227 lb<br>228 lb<br>229 lb<br>230 lb<br>231 lb<br>232 lb<br>233 lb<br>234 lb<br>235 lb<br>236 lb<br>237 lb<br>238 lb<br>239 lb<br>240 lb<br>241 lb<br>242 lb<br>243 lb<br>244 lb<br>245 lb<br>246 lb<br>247 lb<br>248 lb<br>249 lb<br>250 lb<br>251 lb<br>252 lb<br>253 lb<br>254 lb<br>255 lb<br>256 lb<br>257 lb<br>258 lb<br>259 lb<br>260 lb<br>261 lb<br>262 lb<br>263 lb<br>264 lb<br>265 lb</td>
								
							</tr>
						</tbody>
					</table>
								</td>
								
							</tr>
						</tbody>
					</table>
					
					

				</div>
			</div>
			
            <?php } ?>
			
			
			
			

		</div>

	<?php

	}


	// Insert a record into the database that all countries inserted
	public static function datebook_ajax_profiles_inserted() {

		// all countries are now installed so we don't need to run this again
		update_option('datebook_bp_profiles_migrated', 'yes');
		
		die();
		
	}


	// Process counting profiles in countries
	public static function migrate_profiles_datebook_to_buddypress() {
		
		global $profile_id, $upload_folder;

		$current_user_id = absint($_REQUEST['id']);

		if(isset($current_user_id) && $current_user_id > 0){

			global $wpdb, $datebook_gender_titles, $datebook_sexualorientation_titles;

			$table_bp_xprofile_data = strtolower($wpdb->prefix) . 'bp_xprofile_data'; // do not forget about tables prefix
			
			$table_bp_xprofile_fields = strtolower($wpdb->prefix) . 'bp_xprofile_fields';
			
			$table_countries = strtolower($wpdb->prefix) . 'datebook_countries';

			$set_data = $get_data = $item = $bp_user_data = $bp_user_fields = $bp_custom_fields_array = $bp_user_fields_array = $new_array = $datebook_get_data = $bp_custom_fields_array = array();

			//Get entire array
			$item = get_option('datebook_migrate');
			$item = isset($item['bp_migrate_options']) ? $item['bp_migrate_options'] : '';

			if ($item) {

				foreach($item['datebook_bp_field']['to'] as $key => $value){

					if($value){

						$bp_user_data[$value] = $wpdb->get_row($wpdb->prepare("SELECT field_id, user_id, value FROM `" . $table_bp_xprofile_data . "` WHERE `field_id` = %d AND `user_id` = %d", $key, $current_user_id));

					}
				}


				$profile_name = isset($bp_user_data['profile_name']->value) ? $bp_user_data['profile_name']->value : '';
				$aboutme = isset($bp_user_data['aboutme']->value) ? $bp_user_data['aboutme']->value : '';
				$postname = substr($current_user_id.time(), 0, 10);

				// Create post object
				$post_profile = array(
					'post_author' => $current_user_id,
					'post_title' => $profile_name,
					'post_content' => $aboutme,
					'post_name' => $postname,
					'post_status' => 'publish',
					'post_type' => DATEBOOK_POST_TYPE,
					'ping_status' => 'closed'
				);

				// Insert the post into the database
				$profile_id = wp_insert_post($post_profile);

				$get_profile_custom_fields = get_option('datebook_profile_custom_fields');

				$bp_user_fields_count = 0;

				$find_ins_measure = array('inches', 'ins', 'in', 'i');
				$find_ft_measure = array('feets', 'feet', 'foot', 'fts', 'ft', 'f');
				$find_cm_measure = array('centimeters', 'centimeter', 'centimetre', 'cents', 'centi', 'cent', 'cm', 'c', 'm', '.', ',');

				$find_lbs_measure = array('pounds', 'pound', 'lbs', 'lb', 'l');
				$find_kg_measure = array('kilograms', 'kilogram', 'kilos', 'kilo', 'kg', 'k');

				$replace_measure = array('');

				function strposa($haystack, $needle, $offset=0) {
					if(!is_array($needle)) $needle = array($needle);
					foreach($needle as $query) {
						if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
					}
					return false;
				}


				foreach($bp_user_data as $key => $value){

					$user_value = isset($value->value) ? $value->value : '';

					// if foreign language do not exist, then show title in English (en_US)
					$field_items = $get_profile_custom_fields[$key]['field_items_en_US'];
					$field_items_out = explode('|||', strtr($field_items, array("\r\n" => '|||', "\r" => '|||', "\n" => '|||')));

					if($key == 'height' && $user_value != ''){

						if(strposa($user_value, $find_ins_measure)){
							// ft and ins to cm
							$clean_measure = explode(' ', $user_value);
							$feet = trim(str_replace(',','',str_replace($find_ft_measure,$replace_measure,$clean_measure[0])));
							$inches_array = isset($clean_measure[1]) ? $clean_measure[1] : '';
							$inches_array_2 = isset($clean_measure[2]) ? $clean_measure[2] : '';
							$inches_array_3 = isset($clean_measure[3]) ? $clean_measure[3] : '';
							$inches_array_4 = isset($clean_measure[4]) ? $clean_measure[4] : '';

							$inches = $inches_array . $inches_array_2 . $inches_array_3 . $inches_array_4;
							$inches = str_replace($find_ins_measure,$replace_measure,str_replace($find_ft_measure,$replace_measure,$inches));
							$inches = trim(str_replace(',','',$inches));

							$inches = ($feet * 12) + $inches;
							$measure_number_cm = (int) round($inches / 0.393701);

							$feet_pre = $measure_number_cm * 0.0328;
							$measure_number_ft_comma = number_format((float)$feet_pre, 2, ',', '');
							$measure_number_ft_dot = number_format((float)$feet_pre, 2, '.', '');



						} else if(strposa($user_value, $find_ft_measure)){
							// ft to cm
							$clean_measure = trim(str_replace($find_ft_measure,$replace_measure,$user_value));
							$inches = $clean_measure * 30.48;
							$measure_number_cm = (int) round($inches);

							$feet_pre = $measure_number_cm * 0.0328;
							$measure_number_ft_comma = number_format((float)$feet_pre, 2, ',', '');
							$measure_number_ft_dot = number_format((float)$feet_pre, 2, '.', '');

						} else if(strposa($user_value, $find_cm_measure)){
							// cm to ft
							$clean_measure = trim(str_replace($find_cm_measure,$replace_measure,$user_value));
							$feet_pre = $clean_measure * 0.0328;

							$measure_number_cm = $clean_measure;

							$measure_number_ft_comma = number_format((float)$feet_pre, 2, ',', '');
							$measure_number_ft_dot = number_format((float)$feet_pre, 2, '.', '');

						}

						foreach($field_items_out as $key_field_item => $val_field_item) {

							if(preg_match("~\b{$measure_number_cm}\b~", $val_field_item) || preg_match("~\b{$measure_number_ft_comma}\b~", $val_field_item) || preg_match("~\b{$measure_number_ft_dot}\b~", $val_field_item)){

								$key_field_item = $key_field_item + 1;

								$get_data[$key] = "$key_field_item";

							}
						}

					} else if($key == 'weight' && $user_value != ''){

						if(strposa($user_value, $find_lbs_measure)){
							// lbs to kg
							$measure = trim(str_replace(',', '', str_replace($find_lbs_measure,$replace_measure,$user_value)));

							$measure_number_kg = $measure * 0.453592;
							$measure_number_lbs = $measure;

						} else if(strposa($user_value, $find_kg_measure)){
							// kg to lbs
							$measure = trim(str_replace(',', '', str_replace($find_kg_measure,$replace_measure,$user_value)));

							$measure_number_kg = $measure;
							$measure_number_lbs = $measure * 2.20462;

						}

						if(isset($measure_number_lbs) && !empty($measure_number_lbs)){

							foreach($field_items_out as $key_field_item => $val_field_item) {

								if(preg_match("~\b{$measure_number_kg}\b~", $val_field_item) || preg_match("~\b{$measure_number_lbs}\b~", $val_field_item)){

									$key_field_item = $key_field_item + 1;

									$get_data[$key] = "$key_field_item";
									
								}
							}
						}

					} else if($get_profile_custom_fields[$key]['type'] == 'text' || $get_profile_custom_fields[$key]['type'] == 'textarea'){

						$get_data[$key] = "$user_value";

					} else {

						$bp_user_fields = $wpdb->get_results($wpdb->prepare("SELECT name FROM `" . $table_bp_xprofile_fields . "` WHERE `parent_id` = %d ORDER BY id ASC", $value->field_id));

						$data = @unserialize($user_value);

						$set_data = array("0");

						foreach($bp_user_fields as $bp_key => $bp_val) {

							$bp_key = $bp_key + 1;

							if ($data !== false) {

								if(in_array($bp_val->name, $data)){
									$set_data[] = "$bp_key";
								}

							} else {

								if($user_value == $bp_val->name){
									if($get_profile_custom_fields[$key]['type'] == 'checkbox'){
										$get_data[$key] = array("0", "$bp_key");
									} else {
										$get_data[$key] = "$bp_key";
									}
								}
							}
						}

						if ($data !== false) {
							$get_data[$key] = $set_data;
						}

					}

				}

				$datebook_get_data['edit_form'] = $get_data;

				// Add some aditional settings and info
				$bp_user_city = isset($bp_user_data['city_id']->value) ? $bp_user_data['city_id']->value : '';
				$city_slug = DateBook_Utilities::datebook_makeslug($bp_user_city);

				$term_data = DateBook_Utilities::datebook_get_term_by( 'slug', $city_slug );

				// Start finding city in database
				if(isset($term_data->city_id)){

					$datebook_get_data['city'] = $term_data->city_id;

				} else {

					// no shortest distance found, yet
					$shortest = -1;

					// Get all countries
					$query_country = "SELECT * FROM {$table_countries} WHERE parent_id = %d AND level = %d"; //  LIMIT 10 OFFSET 15

					// Select all countries only
					$get_countries_only = $wpdb->get_results($wpdb->prepare($query_country, 0, 0), ARRAY_A);

					// Get all countries
					if (count($get_countries_only) > 0) {

						$bp_user_country = isset($bp_user_data['country_id']->value) ? $bp_user_data['country_id']->value : '';
						
						$country_languages_found = $country_id = 0;

						// loop through words to find the closest
						foreach ($get_countries_only as $locale => $country) {

							$get_value_name_array = maybe_unserialize($country['name']);

							foreach($get_value_name_array as $locale => $language) {
								if($language == $bp_user_country){
									$country_languages_found = 1;
									break;
								}
							}
							if($country_languages_found > 0){
								$country_id = $country['id'];
								break;
							}
						}

						if($country_id > 0){
							
							$get_cities_array = array();

							// Get all regions
							$query_countries = "SELECT * FROM {$table_countries} WHERE parent_id = %d ORDER BY slug ASC";
							$get_regions_only = $wpdb->get_results($wpdb->prepare($query_countries, $country_id), ARRAY_A);

							// Get all regions
							if (count($get_regions_only) > 0) {
								foreach($get_regions_only as $key => $get_region_only){
									// Get all cities
									$get_cities_array[] = $wpdb->get_results($wpdb->prepare($query_countries, $get_region_only['id']), ARRAY_A);
								}
							}

							$city_languages_found = 0;

							// loop through words to find the closest
							foreach ($get_cities_array as $key => $get_city_value) {
								foreach($get_city_value as $subkey => $sublanguage) {
									$language_array = maybe_unserialize($sublanguage['name']);
									foreach($language_array as $locale => $language) {
										$city_languages_array[] = $language;
									}
								}
							}

							foreach($city_languages_array as $city_name) {

								// calculate the distance between the input word, and the current word
								$lev = levenshtein($bp_user_city, $city_name);

								// check for an exact match
								if ($lev == 0) {
									// closest word is this one (exact match)
									$closest = $city_name;
									$shortest = 0;
									// break out of the loop; we've found an exact match
									break;
								}

								// if this distance is less than the next found shortest distance, OR if a next shortest word has not yet been found
								if ($lev <= $shortest || $shortest < 0) {
									// set the closest match, and shortest distance
									$closest[]  = $city_name;
									$shortest = $lev;
								}
							}
							
							if(isset($closest) && is_array($closest)){
								foreach ($closest as $word) {
									// calculate the distance between the input word, and the current word
									$lev = similar_text($bp_user_city, $word);
									$level[$lev] = $word;
								}
							}
							
							$new_key = max(array_keys($level));
							$new_val = $level[$new_key];
							
							$term_data = DateBook_Utilities::datebook_get_term_by( 'slug', $new_val );
							$datebook_get_data['city'] = $term_data->city_id;

						}
					}
				}

				$datebook_get_data['region'] = isset($term_data->region_id) ? $term_data->region_id : '';
				$datebook_get_data['country'] = isset($term_data->country_id) ? $term_data->country_id : '';


				if(isset($datebook_get_data['city']) && $datebook_get_data['city'] > 0){
					// increment counts in counter in city
					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $datebook_get_data['city']) );
					update_post_meta($profile_id, 'city', absint($datebook_get_data['city']));
				}

				if(isset($datebook_get_data['region']) && $datebook_get_data['region'] > 0){
					// increment counts in counter in region
					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $datebook_get_data['region']) );
					update_post_meta($profile_id, 'region', absint($datebook_get_data['region']));
				}

				if(isset($datebook_get_data['country']) && $datebook_get_data['country'] > 0){
					// increment counts in counter in country
					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $datebook_get_data['country']) );
					update_post_meta($profile_id, 'country', absint($datebook_get_data['country']));
				}


				// Update Date of Birth
				$datebook_get_data['birthday'] = '';
				$birthday = isset($bp_user_data['birthday']->value) ? $bp_user_data['birthday']->value : '';
				if (isset($birthday)) {

					$datebook_get_data['birthday'] = $birthday;

					$get_birthday = explode(' ', $birthday);
					$get_birthday = explode('-', $get_birthday[0]);

					$datebook_get_data['dateyear'] = $get_birthday[0];
					$datebook_get_data['datemonth'] = $get_birthday[1];
					$datebook_get_data['dateday'] = $get_birthday[2];

					update_post_meta($profile_id, 'birthday', sanitize_text_field($datebook_get_data['birthday']));
				}
				
				// Detect gender
				$bp_user_gender_fields = $wpdb->get_results($wpdb->prepare("SELECT name FROM `" . $table_bp_xprofile_fields . "` WHERE `parent_id` = %d ORDER BY id ASC", $bp_user_data['gender']->field_id));

				foreach ($bp_user_gender_fields as $bp_key => $bp_value) {

					$bp_key = $bp_key + 1;

					if(isset($bp_value->name) && $bp_value->name == $bp_user_data['gender']->value){
						$datebook_get_data['gender'] = $bp_key;
						break;
					}
				}
				if (isset($datebook_get_data['gender']) && $datebook_get_data['gender'] > 0) {
					update_post_meta($profile_id, 'gender', absint($datebook_get_data['gender']));
				}

				// detect sexual orientation
				foreach ($datebook_sexualorientation_titles as $key => $name) {
					if(isset($bp_user_data['sexualorientation']->value) && $bp_user_data['sexualorientation']->value == $name){
						$datebook_get_data['sexualorientation'] = $key;
					}
				}
				if (isset($datebook_get_data['sexualorientation']) && $datebook_get_data['sexualorientation'] > 0) {
					update_post_meta($profile_id, 'sexualorientation', absint($datebook_get_data['sexualorientation']));
				}


				// Update Family status
				$datebook_get_data['family_status'] = 'single';
				update_post_meta($profile_id, 'family_status', 'single');

				$datebook_get_data['phone'] = isset($bp_user_data['phone']->value) ? $bp_user_data['phone']->value : '';
				$datebook_get_data['website'] = isset($bp_user_data['website']->value) ? $bp_user_data['website']->value : '';

				$datebook_get_data['wishtravel'] = '';
				$datebook_get_data['wishtraveltext'] = '';

				$datebook_get_data['upload_folder'] = $upload_folder = time().rand(1,999);
				$datebook_get_data['profile_type'] = DATEBOOK_POST_TYPE;
				$datebook_get_data['profile_postid'] = $profile_id;
				$datebook_get_data['topad'] = '0';
				$datebook_get_data['featured'] = '0';

				$datebook_get_data['ip'] = '';
				$datebook_get_data['hostname'] = '';

				$datebook_get_data['profile_id'] = $profile_id;
				$datebook_get_data['profile_name'] = $profile_name;

				$datebook_get_data['post_views_count'] = 0;

				// Image copy
				// Include prerequisite
				if ( ! function_exists( 'wp_handle_upload' ) ) {
					require_once( ABSPATH . 'wp-admin/includes/file.php' );
				}
				if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
					require_once( ABSPATH . 'wp-admin/includes/image.php' );
				}

				$upload_dir = wp_upload_dir();

				// Image copy
				$profile_photo_url = bp_core_fetch_avatar(array('item_id' => $current_user_id, 'type' => 'full', 'width' => 32, 'height' => 32, 'class' => 'friend-avatar','html'=>false));

				// Override the default upload path
				function datebook_upload_dir( $dirs ) {

					global $profile_id, $upload_folder;

				    $dirs['subdir'] = '/' . $upload_folder;
				    $dirs['path'] = $dirs['basedir'] . '/' . $upload_folder;
			    	$dirs['url'] = $dirs['baseurl'] . '/' . $upload_folder;

				    return $dirs;

				}

				function datebook_copy_image_to_upload_dir($profile_photo_url, $upload_dir, $profile_id, $current_user_id){

					$get_site_url = get_site_url();

					$dir = str_replace($get_site_url, '', $profile_photo_url);
					$dir = str_replace('/wp-content/uploads', '', $dir);

					$path  = $upload_dir['basedir'] . $dir;

					if (file_exists($path) ) {

						$targetPath = $upload_dir['basedir'] . '/' . $upload_folder;

						if ( ! file_exists( $targetPath ) ) {
							wp_mkdir_p( $targetPath );
						}

						$filename = basename($path);
						$filename_no_ext = pathinfo($path, PATHINFO_FILENAME);
						$extension = pathinfo($path, PATHINFO_EXTENSION);

						$thumbnail_url = $upload_dir['baseurl'] . '/' . $upload_folder . '/' . $filename_no_ext . '.' . $extension;

						// Simulate uploading a file through $_FILES. We need a temporary file for this.
						$tmp = tmpfile();
						$tmp_path = stream_get_meta_data($tmp);
						$tmp_path = $tmp_path['uri'];

						fwrite($tmp, file_get_contents( $path ));
						fseek($tmp, 0); // If we don't do this, WordPress thinks the file is empty

						$fake_FILE = array(
							'name'      => $filename,
							'type'      => 'image/' . $extension,
							'tmp_name'  => $tmp_path,
							'error'     => UPLOAD_ERR_OK,
							'size'      => filesize($path),
						);

						// Trick is_uploaded_file() by adding it to the superglobal
						$_FILES[basename($tmp_path)] = $fake_FILE;

						// Override the default upload path
						add_filter( 'upload_dir', 'datebook_upload_dir' );

						$result = wp_handle_upload( $fake_FILE, array( 'test_form' => false, 'action' => 'local' ) );

						remove_filter( 'upload_dir', 'datebook_upload_dir' );

						fclose($tmp); // Close tmp file
						@unlink($tmp_path); // Delete the tmp file. Closing it should also delete it, so hide any warnings with @
						unset( $_FILES[basename($tmp_path)] ); // Clean up our $_FILES mess.

						$result['attachment_id'] = 0;

						$targetURL . '/' . sanitize_file_name($targetFile);

						if ( empty($result['error'])) {
							$attachment = array(
								'post_title' => $filename_no_ext . '.' . $extension,
								'post_content' => '',
								'post_status' => 'inherit',
								'post_parent' => $profile_id,
								'guid' => $thumbnail_url,
								'post_mime_type' => $result['type'],
							);

							$result['attachment_id'] = wp_insert_attachment( $attachment, $result['file'] );
							
							// Update post
							$post_attachment = array(
								'ID' => $result['attachment_id'],
								'post_author' => $current_user_id
							);
							wp_update_post( $post_attachment );

							if ( is_wp_error( $result['attachment_id'] ) ) {
								$result['attachment_id'] = 0;
							} else {
								$attach_data = wp_generate_attachment_metadata( $result['attachment_id'], $result['file'] );
								$update_attach_metadata = wp_update_attachment_metadata( $result['attachment_id'], $attach_data );
							}
							
							// Add what type of photo we uploaded. We will need this information later
							// Mark this action as Profile Photos
							$datebook_photo_type = DATEBOOK_PROFILE_IMAGE_TYPE;
							update_post_meta($result['attachment_id'], DATEBOOK_IMAGE_TYPE, $datebook_photo_type);
						}

						//echo $result;

						return $filename_no_ext . '.' . $extension;

					}
				}

				$datebook_get_data['profile_photo_id'] = datebook_copy_image_to_upload_dir($profile_photo_url, $upload_dir, $profile_id, $current_user_id);

				if ( class_exists( 'RTMedia' ) ) {

					$table_rt_rtm_media = strtolower($wpdb->prefix) . 'rt_rtm_media';

					$where = "SELECT * FROM {$table_rt_rtm_media}";
					$where .= " WHERE {$table_rt_rtm_media}.media_type = 'photo' AND media_author = {$current_user_id}";
					$where .= " AND ({$table_rt_rtm_media}.privacy is NULL OR {$table_rt_rtm_media}.privacy<=0";
					$where .= " AND {$table_rt_rtm_media}.context = 'profile'";
					$where  .= ") ORDER BY media_id DESC";
					$myrows = $wpdb->get_results( $where );

					if ( $myrows && count( $myrows ) > 0 ) {

						foreach ( $myrows as $row ) {

							$src = wp_get_attachment_image_src( $row->media_id, 'rt_media_single_image' );

							$image_url = $src[0];
							
							$datebook_profile_photo = datebook_copy_image_to_upload_dir($image_url, $upload_dir, $profile_id, $current_user_id);

						}
					}
				}

				$online_status =  mktime(0, 0, 0, date("m"), date("d")-rand(1, 20), date("Y"));
				$datebook_get_data['online_status'] = $online_status;
				update_user_meta($current_user_id, 'online_status', $online_status);

				//adding the id in the database and the type of user, so we can check later what privileges they have
				update_user_meta($current_user_id, 'profile_type', DATEBOOK_POST_TYPE);
				//add the post id that the user created. The user will only be able to edit this single post
				update_user_meta($current_user_id, 'profile_postid', $profile_id);
				update_post_meta($profile_id, 'topad', '0');
				update_post_meta($profile_id, 'featured', '0');


				foreach($datebook_get_data as $key => $value) {

					// sanitize data in array
					if (is_array($value)) {
						$value = array_map( 'sanitize_text_field', $value );
					} else {
						$value = sanitize_text_field( $value );
					}

					//Alter the options array appropriately
					$profile_field_data[sanitize_key($key)] = $value;

				}

				// Update the post meta
				update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);

				// Add a user to the migrated users list
				$datebook_migrated_users = get_option('datebook_migrated_users');
				
				if (($key = array_search($current_user_id, $datebook_migrated_users)) !== false) {
					unset($datebook_migrated_users[$key]);
				}

				update_option('datebook_migrated_users', $datebook_migrated_users);

				$response =  array('success' => sprintf(esc_html__( 'User ID: %1$s (%2$s) has been successfully migrated', 'datebook' ), $current_user_id, $profile_name . ' (' . $profile_id . '_' . $current_user_id . ')' ));

				wp_send_json($response);

				die();

			}
		}
	}

}

DateBook_Migrate::init();