<?php
/**
 * DateBook Countries Installer
 * Inserts countries, regions and cities
 *
 * @class DateBook_Countries_Installer
 * @author Pagick Themes
 * @since 1.6
 */

class DateBook_Countries_Installer {


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

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'datebook_install_script' ) );
		add_action( 'wp_ajax_datebookcountriestool', array( __CLASS__, 'datebook_ajax_process_country' ) );
		add_action( 'wp_ajax_datebookcountriesinserted', array( __CLASS__, 'datebook_ajax_countries_inserted' ) );

		add_action( 'wp_ajax_datebookcountprofiles', array( __CLASS__, 'correct_profiles_quantity' ) );

	}


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

	}


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

		global $wpdb, $allowedposttags;
		
		$table_name = strtolower($wpdb->prefix) . 'datebook_countries';
		
		?>

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

			<h1><?php echo esc_html__('Countries Installer', 'datebook'); ?></h1>
			
			<hr class="wp-header-end">

			<?php if (empty($_POST['datebook-count-profiles-countries'])) { ?>
            
            <div class="welcome-panel datebook-dummy-notify-box">
				<div class="welcome-panel-content">
					
					<h2><?php echo esc_html__('Start installing', 'datebook'); ?></h2>
		
					<p><?php echo esc_html__('Press the START button to install all countries, regions and cities that are necessary for the DateBook theme to function properly.', '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 installation proccess takes about 3-5 minutes.', 'datebook'); ?></p>

					<?php

					// If the button was clicked
					if (!empty($_POST['datebook_reinstall_countries'])) {

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

						if ( $check_countries_table == $table_name ) {
								
								// Insert countries and cities data
								include(DATEBOOK_DIR . 'framework/sample/countries/all_countries.php');

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

									$jsondata = unserialize(urldecode($content));

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

										foreach($jsondata as $country_key => $country_value){

											// insert items for DateBook Taxonomy method
											$wpdb->insert($table_name, array(
												'name' => $country_value['name'],
												'slug' => $country_value['slug'],
												'parent_id' => 0,
												'level' => 0,
												'counter' => 0,
												'active' => 1
											));
										}
									}
								}
							}


							if ($country_datas = $wpdb->get_results($wpdb->prepare("SELECT id FROM $table_name WHERE parent_id = %d ORDER BY id ASC", 0 ) ) ) {

								// 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 success">';

								echo '<p>' . esc_html__( 'All countries have been installed. Now, click the Start button below to start the installation.', 'datebook' ) . '</p>';

								echo '</div>';

								echo '</div>';

							}
							
							// Generate the list of IDs
							$ids = array();
							foreach ( $country_datas as $key => $country_data ){
								$ids[] = $country_data->id;
							}

							$ids = implode( ',', $ids );

						
						} else if ( ! empty( $_POST['datebook-install-countries'] ) || ! empty( $_REQUEST['ids'] ) ) {

						// Form nonce check
						check_admin_referer( 'datebook-install-countries' );

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

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

						} else {

							// Uncomment this to recreate coutries MySQL table if country titles displayed wrongly or not displayed
							//define('DB_CHARSET', 'utf8');
							//$wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );

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

							if ( $check_countries_table != $table_name ) {

								$collate = '';

								if ( $wpdb->has_cap( 'collation' ) ) {
									if ( ! empty($wpdb->charset ) ) {
										$collate .= "DEFAULT CHARACTER SET $wpdb->charset";
									}
									if ( ! empty($wpdb->collate ) ) {
										$collate .= " COLLATE $wpdb->collate";
									}
								}

								$sql = "CREATE TABLE {$table_name} (
									id int(11) NOT NULL AUTO_INCREMENT,
									name LONGTEXT NULL,
									slug VARCHAR(190) NOT NULL,
									translation LONGTEXT NULL,
									parent_id int(11) NOT NULL,
									level int(11) NOT NULL,
									counter int(11) NOT NULL,
									class_counter int(11) NOT NULL,
									tour_counter int(11) NOT NULL,
									active int(11) NOT NULL,
									INDEX (slug),
									PRIMARY KEY  (id)
								) " .  $collate . ";";

								require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
								dbDelta($sql);

								// Uncomment if table was created with wrong charset
								//$wpdb->query("ALTER TABLE {$table_name} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");

								// Insert countries and cities data
								include(DATEBOOK_DIR . 'framework/sample/countries/all_countries.php');

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

									$jsondata = unserialize(urldecode($content));

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

										foreach($jsondata as $country_key => $country_value){

											// insert items for DateBook Taxonomy method
											$wpdb->insert($table_name, array(
												'name' => $country_value['name'],
												'slug' => $country_value['slug'],
												'parent_id' => 0,
												'level' => 0,
												'counter' => 0,
												'active' => 1
											));
										}
									}
								}
							}


							if ( $check_countries_table != $table_name ) {

								echo '<div id="message" class="updated error">';
								echo '<p>' . esc_html__( 'Countries table (MySQL) is not created in your database yet.', 'datebook' ) . '</p>';
								echo '<p>' . esc_html__( 'Try to run this tool again.', 'datebook' ) . '</p>';
								echo '</div></div>';

								return;

							} else if ( ! $country_datas = $wpdb->get_results($wpdb->prepare("SELECT id FROM $table_name WHERE parent_id = %d ORDER BY id ASC", 0 ) ) ) {

								// 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 countries have been found in the database. No worries! Click the Reinstall all countries button below to start the installation.', 'datebook' ) . '</p>';

								echo '</div>';

								echo '<form method="post" action="">';

								wp_nonce_field('datebook-reinstall-countries');

								echo '<p><input id="datebook" type="submit" class="button button-primary button-hero hide-if-no-js" name="datebook_reinstall_countries" value="' . esc_html__( 'Reinstall all countries', 'datebook' ) . '" /></p>';

								echo '</form>';

								echo '</div>';

								return;

							}
							
							// Generate the list of IDs
							$ids = array();
							foreach ( $country_datas as $key => $country_data ){
								$ids[] = $country_data->id;
							}

							$ids = implode( ',', $ids );

						}


						$message_failures = sprintf(esc_html__( 'Almost success! %1$s countries have been successfully installed. But %2$s countries are not installed. To try to run this tool again.', 'datebook' ),
						'" + datebooktool_successes + "', 
						'" + datebooktool_errors + "' 
						);

						$message_success = sprintf( esc_html__( 'All %1$s countries have been successfully installed.', 'datebook' ), '" + datebooktool_successes + "' );
						
						$count = count( $country_datas );
						
					?>

					<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__( 'Total Countries:', 'datebook' ); ?> <span style="width:100%;padding: 2%;font-size: 24px"> <?php printf( '%s', $count ); ?> </span></td>
							<td><?php echo esc_html__( 'Countries inserted:', '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__( 'Insert 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: "datebookcountriesinserted" },
									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: "datebookcountriestool", 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 installing 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() );

						});
						// ]]>

						');

						?>

				<?php } else { ?>

					<noscript>
						<p><?php echo esc_html__( 'You must enable Javascript in order to proceed!', 'datebook' ) ?></p>
					</noscript>
					
					<form method="post" action="">

						<?php wp_nonce_field('datebook-install-countries') ?>

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

					</form>

				<?php } ?>

				</div>
			</div>
            
            <?php } ?>
            
			<?php if (empty($_POST['datebook-install-countries'])){ ?>
            
            <div class="welcome-panel datebook-dummy-notify-box">
				<div class="welcome-panel-content">
		
					<h2><?php echo esc_html__('Recount the quantity of profiles and tours in Countries', 'datebook'); ?></h2>

					<p><?php echo esc_html__('In case, the quantity of profiles and tours in countries were wrongly counted, then you can fix them. Click on the “Recount” button to start recounting.', 'datebook'); ?></p>

					<?php
					
					// If the button was clicked
					if ( ! empty( $_POST['datebook-count-profiles-countries'] ) || ! empty( $_REQUEST['ids'] ) ) {

						// Form nonce check
						check_admin_referer( 'datebook-count-profiles-countries' );

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

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

						} else {
							
							$check_countries_table = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_name));

							if ( $check_countries_table != $table_name ) {

								$collate = '';

								if ( $wpdb->has_cap( 'collation' ) ) {
									if ( ! empty($wpdb->charset ) ) {
										$collate .= "DEFAULT CHARACTER SET $wpdb->charset";
									}
									if ( ! empty($wpdb->collate ) ) {
										$collate .= " COLLATE $wpdb->collate";
									}
								}

								$sql = "CREATE TABLE " . $table_name . " (
									id int(11) NOT NULL AUTO_INCREMENT,
									name LONGTEXT NULL,
									slug VARCHAR(190) NOT NULL,
									translation LONGTEXT NULL,
									parent_id int(11) NOT NULL,
									level int(11) NOT NULL,
									counter int(11) NOT NULL,
									class_counter int(11) NOT NULL,
									tour_counter int(11) NOT NULL,
									active int(11) NOT NULL,
									INDEX (slug),
									PRIMARY KEY  (id)
								) " .  $collate . ";";
								

								require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
								dbDelta($sql);

								// Insert countries and cities data
								include(DATEBOOK_DIR . 'framework/sample/countries/all_countries.php');

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

									$jsondata = unserialize(urldecode($content));

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

										foreach($jsondata as $country_key => $country_value){

											// insert items for DateBook Taxonomy method
											$wpdb->insert($table_name, array(
												'name' => $country_value['name'],
												'slug' => $country_value['slug'],
												'parent_id' => 0,
												'level' => 0,
												'counter' => 0,
												'active' => 1
											));
										}
									}
								}
							}
							

							if ( $check_countries_table != $table_name ) {
								
								echo '<div id="message" class="updated error">';
								
								echo '<p>' . esc_html__( "Countries table (MySQL) is not created in your database yet.", 'datebook' ) . '</p>';
								echo '<p>' . esc_html__( "Try to run this tool again.", 'datebook' ) . '</p>';
								
								echo '</div>';

								return;

							} else if ( ! $country_datas = $wpdb->get_results($wpdb->prepare("SELECT id FROM $table_name WHERE parent_id = %d ORDER BY id ASC", 0 ) ) ) {

								// 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 countries have been found in the database. No worries! Click the Reinstall all countries button below to start the installation.", 'datebook' ) . '</p>';

								echo '</div>';
								
								echo '<form method="post" action="">';

								wp_nonce_field('datebook-reinstall-countries');

								echo '<p><input id="datebook" type="submit" class="button button-primary button-hero hide-if-no-js" name="datebook_reinstall_countries" value="' . esc_html__( 'Reinstall all countries', 'datebook' ) . '" /></p>';

								echo '</form>';

								return;

							}
							
							// Generate the list of IDs
							$ids = array();
							foreach ( $country_datas as $key => $country_data ){
								$ids[] = $country_data->id;
							}

							$ids = implode( ',', $ids );

						}

						$message_failures = sprintf(esc_html__( 'Almost success! %1$s countries have been successfully recounted. But %2$s countries are not counted. To try to run this tool again.', 'datebook' ),
						'" + datebooktool_successes + "', 
						'" + datebooktool_errors + "' 
						);

						$message_success = sprintf( esc_html__( 'All %1$s countries have been successfully recounted.', 'datebook' ), '" + datebooktool_successes + "' );
						
						$count = count( $country_datas );
						
					?>

					<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 Countries:', 'datebook' ); ?> <span style="width:100%;padding: 2%;font-size: 24px"> <?php printf( '%s', $count ); ?> </span></td>
							<td><?php echo esc_html__( 'Countries counted:', '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__( 'Count 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: "datebookcountriesinserted" },
									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: "datebookcountprofiles", 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 installing 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() );

						});
						// ]]>

						');

						?>

				<?php } else { ?>

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

						<?php wp_nonce_field('datebook-count-profiles-countries') ?>

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

					</form>

				<?php } ?>

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

		</div>

	<?php

	}


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

		global $wpdb;

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

		$country_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . $table_name . "` WHERE `id` = %d", $id));

		$country_slug = $country_data->slug;

		$datebook_get_data = maybe_unserialize($country_data->name );

		if(is_array($datebook_get_data)){

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

			$country_data->name = $datebook_get_data;

		} else {

			$country_data->name = $datebook_get_data;

		}

		if ( !$country_data || $country_data->parent_id != '0' ){

			die( json_encode( array( 'error' => sprintf( esc_html__( 'Failed inserting: %s is an invalid country ID.', 'datebook' ), esc_html( $country_data->name ) ) ) ) );

		}


		// Insert countries and cities data
		include(DATEBOOK_DIR . 'framework/sample/countries/' . $country_slug . '.php');

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

			$jsondata = unserialize(urldecode($content));

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

				// Update country
				$wpdb->update($table_name, array(
					'name' => $jsondata['name']
				), array('slug' => $jsondata['slug']));
				
				$count_regions = $count_cities = 0;

				// Update regions
				foreach($jsondata['regions'] as $region => $region_value){

					$count_regions++;

					if($region_value['level'] == 2) {

						$mysql_insert_id_region = $country_data->id;

					} else if($region_value['level'] == 1) {

						// insert items for DateBook Taxonomy method
						$if_taxonomy_exists = $wpdb->get_row($wpdb->prepare("SELECT id FROM " . $table_name . " WHERE slug = %s AND parent_id = %d AND level = %d", $region_value['slug'], $country_data->id, 1));

						if (!empty($if_taxonomy_exists)) {

							$wpdb->update ( $table_name, array(
								'name' => $region_value['name']
							), array('id' => $if_taxonomy_exists->id));

							$mysql_insert_id_region = $if_taxonomy_exists->id;

						} else {

							$wpdb->insert($table_name, array(
								'name' => $region_value['name'],
								'slug' => $region_value['slug'],
								'parent_id' => $country_data->id,
								'level' => 1,
								'counter' => 0,
								'active' => 1
				   			));

							$mysql_insert_id_region = $wpdb->insert_id;
					
						}
					}

					// Update cities
					foreach($region_value['cities'] as $city_key => $city_value){

						$count_cities++;

						// insert items for DateBook Taxonomy method
						$if_taxonomy_exists = $wpdb->get_row($wpdb->prepare("SELECT id FROM " . $table_name . " WHERE slug = %s AND parent_id = %d AND level = %d", $city_value['slug'], $mysql_insert_id_region, 2));

						if (!empty($if_taxonomy_exists)) {

							$wpdb->update($table_name, array(
								'name' => $city_value['name']
							), array('id' => $if_taxonomy_exists->id));

						} else {

							$wpdb->insert($table_name, array(
					    	    'name' => $city_value['name'],
								'slug' => $city_value['slug'],
								'parent_id' => $mysql_insert_id_region,
								'level' => 2,
								'counter' => 0,
								'active' => 1
							));

						}
					}
				}

				$response =  array('success' => sprintf( esc_html__( '&quot;%1$s&quot; was successfully installed in %2$s seconds.', 'datebook' ), esc_html( $country_data->name . ' (' . $count_regions . ' regions and ' . $count_cities . ' cities)'), absint(round(timer_stop())) ) );

				wp_send_json($response);

				die();
		
			}
		}

	}
	

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

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

		// Countries with translation inserted
		update_option('datebook_upgrade_7', 'yes');
		update_option('datebook_upgrade_11', 'yes');

		die();
		
	}


	// Process counting profiles in countries
	public static function correct_profiles_quantity() {

		global $wpdb;

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

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

			$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix
			
			$country_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . $table_name . "` WHERE `id` = %d", $country_id));

			$datebook_get_data = maybe_unserialize( $country_data->name );

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

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

				$country_data->name = $datebook_get_data;

			} else {

				$country_data->name = $datebook_get_data;

			}

			$count_profiles_all = $count_profiles_regions = $count_profiles_cities = 0;

			// 1. Count profiles in countries
			$country_query_args = array(
				'post_type'  => DATEBOOK_POST_TYPE,
				'post_status' => 'publish',
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'country',
						'value' => $country_id,
					),
				)
			);

			$country_posts = new WP_Query( $country_query_args );
			$count_profiles_country = absint($country_posts->found_posts);

			// Update number of profiles in country
			$wpdb->query( $wpdb->prepare("UPDATE `" . $table_name . "` SET counter = %d WHERE id = %d", $count_profiles_country, $country_id) );
			
			/////////////////////////////////////////////////////

			// 1. Count countries in tours
			$tour_country_query_args = array(
				'post_type'  => DATEBOOK_TOUR_TYPE,
				'post_status' => 'publish',
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'country',
						'value' => $country_id,
					),
				)
			);

			$tour_country_posts = new WP_Query($tour_country_query_args);
			$count_tour_country = absint($tour_country_posts->found_posts);

			// Update number of tours in country
			$wpdb->query( $wpdb->prepare("UPDATE `" . $table_name . "` SET tour_counter = %d WHERE id = %d", $count_tour_country, $country_id) );
			
			/////////////////////////////////////////////////////

			// 2. Count regions in profiles
			$query = "SELECT * FROM `" . $table_name . "` WHERE parent_id = %d";
			$get_regions_only = $wpdb->get_results($wpdb->prepare($query, $country_id), ARRAY_A);

			// Get all regions
			if (is_array($get_regions_only) && !empty($get_regions_only)) {

				foreach( $get_regions_only as $cat ){

					// 2. Count regions in profiles
					$region_query_args = array(
						'post_type'  => DATEBOOK_POST_TYPE,
						'post_status' => 'publish',
						'posts_per_page' => -1,
						'meta_query' => array(
							array(
								'key' => 'region',
								'value' => $cat['id'],
							),
						)
					);

					$region_posts = new WP_Query( $region_query_args );
					$count_profiles_region = absint($region_posts->found_posts);
					
					$count_profiles_regions += $count_profiles_region;

					// counts in regions
					$wpdb->query( $wpdb->prepare("UPDATE `" . $table_name . "` SET counter = %d WHERE id = %d", $count_profiles_region, $cat['id']) );

					// Count cities
					$query = "SELECT * FROM `" . $table_name . "` WHERE parent_id = %d";
					$get_cities_only = $wpdb->get_results($wpdb->prepare($query, $cat['id']), ARRAY_A);

					// Get all cities
					if (is_array($get_cities_only) && !empty($get_cities_only)) {

						foreach( $get_cities_only as $cat ){

							// Count regions
							$city_query_args = array(
								'post_type'  => DATEBOOK_POST_TYPE,
								'post_status' => 'publish',
								'posts_per_page' => -1,
								'meta_query' => array(
									array(
										'key' => 'city',
										'value' => $cat['id'],
									),
								)
							);

							$city_posts = new WP_Query( $city_query_args );
							$count_profiles_city = absint($city_posts->found_posts);

							$count_profiles_cities += $count_profiles_city;

							// counts in regions
							$wpdb->query( $wpdb->prepare("UPDATE `" . $table_name . "` SET counter = %d WHERE id = %d", $count_profiles_city, $cat['id']) );

						}
					}

					///////////////////////////////////////////////

					// 2. Count regions in tours
					$tour_region_query_args = array(
						'post_type'  => DATEBOOK_TOUR_TYPE,
						'post_status' => 'publish',
						'posts_per_page' => -1,
						'meta_query' => array(
							array(
								'key' => 'region',
								'value' => $cat['id'],
							),
						)
					);

					$tour_region_posts = new WP_Query( $tour_region_query_args );
					$count_tour_region = absint($tour_region_posts->found_posts);

					// counts in regions
					$wpdb->query( $wpdb->prepare("UPDATE `" . $table_name . "` SET tour_counter = %d WHERE id = %d", $count_tour_region, $cat['id']) );

					// Count cities
					$query = "SELECT * FROM `" . $table_name . "` WHERE parent_id = %d";
					$get_tour_cities_only = $wpdb->get_results($wpdb->prepare($query, $cat['id']), ARRAY_A);

					// Get all cities
					if (is_array($get_tour_cities_only) && !empty($get_tour_cities_only)) {

						foreach( $get_tour_cities_only as $cat ){

							// Count regions
							$tour_city_query_args = array(
								'post_type'  => DATEBOOK_TOUR_TYPE,
								'post_status' => 'publish',
								'posts_per_page' => -1,
								'meta_query' => array(
									array(
										'key' => 'city',
										'value' => $cat['id'],
									),
								)
							);

							$tour_city_posts = new WP_Query( $tour_city_query_args );
							$count_tour_city = absint($tour_city_posts->found_posts);

							// counts in regions
							$wpdb->query( $wpdb->prepare("UPDATE `" . $table_name . "` SET tour_counter = %d WHERE id = %d", $count_tour_city, $cat['id']) );

						}
					}
				}
			}

			$response =  array('success' => sprintf(esc_html__( 'Profiles (%1$s) and tours in &quot;%2$s&quot; and its regions and cities have been successfully counted', 'datebook' ), $count_profiles_cities, esc_html( $country_data->name . ' ')));

			wp_send_json($response);

			die();
			
		}

	}


}

DateBook_Countries_Installer::init();