<?php
/**
 * DateBook Demo COntent Installer
 * Creates profiles, classified ads and tours
 *
 * @class DateBook_Demo_Content_Installer
 * @author Pagick Themes
 * @since 4.4.9
 */

class DateBook_Demo_Content_Installer {


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

		add_action('wp_ajax_get_countries', array( __CLASS__, 'get_countries_ajax'));

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'datebook_install_script' ) );
		add_action( 'wp_ajax_datebookcreateprofiles', array( __CLASS__, 'datebook_ajax_process_demo_content' ) );
		add_action( 'wp_ajax_datebookprofilesinserted', array( __CLASS__, 'datebook_ajax_demo_content_inserted' ) );

	}
	
	
	
	/**
	 * 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 ));

	}


	/**
	 * Show Popup window with countries
	 *
	 * @access public
	 * @return void
	 */
	public static function countries_popup($location_ID = 0, $location_type = 'country') {

		global $wpdb;

		$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

		// Get city or region from the search form
		$search_location = $multiple_count = $multiple_country = $multiple_region = $multiple_city = 0;
		if ($location_ID > 0 && $location_type == 'country'){
			$search_location = $location_ID;
		} else if($location_type == 'region'){
			$search_location = implode(',',$location_ID);
		}

		if($location_type == 'region'){
			// Get all cities
			$query = "SELECT * FROM " . $table_name . " WHERE parent_id IN (" . $search_location . ") AND active = %d AND counter >= %d ORDER BY slug ASC";
		} else {
			// Get all countries and regions
			$query = "SELECT * FROM " . $table_name . " WHERE parent_id = " . $search_location . " AND active = %d AND counter >= %d ORDER BY slug ASC";
		}

		// Display all active countries
		$get_countries_only = $wpdb->get_results($wpdb->prepare($query, 1, 0), ARRAY_A);

		$search_item_out = $search_item = '';

		if(isset($get_countries_only) && is_array($get_countries_only) && !empty($get_countries_only)){

			foreach($get_countries_only as $cat){

				if ($cat['level'] == 0) {
					//$multiple_count++;
					$multiple_country++;
				} else if ($cat['level'] == 1) {
					$multiple_count++;
					$multiple_region++;
				} else if ($cat['level'] == 2) {
					$multiple_city++;
				}

				$cat_name_array = maybe_unserialize( $cat['name'] );

				// if foreign language do not exist, then show title in English (en_US)
				$cat_name = isset($cat_name_array[DATEBOOK_WPLANG]) && !empty($cat_name_array[DATEBOOK_WPLANG]) ? $cat_name_array[DATEBOOK_WPLANG] : $cat_name_array['en_US'];
				
				if($cat['level'] == 0 || $cat['level'] == 1){
					$search_item .= '<option value="' . esc_attr($cat['id']) . '">' . esc_attr($cat_name) . '</option>';
				} else {
					$search_item .= '<span style="float:left; width: 25%"><input class="selectcity" type="checkbox" name="city[]" value="' . esc_attr($cat['id']) . '" /> ' . esc_attr($cat_name) . '</span>';
				}

			}

		} else {

			$search_item .= '<option>' . esc_html__( 'No countries found', 'datebook' ) . '</option>';

		}

		if($multiple_country > 0){
			$search_item_out .= '<select class="custom-select selectcountry" name="country" style="display:block; width: 100%; margin-bottom: 10px">';
		} else if($multiple_region > 0){
			$search_item_out .= '<select class="custom-select selectregion" name="region" multiple style="display:block; width: 100%; height: 200px; margin-bottom: 10px">';
			
		} else if($multiple_city > 0){
			$search_item_out .= '<div class="selectcity" style="display: inline-block; width: 100%; margin-bottom: 10px">';
		}

		$search_item_out .= $search_item;

		if($multiple_country > 0 || $multiple_region > 0){
			$search_item_out .= '</select>';
		}
		if($multiple_city > 0){
			$search_item_out .= '</div>';
		}

		// display the Countries list
		return $search_item_out;

	}


	/**
	 * Ajax request to retrive countries
	 *
	 * @access public
	 */
	public static function get_countries_ajax(){

		$reponse = array();
    	if(!empty($_POST['id'])){
			$response['response'] = self::countries_popup($_POST['id'], $_POST['location_type']);
		} else {
			$response['response'] = esc_html__('Select a location', 'datebook');
		}

		header( "Content-Type: application/json" );
		echo json_encode($response);

		//Don't forget to always exit in the ajax function.
		exit();
	}


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

		$data = stripslashes_deep($item);

		return $data;

	}


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

		global $allowedposttags;

		// validate data, and if all ok save item to database
		if (isset($_POST['datebook_create_start'])) {
			// if id is zero insert otherwise update
			$item_data = self::validate_data($_POST);

			update_option('datebook_demo_profiles_options', $item_data);

		}

		?>

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

		<div class="wrap">

			<h1><?php echo esc_html__('Demo Content Installer', 'datebook'); ?></h1>
			
			<hr class="wp-header-end">
			
			<p><?php echo esc_html__('You can create profiles that look realistic and as many as you want.', 'datebook'); ?>.</p>
			
			<?php

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

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

					<h2><?php echo esc_html__('Demo Profiles', 'datebook'); ?></h2>

					<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 creating process may take long depending on the quantity of profiles. Thus, you may stop and continue at any time.', 'datebook'); ?>.</p>

					<?php

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

						$create_options = get_option('datebook_demo_profiles_options');

						if(!$create_options) {
							
							?>

							<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__( 'You did not save the Profile form below', 'datebook' ); ?></p>
							</div>
					
							<?php
						
							return;

						} else if ( !empty( $_REQUEST['ids'] ) ) {

							// Create the list of country IDs

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

						} else {

							if ( ! $user_datas = get_option('datebook_demo_profiles_options') ) {

								// 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__( 'Create profiles form has not been saved yet', 'datebook' ) . '</p>';

								echo '</div>';

								echo '</div>';

								return;

							}

							// Generate the list of IDs
							$pre_ids_array = $pre_ids_array = array();

							for ($x = 1; $x <= $user_datas['profile_quantity']; $x++) {
								$pre_ids_array[] = $x;
							}

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

							// Add a user to the created users list
							foreach($pre_ids_array as $key => $value){
								if (($findID = array_search($value, $datebook_created_profiles)) !== 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 created. But %2$s profiles are not created.', 'datebook' ),
						'" + datebooktool_successes + "', 
						'" + datebooktool_errors + "' 
						);

						$message_success = sprintf( esc_html__( 'All %1$s profiles have been successfully created.', '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 created:', '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__( 'Profile 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: "datebookcreateprofiles", 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 creating 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() );

						});
						// ]]>

						');

				?>

				</div>
			</div>


			<?php }	else if (!isset($_POST['datebook_create_start'])){

				$datebook_get_data = array();
				
				global $datebook_field_titles;
				
				set_query_var( 'datebook_field_titles', $datebook_field_titles );
				$datebook_field_titles = get_query_var( 'datebook_field_titles' );
				if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

				delete_option('datebook_demo_profiles_options');
				delete_option('datebook_created_profiles');

				?>

			<div class="welcome-panel datebook-dummy-notify-box">
				<div class="welcome-panel-content">
					
					<h2><?php echo esc_html__('Create profiles', 'datebook'); ?></h2>

					<p><?php echo esc_html__('Press the START button to start creating profiles', 'datebook'); ?>.</p>
					<p><?php echo esc_html__('Fill in all the fields that you want to create in profiles', 'datebook'); ?></p>

					<hr />

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

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

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

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

					<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
						<tbody>
							
							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-gender" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Gender', 'datebook' ); ?></label>
								</th>
								<td>
								<select class="custom-select" name="gender">

								<?php
								
								global $datebook_gender_titles;

								$datebook_get_gender = 1;
								
								if (of_get_option('gender_allowed') != '') {
									$allowed_gender = of_get_option('gender_allowed');
								}

								// Add custom Genders
								if (of_get_option('gender_allowed_other_' . DATEBOOK_WPLANG) != '') {

									$allowed_gender_other_array = explode('<br />', strtr(of_get_option('gender_allowed_other_' . DATEBOOK_WPLANG), array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')));
									foreach ($allowed_gender_other_array as $key => $value ){
										$allowed_gender[] = 1;
									}
								}

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

									if(isset($allowed_gender[$key]) && $allowed_gender[$key] == 1){

										?>

										<option value="<?php echo sanitize_key($key); ?>"<?php if (isset($datebook_get_gender) && $datebook_get_gender == $key) { echo ' selected="selected"'; } ?>><?php echo esc_html__( $value, 'datebook' ); ?></option>

										<?php
									}
								}

								?>
								
								</select>

								</td>
							</tr>

							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-profile-quantity" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Quantity of profiles', 'datebook' ); ?></label>
								</th>
								<td>
									<input type="number" name="profile_quantity" value="300" style="width:auto" />
								</td>
							</tr>

							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-subscription-plan-id" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Countries', 'datebook' ); ?></label>
									
								</th>
								<td class="datebook-location">

									<?php
									
									echo self::countries_popup();

									?>
									
									<table class="datebook-country-last" cellspacing="0" cellpadding="0" style="width: 100%;">
									<tr>
										<td style="padding:0"><?php echo esc_html__( 'Hold down CTRL to select more regions. If location is not selected, random countries, regions and cities will be assigned to random profiles.', 'datebook' ); ?></td>
									</tr>
									</table>

								</td>
							</tr>

							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-date-birth" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Date of birth', 'datebook' ); ?></label>
								</th>
								<td style="padding:0">
								
								<table cellspacing="0" cellpadding="0" style="width: 100%;" class="form-table">
									<tr class="form-field">
										<td valign="top" scope="row">
										<input type="text" name="date_birth_start" id="datebook-start" value="<?php if (isset($datebook_get_data['date_birth_start'])) { echo date("Y", $datebook_get_data['date_birth_start']); } else { echo date('Y', strtotime('-50 years')); } ?>" class="form-control" placeholder="<?php echo date('Y', strtotime('-50 years')); ?>" />
										
										</td>
										<td>
										<input type="text" name="date_birth_end" id="datebook-end" value="<?php if (isset($datebook_get_data['date_birth_end'])) { echo date("Y", $datebook_get_data['date_birth_end']); } else { echo date('Y', strtotime('-18 years')); } ?>" class="form-control" placeholder="<?php echo date('Y', strtotime('-18 years')); ?>" />
										</td>
									</tr>
								</table>
								<?php echo esc_html__( 'Select a range of years between which random birth dates will be generated.', 'datebook' ); ?>
								</td>
							</tr>

							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-sexualorientation" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Sexual orientation', 'datebook' ); ?> (<?php echo esc_html__( 'optional', 'datebook' ); ?>)</label>
								</th>
								<td>

								<?php

								$allowed_sexual_orientation = of_get_option('sexual_orientation_allowed');

								// Add custom Sexual Orientations
								if (of_get_option('sexual_orientation_allowed_other_' . DATEBOOK_WPLANG) != '') {
									$sexual_orientation_allowed_other_array = explode('<br />', strtr(of_get_option('sexual_orientation_allowed_other_' . DATEBOOK_WPLANG), array('\r\n' => '<br />', '\r' => '<br />', '\n' => '<br />')));
									
									foreach ($sexual_orientation_allowed_other_array as $key => $value ){
										$allowed_sexual_orientation[] = 1;
									}
								}

								?>

								<ul>

								<?php

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

									if(isset($allowed_sexual_orientation[$key]) && $allowed_sexual_orientation[$key] == 1){

										?>

										<li><input type="checkbox" name="sexualorientation[]" value="<?php echo sanitize_key($key); ?>" /> <?php echo esc_html__( $value, 'datebook' ); ?></li>

								<?php } } ?>
								
								</ul>
								
								<?php echo esc_html__( 'If selected, these items will be assigned to random profiles.', 'datebook' ); ?>

								</td>
							</tr>

							
							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-registration" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Date of registration', 'datebook' ); ?></label>
								</th>
								<td style="padding:0">
								
								<table cellspacing="0" cellpadding="0" style="width: 100%;" class="form-table">
									<tr class="form-field">
										<td valign="top" scope="row">
										<input type="text" name="registration_start" id="datebook-start" value="<?php if (isset($datebook_get_data['registration_start'])) { echo date("d.m.Y", $datebook_get_data['registration_start']); } else { echo date('d.m.Y', strtotime('-2 years')); } ?>" class="form-control" />
										</td>
										<td>
										<input type="text" name="registration_end" id="datebook-end" value="<?php if (isset($datebook_get_data['registration_end'])) { echo date("d.m.Y", $datebook_get_data['registration_end']); } else { echo date('d.m.Y'); } ?>" class="form-control" />
										</td>
									</tr>
								</table>
								<?php echo esc_html__( 'Select a range of dates between which random profile registration dates will be generated.', 'datebook' ); ?>
								</td>
							</tr>
							
							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-top" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Top status', 'datebook' ); ?></label>
								</th>
								<td style="padding:0">

								<table cellspacing="0" cellpadding="0" style="width: 100%;" class="form-table">
									<tr class="form-field">
										<td valign="top" scope="row">
										<input type="text" name="top_start" id="datebook-start" value="<?php if (isset($datebook_get_data['top_start'])) { echo date("d.m.Y", $datebook_get_data['top_start']); } else { echo date('d.m.Y', strtotime('-1 day')); } ?>" class="form-control" />
										</td>
										<td>
										<input type="text" name="top_end" id="datebook-end" value="<?php if (isset($datebook_get_data['top_end'])) { echo date("d.m.Y", $datebook_get_data['top_end']); } else { echo date('d.m.Y', strtotime('+365 days')); } ?>" class="form-control" />
										</td>
									</tr>
								</table>
								<?php echo esc_html__( 'Select a range of dates between which random expiration dates for Top status will be generated for random profiles.', 'datebook' ); ?>
								</td>
							</tr>
							
<tr class="form-field">
							<th valign="top" scope="row">
									<label for="datebook-featured" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Featured status', 'datebook' ); ?></label>
								</th>
								<td style="padding:0">
								
								<table cellspacing="0" cellpadding="0" style="width: 100%;" class="form-table">
									<tr class="form-field">
										<td valign="top" scope="row">
										<input type="text" name="featured_start" id="datebook-start" value="<?php if (isset($datebook_get_data['featured_start'])) { echo date("d.m.Y", $datebook_get_data['featured_start']); } else { echo date('d.m.Y', strtotime('-1 day')); } ?>" class="form-control" />
										</td>
										<td>
										<input type="text" name="featured_end" id="datebook-end" value="<?php if (isset($datebook_get_data['featured_end'])) { echo date("d.m.Y", $datebook_get_data['featured_end']); } else { echo date('d.m.Y', strtotime('+365 days')); } ?>" class="form-control" />
										</td>
									</tr>
								</table>
								<?php echo esc_html__( 'Select a range of dates between which random expiration dates for Featured status will be generated for random profiles.', 'datebook' ); ?>
								</td>
							</tr>

							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-custom-taxonomy" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Type', 'datebook' ); ?></label>
								</th>
								<td>

								<ul>
								<?php
								
								wp_terms_checklist( 0, array(
									'style'	=> '', 'class' => 'custom-select', 'taxonomy' => DATEBOOK_PROFILES_TAX,
								) );
								
								?>
								
								</ul>
								
								<?php echo esc_html__( 'If selected, these items will be assigned to random profiles.', 'datebook' ); ?>

								</td>
							</tr>
							

							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-customfields" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Custom fields', 'datebook' ); ?></label>
								</th>
								<td>
									<ul>
									<li><input type="radio" name="customfields" value="1" checked><?php echo esc_html__( 'Add custom fields to random profiles', 'datebook' ); ?></li>
									<li><input type="radio" name="customfields" value="2"><?php echo esc_html__( 'Add custom fields to all profiles', 'datebook' ); ?></li>
									<li><input type="radio" name="customfields" value="3"><?php echo esc_html__( 'Do not add', 'datebook' ); ?></li>
									</ul>
								</td>
							</tr>
							
							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-names" class="datebook-meta-box-field-label"><?php echo esc_html__( 'Names', 'datebook' ); ?> (<?php echo esc_html__( 'optional', 'datebook' ); ?>)</label>
								</th>
								<td>
									<textarea name="names" cols="50" rows="5" placeholder="<?php echo esc_html__( 'Enter as many names as you want, separated by comma. If empty, the default names from the reserved list will be used.', 'datebook' ); ?> <?php echo esc_html__( 'Example', 'datebook' ); ?>: Alice, Brenda, Delia, Francesca, Joanna"></textarea>
								</td>
							</tr>
							
							<tr class="form-field">
								<th valign="top" scope="row">
									<label for="datebook-aboutme" class="datebook-meta-box-field-label"><?php echo esc_html__( 'About me', 'datebook' ); ?> (<?php echo esc_html__( 'optional', 'datebook' ); ?>)</label>
								</th>
								<td>
									<textarea name="aboutme" cols="50" rows="5" placeholder="<?php echo esc_html__( 'Enter as many texts as you want, separated by double vertical lines ||.', 'datebook' ); ?> <?php echo esc_html__( 'Example', 'datebook' ); ?>: Hi, I would like to make friends || Life is wonderful || Let's chat and see where it leads :) || Surpise me"></textarea>
								</td>
							</tr>

						</tbody>
					</table>

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

					</form>

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

	<?php

	}


	/**
	 * Renders fields in custom profile form
	 *
	 */
	public static function render_field_in($value) {

		$result = $get_user_filled_fields = array();

		if(is_array($value)){

			// if foreign language do not exist, then show title in English (en_US)
			$value['field_items'] = isset($value['field_items_' . DATEBOOK_WPLANG]) ? $value['field_items_' . DATEBOOK_WPLANG] : $value['field_items_en_US'];

			$value['field_items'] = explode('<br />', strtr($value['field_items'], array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')));

			$count_field_items = count($value['field_items']);

			switch ( $value['type'] ) {

				case 'select':
				
					$get_user_filled_fields = rand(1, $count_field_items);

					foreach ($value['field_items'] as $key => $val) {

						$key = $key + 1;

						if(isset($get_user_filled_fields)){
							if( $get_user_filled_fields == $key ) {
								$result = $key;
							}
						}
					} 

				break;

				case 'checkbox':
				
				$key = 0;

					$get_user_filled_fields = rand(1, $count_field_items);

					foreach ($value['field_items'] as $key => $val) {

						$key = $key + 1;

						if(isset($get_user_filled_fields)){
							if( $get_user_filled_fields == $key ) {
								$result[] = $key;
							}
						}
					}

				break;

				case 'radio':
				
				$key = 0;

					$get_user_filled_fields = rand(1, $count_field_items);

					foreach ($value['field_items'] as $key => $val) {
						
						$key = $key + 1;
						
						if(isset($get_user_filled_fields)){
							if( $get_user_filled_fields == $key ) {
								$result = $key;
							}
						}
					}

				break;

			} // end switch
			
		}
		
		return $result;

	}


	/**
	 * Get custom fields
	 *
	 */
	public static function get_custom_fields() {

		global $datebook_reserved_fields;
		
		$result = 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)){

			// Get custom fields
			$get_profile_custom_fields = get_option('datebook_profile_custom_fields');

			// Remove reserved fields from custom fields
			foreach ($get_profile_custom_fields as $key => $value) {
				if(isset($datebook_reserved_fields[$key])){
					unset($get_profile_custom_fields[$key]);
				}
			}

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

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

					$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']]) && isset($get_profile_custom_fields[$column['slug']]['active']) && $get_profile_custom_fields[$column['slug']]['active'] == 1) {

										$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'];

										// Render field
										$result[$column['slug']] = self::render_field_in($custom_field_data);

									}
								}
							}
						}
					}
				}
			}
		}

		return $result;

	}


	// Process a single profile ID (this is an AJAX handler)
	public static function datebook_ajax_process_demo_content() {

		global $wpdb;

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

		$table_countries = strtolower($wpdb->prefix) . 'datebook_countries';

		$men_names = array('Aaron', 'Abel', 'Abner', 'Abraham', 'Adam', 'Adrian', 'Alan', 'Albert', 'Alexander', 'Alfred', 'Algernon', 'Alister', 'Alonso', 'Alphonso', 'Alvin', 'Ambrose', 'Amos', 'Andrew', 'Angus', 'Anthony', 'Archibald', 'Arnold', 'Arthur', 'Augustus', 'Augustine', 'Austin', 'Avery', 'Baldwin', 'Barry', 'Barty', 'Basil', 'Benedict', 'Bennie', 'Bennet', 'Berney', 'Bert', 'Bertram', 'Bertrand', 'Blake', 'Bradford', 'Brad', 'Brandon', 'Brenton', 'Bryan', 'Broderick', 'Bruce', 'Bruno', 'Byron', 'Calvin', 'Cameron', 'Carey', 'Carl', 'Casey', 'Caspar', 'Cedric', 'Charles', 'Chester', 'Christian', 'Christopher', 'Clarence', 'Clark', 'Claude', 'Clayton', 'Clifford', 'Clive', 'Colin', 'Cornelius', 'Craig', 'Curtis', 'Cyrus', 'Dale', 'Daniel', 'Darrell', 'David', 'Dean', 'Dennis', 'Derek', 'Desmond', 'Dexter', 'Dominic', 'Don', 'Donald', 'Donovan', 'Dorian', 'Douglas', 'Drew', 'Dwayne', 'Duke', 'Dunny', 'Dustin', 'Dylan', 'Edgar', 'Edward', 'Edwin', 'Elliot', 'Elton', 'Elvis', 'Emery', 'Emil', 'Emmanuel', 'Eric', 'Ernest', 'Irvin', 'Ethan', 'Eugene', 'Eustace', 'Evan', 'Everard', 'Everett', 'Fabian', 'Felix', 'Ferdinand', 'Fergus', 'Floyd', 'Ford', 'Francis', 'Franklin', 'Frederick', 'Ricky', 'Fred', 'Gabriel', 'Garrett', 'Geoffrey', 'George', 'Gerald', 'Gilbert', 'Glenn', 'Graham', 'Grant', 'Gregory', 'Griffith', 'Harold', 'Harris', 'Harvey', 'Henry', 'Herbert', 'Herman', 'Horace', 'Howard', 'Hugh', 'Hugo', 'Humphrey', 'Ian', 'Ignatius', 'Irvin', 'Isaac', 'Ivor', 'Jack', 'Jacob', 'James', 'Jason', 'Jasper', 'Jefferson', 'Jeffrey', 'Jeremy', 'Jerome', 'Jesse', 'John', 'Jonathan', 'Joseph', 'Joshua', 'Julian', 'Justin', 'Karl', 'Keith', 'Kelly', 'Kelvin', 'Kendall', 'Kendrick', 'Kenneth', 'Kent', 'Kevin', 'Kristopher', 'Kurt', 'Kyle', 'Lambert', 'Lamont', 'Lancelot', 'Laurence', 'Lee', 'Leo', 'Leonard', 'Leopold', 'Leroy', 'Leslie', 'Lester', 'Lewis', 'Lincoln', 'Lindon', 'Lindsay', 'Linus', 'Lionel', 'Lloyd', 'Logan', 'Lonnie', 'Louis', 'Lowell', 'Lucian', 'Luke', 'Luther', 'Lyle', 'Lynn', 'Malcolm', 'Manuel', 'Marion', 'Mark', 'Marshall', 'Martin', 'Marvin', 'Matthew', 'Matthias', 'Maurice', 'Maximilian', 'Maxwell', 'Maynard', 'Melvin', 'Merlin', 'Merrill', 'Michael', 'Miles', 'Milton', 'Mitchell', 'Monroe', 'Montague', 'Montgomery', 'Morgan', 'Mortimer', 'Morton', 'Moses', 'Murray', 'Nathan', 'Neal', 'Nelson', 'Nevill', 'Newton', 'Nicholas', 'Nigel', 'Noah', 'Noel', 'Norbert', 'Norris', 'Norman', 'Norton', 'Oliver', 'Orson', 'Orville', 'Oscar', 'Oswald', 'Owen', 'Patrick', 'Paul', 'Percival', 'Perry', 'Peter', 'Philip', 'Quentin', 'Quincy', 'Ralph', 'Randall', 'Randolph', 'Raphael', 'Raymond', 'Reginald', 'Rene', 'Reuben', 'Reynold', 'Richard', 'Rick', 'Robert', 'Roderic', 'Rodney', 'Roger', 'Roland', 'Rolph', 'Ronald', 'Ron', 'Roscoe', 'Ross', 'Roy', 'Rudolph', 'Russell', 'Ryan', 'Samson', 'Samuel', 'Sanford', 'Saul', 'Scott', 'Sean', 'Sebastian', 'Seth', 'Seymour', 'Shannon', 'Sheldon', 'Shelley', 'Sidney', 'Silas', 'Silvester', 'Simeon', 'Simon', 'Solomon', 'Stacy', 'Stanley', 'Stephen', 'Stuart,Terence', 'Thaddeus', 'Theodore', 'Timothy', 'Thomas', 'Tobias', 'Todd', 'Tracy', 'Travis', 'Tristram', 'Troy', 'Tyler', 'Ulysses', 'Uriah', 'Valentine', 'Valerian', 'Vernon', 'Victor', 'Vincent', 'Virgil', 'Wallace', 'Walter', 'Warren', 'Wayne', 'Wesley', 'Wilbur', 'Wiley', 'Wilfred', 'Willard', 'William', 'Willis', 'Wilson', 'Winfred', 'Winston', 'Woodrow', 'Xavier', 'Zacky');


		$women_names = array('Abigail', 'Ada', 'Adelaide', 'Adele', 'Adeline', 'Adriana', 'Agatha', 'Agnes', 'Aileen', 'Alberta', 'Alexandra', 'Alexis', 'Alfreda', 'Alice', 'Alison', 'Althea', 'Amabel', 'Amanda', 'Amber', 'Amelia', 'Amy', 'Anastasia', 'Andrea', 'Angela', 'Anita', 'Anna', 'Annabel', 'Annette', 'Antoinette', 'Antonia', 'April', 'Arabella', 'Arlene', 'Ashley', 'Audrey', 'Augusta', 'Augustina', 'Aurora', 'Barbara', 'Beatrice', 'Belinda', 'Belle', 'Berenice', 'Bertha', 'Betty', 'Beverly', 'Blanche', 'Bonnie', 'Brenda', 'Brett', 'Bridget', 'Brittany', 'Camille', 'Candace', 'Caren', 'Carla', 'Carlotta', 'Carmen', 'Carol', 'Caroline', 'Cassandra', 'Catherine', 'Cecilia', 'Celeste', 'Celestine', 'Celia', 'Celine', 'Charity', 'Charlotte', 'Cheryl', 'Christine', 'Clara', 'Clarice', 'Claudia', 'Clemency', 'Clementine', 'Colleen', 'Constance', 'Cora', 'Cordelia', 'Corinna', 'Cornelia', 'Courtney', 'Crystal', 'Cynthia', 'Daisy', 'Danielle', 'Daphne', 'Darlene', 'Deborah', 'Delia', 'Della', 'Denise', 'Diana', 'Dina', 'Dolores', 'Dominique', 'Donna', 'Dora', 'Doreen', 'Doris', 'Dorothy', 'Edith', 'Edna', 'Elaine', 'Eleanor', 'Elisa', 'Elizabeth', 'Ella', 'Ellen', 'Eloise', 'Elsie', 'Elvira', 'Emily', 'Emma', 'Erica', 'Erin', 'Ernestine', 'Estelle', 'Esther', 'Ethel', 'Etta', 'Eugenia', 'Eulalia', 'Eunice', 'Euphemia', 'Eustacia', 'Eva', 'Eveline', 'Evangeline', 'Faith', 'Felicia', 'Florence', 'Frances', 'Francesca', 'Francine', 'Frederica', 'Gabrielle', 'Genevieve', 'Georgina', 'Geraldine', 'Gertrude', 'Gillian', 'Gina', 'Gladys', 'Glenda', 'Gloria', 'Grace', 'Gwendolen', 'Hannah', 'Harriet', 'Hazel', 'Heather', 'Helen', 'Henrietta', 'Hester', 'Hillary', 'Hilda', 'Holly', 'Hope', 'Ida', 'Imogen', 'Irene', 'Iris', 'Irma', 'Isabel', 'Jacqueline', 'Jane', 'Janet', 'Janice', 'Jean', 'Jeannette', 'Jemima', 'Jennifer', 'Jenny', 'Jessica', 'Jill', 'Joanna', 'Joceline', 'Josephine', 'Joyce', 'Judith', 'Julia', 'Julianne', 'Juliet', 'June', 'Justina', 'Karen', 'Katherine', 'Kathleen', 'Kelly', 'Kimberly', 'Kristina', 'Laura', 'Laureen', 'Laurel', 'Laverne', 'Lavinia', 'Leah', 'Leila', 'Lena', 'Leona', 'Leonora', 'Leslie', 'Leticia', 'Lillian', 'Lily', 'Linda', 'Lindsay', 'Lisa', 'Lois', 'Lona', 'Lora', 'Lorena', 'Lorna', 'Loretta', 'Lorinda', 'Lorraine', 'Lottie', 'Louise', 'Lucille', 'Lucinda', 'Lucy', 'Lydia', 'Lynn', 'Mabel', 'Madeline', 'Magdaline', 'Marcia', 'Margaret', 'Marianne', 'Marilyn', 'Maribel', 'Marietta', 'Marina', 'Marion', 'Marjorie', 'Martha', 'Mary', 'Mary', 'Matilda', 'Maud', 'Maureen', 'Maxine', 'Megan', 'Melanie', 'Melinda', 'Melissa', 'Mercedes', 'Meredith', 'Michelle', 'Mildred', 'Millicent', 'Minnie', 'Miranda', 'Miriam', 'Molly', 'Mona', 'Monica', 'Morgan', 'Muriel', 'Myra', 'Nadine', 'Natalie', 'Nancy', 'Nell', 'Nettie', 'Nicki', 'Nicole', 'Nina', 'Noel', 'Nora', 'Noreen', 'Norma', 'Octavia', 'Olivia', 'Ophelia', 'Pamela', 'Pansy', 'Patricia', 'Paula', 'Pearl', 'Peggy', 'Penelope', 'Phoebe', 'Phyllis', 'Polly', 'Priscilla', 'Prudence', 'Rachel', 'Raquel', 'Rebecca', 'Regina', 'Renata', 'Renee', 'Rhoda', 'Rhonda', 'Roberta', 'Rose', 'Rosabel', 'Rosalie', 'Rosaline', 'Rosalinda', 'Rosanna', 'Rosemary', 'Rowena', 'Roxanna', 'Ruby', 'Ruth', 'Sabrina', 'Samantha', 'Sarah', 'Selina', 'Selma', 'Shannon', 'Sharon', 'Shauna', 'Sheila', 'Shelley', 'Shirley', 'Sibyl', 'Sidney', 'Sonia', 'Sophia', 'Stacy', 'Stephanie', 'Stella', 'Susan', 'Sylvia', 'Tabitha', 'Tamara', 'Tanya', 'Teresa', 'Theodora', 'Thelma', 'Tiffany', 'Tina', 'Tracy', 'Ulrica', 'Una', 'Ursula', 'Valentina', 'Valerie', 'Vanessa', 'Vera', 'Verna', 'Veronica', 'Victoria', 'Vida', 'Viola', 'Violetta', 'Virginia', 'Vivian', 'Wanda', 'Wendy', 'Wilhelmina', 'Winifred', 'Yolanda', 'Yvonne', 'Yvette', 'Zoey');


		$datebook_get_data = $profile_field_data = array();

		$user_datas = get_option('datebook_demo_profiles_options');

		$gender = isset($user_datas['gender']) && $user_datas['gender'] > 0 ? $user_datas['gender'] : rand(1, 2);

		$profile_name_array = isset($user_datas['names']) && !empty($user_datas['names']) ? array_filter(explode(',', $user_datas['names'])) : '';

		if(isset($profile_name_array) && is_array($profile_name_array) && !empty($profile_name_array)){
			$profile_name = $profile_name_array[array_rand($profile_name_array)];
		} else {
			$profile_name = $gender == 1 ? $women_names[array_rand($women_names)] : $men_names[array_rand($men_names)];
		}

		$pre_emailaddress = strtolower($profile_name).time();
		$emailaddress = $pre_emailaddress . '@website.com';

		$userdata = array(
			'user_login'	=> $pre_emailaddress,
			'user_email'	=> $emailaddress,
			'user_pass'	 => $pre_emailaddress,
			'display_name'  => $profile_name
		);

		$current_user_id = wp_insert_user($userdata);

		$aboutyou_array = isset($user_datas['aboutme']) && !empty($user_datas['aboutme']) ? array_filter(explode('||', $user_datas['aboutme'])) : '';

		if(isset($aboutyou_array) && is_array($aboutyou_array) && !empty($aboutyou_array)){
			$aboutyou = $aboutyou_array[array_rand($aboutyou_array)];
		} else {
			$aboutyou = '';
		}

		$registration_start = isset($user_datas['registration_start']) ? strtotime($user_datas['registration_start']) : strtotime('-1 year');
		$registration_end = isset($user_datas['registration_end']) ? strtotime($user_datas['registration_end']) : strtotime(date('Y-m-d H:i:s'));

		$registration_date = date('Y-m-d H:i:s', rand($registration_start, $registration_end));

		// Create post object
		$post_profile = array(
			'post_author' => $current_user_id,
			'post_date' => $registration_date,
			'post_title' => $profile_name,
			'post_content' => $aboutyou,
			'post_name' => time(),
			'post_status' => 'publish',
			'post_type' => DATEBOOK_POST_TYPE,
			'ping_status' => 'closed'
		);
		// Insert the post into the database
		$profile_id = wp_insert_post( $post_profile );

		// Countries
		$country_title = $region_title = $city_title = '';

		if(isset($user_datas['country']) && $user_datas['country'] > 0){

			$countries = isset($user_datas['country']) && $user_datas['country'] > 0 ? $user_datas['country'] : 0;

			if(isset($user_datas['city']) && is_array($user_datas['city']) && count($user_datas['city']) > 0) {
				$locations = $user_datas['city'][array_rand($user_datas['city'])];
				$deep_level = 1;
			} else if(isset($user_datas['city']) && !is_array($user_datas['city']) && $user_datas['city'] > 0) {
				$locations = $user_datas['city'];
				$deep_level = 1;
			} else if(isset($user_datas['region']) && is_array($user_datas['region']) && count($user_datas['region']) > 0) {
				$locations = $user_datas['region'][array_rand($user_datas['region'])];
				$deep_level = 2;
			} else if(isset($user_datas['region']) && !is_array($user_datas['region']) && $user_datas['region'] > 0) {
				$locations = $user_datas['region'];
				$deep_level = 2;
			} else if($countries > 0) {
				$locations = $countries;
				$deep_level = 3;
			}
			
			$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $locations, $deep_level );

			$country_id = isset($term_data->country_id) ? $term_data->country_id : 0;
			$region_id = isset($term_data->region_id) ? $term_data->region_id : 0;
			$city_id = isset($term_data->city_id) ? $term_data->city_id : 0;

			$country_title = isset($term_data->country) ? $term_data->country : '';
			$region_title = isset($term_data->region) ? $term_data->region : '';
			$city_title = isset($term_data->city) ? $term_data->city : '';

			$datebook_get_data['country'] = $country_id;
			update_post_meta($profile_id, 'country', $country_id);

			$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $country_id) );

			if($region_id == 0){

				$regions_array = array();

				// Set region
				$query = "SELECT * FROM " . $table_countries . " WHERE parent_id = %d";
				$get_prepared = $wpdb->prepare($query, $country_id);
				$get_regions_only = $wpdb->get_results($get_prepared, ARRAY_A);
				
				if(isset($get_regions_only) && is_array($get_regions_only) && !empty($get_regions_only)){
					foreach($get_regions_only as $cat){
						$regions_array[] = $cat['id'];
					}

					$k = array_rand($regions_array);
					$region_id = $regions_array[$k];

					$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $region_id) );
					update_post_meta($profile_id, 'region', $region_id);
					$datebook_get_data['region'] = $region_id;

					// Set city
					if($region_id > 0 && $city_id == 0){

						$cities_array = array();

						$query = "SELECT * FROM " . $table_countries . " WHERE parent_id = %d";
						$get_prepared = $wpdb->prepare($query, $region_id);
						$get_regions_only = $wpdb->get_results($get_prepared, ARRAY_A);

						if(isset($get_regions_only) && is_array($get_regions_only) && !empty($get_regions_only)){
							foreach($get_regions_only as $cat){
								$cities_array[] = $cat['id'];
							}

							$k = array_rand($cities_array);
							$city_id = $cities_array[$k];

							$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $city_id) );
							update_post_meta($profile_id, 'city', $city_id);
							$datebook_get_data['city'] = $city_id;
						}
					}
				}

			} else if($region_id > 0){
				$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $region_id) );
				update_post_meta($profile_id, 'region', $region_id);
				$datebook_get_data['region'] = $region_id;
				
				// Set city
				if($city_id == 0){

					$cities_array = array();

					$query = "SELECT * FROM " . $table_countries . " WHERE parent_id = %d";
					$get_prepared = $wpdb->prepare($query, $region_id);
					$get_regions_only = $wpdb->get_results($get_prepared, ARRAY_A);

					if(isset($get_regions_only) && is_array($get_regions_only) && !empty($get_regions_only)){
						foreach($get_regions_only as $cat){
							$cities_array[] = $cat['id'];
						}

						$k = array_rand($cities_array);
						$city_id = $cities_array[$k];

						$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $city_id) );
						update_post_meta($profile_id, 'city', $city_id);
						$datebook_get_data['city'] = $city_id;
					}
				}
			}

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


		$date_birth_start = isset($user_datas['date_birth_start']) ? $user_datas['date_birth_start'] : date('Y', strtotime('-80 years'));
		$date_birth_end = isset($user_datas['date_birth_end']) ? $user_datas['date_birth_end'] : date('Y', strtotime('-18 years'));

		$dateyear = rand($date_birth_start, $date_birth_end);
		$datemonth = rand(01, 12);
		$dateday = rand(01, 28);

		update_post_meta($profile_id, 'birthday', sanitize_text_field($dateyear . '-' . $datemonth . '-' . $dateday));


		$sexualorientation_array = isset($user_datas['sexualorientation']) ? $user_datas['sexualorientation'] : '';

		if(is_array($sexualorientation_array) && count($sexualorientation_array) > 0) {
			$sexualorientation = $sexualorientation_array[array_rand($sexualorientation_array)];
		} else if(!is_array($sexualorientation_array) && $sexualorientation_array > 0) {
			$sexualorientation = $sexualorientation_array;
		} else {
			$sexualorientation = 0;
		}

		update_post_meta($profile_id, 'sexualorientation', absint($sexualorientation));

		update_post_meta($profile_id, 'family_status', 'single');

		// Add Top
		$top_start = isset($user_datas['top_start']) ? strtotime($user_datas['top_start']) : '';
		$top_end = isset($user_datas['top_end']) ? strtotime($user_datas['top_end']) : '';
		$top_date = rand($top_start, $top_end);
		if($top_start > 0 && $top_end > 0 && $top_date > 0) {
			update_post_meta($profile_id, 'topad', '1');
			update_post_meta($profile_id, 'topad_ends', $top_date);
			$datebook_get_data['topad'] = 1;
		}

		// Add Featured
		$featured_start = isset($user_datas['featured_start']) ? strtotime($user_datas['featured_start']) : '';
		$featured_end = isset($user_datas['featured_end']) ? strtotime($user_datas['featured_end']) : '';
		$featured_date = rand($featured_start, $featured_end);
		if($featured_start > 0 && $featured_end > 0 && $top_date > 0) {
			update_post_meta($profile_id, 'featured', '1');
			update_post_meta($profile_id, 'featured_ends', $featured_date);
			$datebook_get_data['featured'] = 1;
		}


		$profiletype_array = isset($user_datas['tax_input']['profiletype']) ? $user_datas['tax_input']['profiletype'] : '';

		if(is_array($profiletype_array) && count($profiletype_array) > 0) {
			$profiletype = (int)$profiletype_array[array_rand($profiletype_array)];
		} else if(!is_array($profiletype_array) && $profiletype_array > 0) {
			$profiletype = (int)$profiletype_array;
		} else {
			$profiletype = 0;
		}

		if($profiletype > 0){
			wp_set_object_terms( $profile_id, $profiletype, DATEBOOK_PROFILES_TAX );
		}


		$online_status =  mktime(0, 0, 0, date("m"), date("d")-rand(1, 20), date("Y"));
		update_user_meta( $current_user_id, 'online_status', sanitize_text_field($online_status) );
		update_user_meta( $current_user_id, 'profile_type', DATEBOOK_POST_TYPE );
		update_user_meta( $current_user_id, 'profile_postid', absint($profile_id) );

				
		$datebook_get_data['birthday'] = $dateyear . '-' . $datemonth . '-' . $dateday;
		$datebook_get_data['dateyear'] = $dateyear;
		$datebook_get_data['datemonth'] = $datemonth;
		$datebook_get_data['dateday'] = $dateday;
		
		update_post_meta($profile_id, 'gender', absint($gender));
		$datebook_get_data['gender'] = $gender;

		$datebook_get_data['sexualorientation'] = $sexualorientation;
		$datebook_get_data['family_status'] = 'single';
		$datebook_get_data['upload_folder'] = time() . rand(1,999);
		$datebook_get_data['profile_type'] = DATEBOOK_POST_TYPE;
		$datebook_get_data['profile_postid'] = $profile_id;
		$datebook_get_data['online_status'] = $online_status;
		//$datebook_get_data['phone'] = "+" . rand(1234567890, 9234567890);
		//$datebook_get_data['wishtravel'] = rand(0, 1);
		//$datebook_get_data['wishtraveltext'] = 'Donec consectetur libero ut tortor condimentum eu egestas est viverra. Sed eget turpis dui, sed auctor nisi. Fusce suscipit risus sed tortor mattis sollicitudin. Vivamus dictum, nisl sed aliquet sodales, nisi ipsum interdum metus.';
		$datebook_get_data['ip'] = '';
		$datebook_get_data['hostname'] = '';


		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;

		}


		// get demo profile fields
		$customfields = isset($user_datas['customfields']) ? $user_datas['customfields'] : 3;

		if($customfields < 3){

			$customfields_random = $customfields == 1 ? rand(0, 1) : 1;

			if($customfields_random == 1){

				$get_custom_fields = self::get_custom_fields();

				if (is_array($get_custom_fields) && !empty($get_custom_fields)) {

					// Insert member filled custom fields
					foreach($get_custom_fields as $key => $value) {

						if (is_array($value)) {
							$value = array_map( 'sanitize_text_field', $value );
						} else {
							$value = sanitize_text_field( $value );
						}

						$profile_field_data['edit_form'][sanitize_key($key)] = $value;
						
					}
				}
			}
		}

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


		// Insert profiles and cities data
		$response =  array('success' => sprintf(esc_html__( 'Profile ID: %1$s (%2$s) created', 'datebook' ), $current_user_id, $profile_name . ', ' . $datebook_get_data['birthday'] . ', ' . $city_title . ' ' . $region_title . ' ' . $country_title));
		
		


		// Add a profile to the created profiles list
		$datebook_created_profiles = get_option('datebook_created_profiles');

		if (($key = array_search($current_user_id, $datebook_created_profiles)) !== false) {
			unset($datebook_created_profiles[$key]);
		}

		update_option('datebook_created_profiles', $datebook_created_profiles);


		wp_send_json($response);

		die();

	}
	

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

		// all demo profiles are now created so we don't need to run this again
		update_option('datebook_all_demo_profiles_created', 'yes');

		die();
		
	}

}

DateBook_Demo_Content_Installer::init();