<?php

if (!defined('ABSPATH')) {
	exit;
}

/**
 * Class DateBook_Search
 *
 * @class DateBook_Search
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Search {


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

		add_action('datebook_ajax_search', array(__CLASS__, 'process_ajax_search'));

		add_action('datebook_search_front', array(__CLASS__, 'show_search_form'));
		add_shortcode('datebook_search_form', array(__CLASS__, 'pre_search_form'));

		add_shortcode('datebook_all_profiles', array(__CLASS__, 'return_list_of_profiles'));
		add_shortcode('datebook_top_offer_panel', array(__CLASS__, 'pre_offer_top_position'));

		add_action('datebook_search_page', array(__CLASS__, 'datebook_show_search_on_search_page'));
	}


	/**
	 * Validate all input data
	 *
	 * @access private
	 */
	private static function datebook_catch_search_requests() {

		if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'searchprofiles') {
			
			global $datebook_reserved_fields;

			$datebook_meta_query = array();


			if (isset($_REQUEST['agerange'])) {

				$search_agerange = $_REQUEST['agerange'];
				$search_agerange = explode("-", $search_agerange);
				$_REQUEST['agefrom'] = trim($search_agerange[0]);
				$_REQUEST['ageto'] = trim($search_agerange[1]);

				$array = array(
					'key' => 'agerange',
					'value' => $_REQUEST['agefrom'] . '-' . $_REQUEST['ageto']
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}

			$search_gender				= isset($_REQUEST['gender']) ? $_REQUEST['gender'] : NULL;

			$search_agefrom				= isset($_REQUEST['agefrom']) ? $_REQUEST['agefrom'] : NULL;
			$search_ageto				= isset($_REQUEST['ageto']) ? $_REQUEST['ageto'] : NULL;

			$search_country				= isset($_REQUEST['country']) ? $_REQUEST['country'] : NULL;
			$search_region				= isset($_REQUEST['region']) ? $_REQUEST['region'] : NULL;
			$search_city				= isset($_REQUEST['city']) ? $_REQUEST['city'] : NULL;

			$search_online				= isset($_REQUEST['online_status']) ? $_REQUEST['online_status'] : NULL;
			$search_sexualorientation	= isset($_REQUEST['sexualorientation']) ? $_REQUEST['sexualorientation'] : NULL;
			$search_singles				= isset($_REQUEST['singles']) ? $_REQUEST['singles'] : NULL;
			$search_profilename			= isset($_REQUEST['searchbyprofilename']) ? $_REQUEST['searchbyprofilename'] : NULL; // Name and ID
			$search_username			= isset($_REQUEST['searchbyusername']) ? $_REQUEST['searchbyusername'] : NULL; // Username


			if ($search_profilename) {
				$profile_name = wp_trim_words(wp_strip_all_tags($search_profilename, true), 200, '');
				$array = array(
					'key' => 'profile_name',
					'value' => $profile_name
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}

			if ($search_username) {
				$username = wp_trim_words(wp_strip_all_tags($search_username, true), 200, '');
				$array = array(
					'key' => 'username',
					'value' => $username
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}


			if ($search_gender) {
				$array = array(
					'key' => 'gender',
					'value' => $search_gender,
					'compare' => '='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}


			$register_age_min = of_get_option('register_age_min') > 0 ? of_get_option('register_age_min') : 18;
			$register_age_max = of_get_option('register_age_max') > 0 ? of_get_option('register_age_max') : 80;

			if ($search_agefrom >= $register_age_min && $search_ageto <= $register_age_max) {
				$agefrom = (int) $search_agefrom;
				$ageto = (int) $search_ageto;

				$array = array(
					'key' => 'birthday',
					'value' => $agefrom . ' AND ' . $ageto,
					'compare' => '>='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}

			if ($search_country && $search_country > 0) {
				$array = array(
					'key' => 'country',
					'value' => $search_country,
					'compare' => '='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}

			if ($search_region && $search_region > 0) {
				$array = array(
					'key' => 'region',
					'value' => $search_region,
					'compare' => '='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}

			if ($search_city && $search_city > 0) {
				$array = array(
					'key' => 'city',
					'value' => $search_city,
					'compare' => '='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}


			if ($search_online == 1) {

				$check_online_status = of_get_option('check_online_status') ? of_get_option('check_online_status') : 120; // 120 seconds = 2 minutes

				$time_two_minutes = time() - $check_online_status;
				$array = array(
					'key' => 'online_status',
					'value' => $time_two_minutes,
					'compare' => '>'
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}


			if ($search_sexualorientation) {
				$array = array(
					'key' => 'sexualorientation',
					'value' => $search_sexualorientation,
					'compare' => '='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}


			if ($search_singles) {
				$array = array(
					'key' => 'family_status',
					'value' => $search_singles,
					'compare' => '='
				);
				$datebook_meta_query['register'][] = $array;
				unset($array);
			}

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

			foreach ($get_profile_custom_fields as $key => $value) {
				if(isset($datebook_reserved_fields[$key])){
					unset($get_profile_custom_fields[$key]);
				}
			}

			/*$datebook_profiletypes = array();
			$profiletypes_array = get_terms(array('orderby' => 'term_id', 'order' => 'ASC','taxonomy' => DATEBOOK_PROFILES_TAX, 'hide_empty' => false));
			foreach ($profiletypes_array as $key => $value ){
				$datebook_profiletypes[] = isset($value->name) ? $value->name : '';
			}
			$profiletypes = implode("\r\n", $datebook_profiletypes);
			$datebook_reserved_fields['profiletypereserved'] = array('slug' => 'profiletypereserved', 'name_en_US' => esc_html__('Profile Type', 'datebook'), 'type' => 'select', 'field_items_en_US' => $profiletypes, 'searchable' => 1, 'required' => 1, 'active' => 1, 'active_fields' => array('enable' => 0, 'type' => 1, 'field_items' => 0, 'characters_limit' => 0, 'searchable' => 1, 'required' => 0));

			$get_profile_custom_fields = array_merge($all_custom_fields, $datebook_reserved_fields);*/


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

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

					$value_active = isset($value['active']) && $value['active'] == 1 ? 1 : 0;
					$value_searchable = isset($value['searchable']) && $value['searchable'] == 1 ? 1 : 0;

					if ($value_active != 1 && $value_searchable != 1) continue;

					if (isset($_REQUEST[$key])) {

						if (is_array($_REQUEST[$key])) {

							$datebook_meta_query['custom_fields'][$key] = array_map('absint', preg_replace("/([^0-9])/", '', $_REQUEST[$key]));
						} else {

							$datebook_meta_query['custom_fields'][$key] = $_REQUEST[$key];
						}
					}
				}
			}
			
			/*Array
(
    [register] => Array
        (
            [0] => Array
                (
                    [key] => agerange
                    [value] => 18-80
                )

            [1] => Array
                (
                    [key] => birthday
                    [value] => 18 AND 80
                    [compare] => >=
                )

            [2] => Array
                (
                    [key] => country
                    [value] => 173
                    [compare] => =
                )

        )

    [custom_fields] => Array
        (
            [countrycity] => Poland
        )

)*/

			return $datebook_meta_query;
		}
	}


	/**
	 * Compare any custom field in the profile with the custom fields in the search form
	 *
	 */
	private static function search_customfields_in_profile($search_fields_array, $profile_fields_array) {

		$selected_search = $selected_profile = 0;

		foreach ($search_fields_array as $key1 => $value1) {
			if (isset($value1)) {
				if (isset($value1) && is_array($value1)) {
					foreach ($value1 as $key2 => $value2) {
						if ($value2 > 0) {
							$selected_search += 1;
							if (isset($profile_fields_array[$key1]) && in_array($value2, $profile_fields_array[$key1])) {
								$selected_profile += 1;
							}
						}
					}
				} else if (is_numeric($value1) && $value1 > 0) {
					$selected_search += 1;
					if (isset($profile_fields_array[$key1]) && is_numeric($profile_fields_array[$key1]) && $profile_fields_array[$key1] > 0) {
						if ($profile_fields_array[$key1] == $value1) {
							$selected_profile += 1;
						}
					}
				} else if (!is_numeric($value1) && strlen($value1) > 0) {
					$selected_search += 1;
					if (isset($profile_fields_array[$key1]) && !is_numeric($profile_fields_array[$key1]) && strlen($profile_fields_array[$key1]) > 0) {
						if ($profile_fields_array[$key1] == $value1) {
							$selected_profile += 1;
						}
					}
				}
			}
		}

		$custom_field_selected = $selected_search > 0 ? 1 : 0;

		if ($selected_search > 0 && $selected_profile > 0 && $selected_search == $selected_profile) {
			$custom_field_exists = 1;
		} else {
			$custom_field_exists = 0;
		}

		return array('custom_field_selected' => $custom_field_selected, 'custom_field_exists' => $custom_field_exists);
	}


	/**
	 * Return profiles
	 *
	 * @access private
	 * @return void
	 */
	public static function return_list_of_profiles($atts = array()) {

		global $wpdb, $datebook_meta_query;

		// validate the Profile form input
		$datebook_meta_query = self::datebook_catch_search_requests();
		
		$search_paged = (isset($_REQUEST['paged']) ? $_REQUEST['paged'] : null);
		$search_previous = (isset($_REQUEST['previous']) ? $_REQUEST['previous'] : null);
		$search_next = (isset($_REQUEST['next']) ? $_REQUEST['next'] : null);

		if ($search_paged) {
			$paged = (int) $search_paged;
		} else {
			$paged = 1;
		}

		if (isset($search_previous)) {
			$paged = $paged - 1;
		}

		if (isset($search_next)) {
			$paged = $paged + 1;
		}

		$paged = get_query_var('paged') ? get_query_var('paged') : 1;

		$search_query_link_array = array();

		$search_query_link_array['action'] = 'searchprofiles';
		$search_for_meta = $query_empty = 0;

		if (isset($datebook_meta_query['register']) && !empty($datebook_meta_query['register']) && count($datebook_meta_query['register']) > 0) {

			$query = array();

			foreach ($datebook_meta_query['register'] as $one) {

				if ($one['key'] != 'birthday') {
					$search_query_link_array[$one['key']] = $one['value'];
				}

				// Omit request. Do not send these requests to database
				if ($one['key'] == 'agerange') continue;

				if ($one['key'] == 'online_status') {

					$sql = $wpdb->prepare("SELECT `meta_value` FROM `" . $wpdb->usermeta . "` WHERE `user_id` IN (SELECT `user_id` FROM `" . $wpdb->usermeta . "` WHERE `meta_key` = %s AND `meta_value` > %d) AND `meta_key` = 'profile_postid'", $one['key'], $one['value']);

				} else if ($one['key'] == 'birthday') {

					$age_between = explode('AND', $one['value']);

					$sql = $wpdb->prepare("SELECT `post_id` FROM (SELECT *, TIMESTAMPDIFF(YEAR, `meta_value`, NOW()) AS age FROM `" . $wpdb->postmeta . "`) as sub_query WHERE age BETWEEN %d AND %d", $age_between[0], $age_between[1]);

				} else if ($one['key'] == 'profile_name') {

					$profile_name_value = '%' . $wpdb->esc_like($one['value']) . '%';
					$sql = $wpdb->prepare("SELECT `ID` FROM `" . $wpdb->posts . "` WHERE `post_type` = %s AND `post_title` LIKE %s OR `post_name` LIKE %s OR `post_excerpt` LIKE %s", DATEBOOK_POST_TYPE, $profile_name_value, $profile_name_value, $profile_name_value);

				} else if ($one['key'] == 'username') {

					$sql = $wpdb->prepare("SELECT `meta_value` FROM `" . $wpdb->usermeta . "` WHERE `user_id` IN (SELECT `user_id` FROM `" . $wpdb->usermeta . "` WHERE `meta_key` = 'nickname' AND `meta_value` LIKE %s) AND `meta_key` = 'profile_postid'", $one['value']);

				} else {

					$sql = $wpdb->prepare("SELECT `post_id` FROM `" . $wpdb->postmeta . "` WHERE `meta_key` = %s AND `meta_value` " . esc_attr($one['compare']) . " %s", $one['key'], $one['value']);

				}

				$q = $wpdb->get_col($sql);

				if (count($q) > 0) {

					$query[] = $q;
				} else {

					$query_empty++;
				}
			}

			$search_for_meta = 1;

			$found_profiles = 1;
		}
		
		

		$search_from_form = (isset($_REQUEST['action']) && $_REQUEST['action'] == 'searchprofiles') ? 1 : 0;

		// Display other profiles if search result is empty
		if (($search_for_meta == 0 || $query_empty > 0) && ($search_from_form == 0 || of_get_option('if_search_results_empty') == 1 || of_get_option('if_search_results_empty') == 3)) {

			$query = array();

			$query_empty = 0;

			$sql = $wpdb->prepare("SELECT `ID` FROM `" . $wpdb->posts . "` WHERE `post_status` = 'publish' AND `post_type` = %s", DATEBOOK_POST_TYPE);

			$q = $wpdb->get_col($sql);

			if (count($q) > 0) {
				$query[] = $q;
			} else {
				$query_empty++;
			}

			$found_profiles = 0;
		}


		if (isset($query) && count($query) > 0 && $query_empty == 0) {

			$nr = count($query);
			$all_found_profile_ids = $query[0];

			for ($i = 0; $i < $nr - 1; $i++) {
				$j = $i + 1;
				$all_found_profile_ids = array_intersect($all_found_profile_ids, $query[$j]);
			}

			if (count($all_found_profile_ids) > 0) {

				$custom_field_selected = $custom_field_exist = 0;
				$re_found_profile_ids = array();

				$datebook_custom_fields_array = isset($datebook_meta_query['custom_fields']) && !empty($datebook_meta_query['custom_fields']) ? $datebook_meta_query['custom_fields'] : array();

				if ($search_for_meta > 0 && $found_profiles > 0 && $query_empty == 0 && !empty($datebook_custom_fields_array) && count($datebook_custom_fields_array) > 0) {

					foreach ($all_found_profile_ids as $key => $value_profile_id) {

						$get_profile_data = get_post_meta($value_profile_id, 'profile_personal_data', true);
						$profile_custom_fields = isset($get_profile_data['edit_form']) ? $get_profile_data['edit_form'] : array();

						$compare_fields_and_profile = self::search_customfields_in_profile($datebook_custom_fields_array, $profile_custom_fields);

						$custom_field_selected += $compare_fields_and_profile['custom_field_selected'];

						if ($compare_fields_and_profile['custom_field_exists'] == '1') {
							$custom_field_exist++;
							$re_found_profile_ids[] = $value_profile_id;
						}
					}
				}


				if ($found_profiles == 0) {
					// Empty search = All profiles
					$total_found_array = $all_found_profile_ids;
					// Display message No profiles found
					$show_no_found_message = $search_for_meta > 0 ? 1 : 0;
				} else if ($found_profiles > 0 && $custom_field_selected == 0) {
					// Main fields selected, custom fields not selected = Found main result
					$total_found_array = $all_found_profile_ids;
					// Display message No profiles found
					$show_no_found_message = 0;
				} else if ($found_profiles > 0 && $custom_field_selected > 0 && $custom_field_exist > 0) {
					// Main fields selected, custom fields selected, custom fields found = Found
					$total_found_array = $re_found_profile_ids;
					// Display message No profiles found
					$show_no_found_message = 0;
				} else if ($found_profiles > 0 && $custom_field_selected > 0 && $custom_field_exist == 0) {
					// Main fields selected, custom fields selected, no custom fields found = No found
					$total_found_array = '';
					// Display message No profiles found
					$show_no_found_message = 1;
				} else {
					// Main fields not selected, custom fields not selected = No found
					$total_found_array = '';
					// Display message No profiles found
					$show_no_found_message = 1;
				}

				$show_no_found_message = isset($atts['show_no_found_message']) ? $atts['show_no_found_message'] : $show_no_found_message;

				$search_query_link_array = $show_no_found_message == 0 && isset($_REQUEST['referrer']) && $_REQUEST['referrer'] == 'searchform' ? add_query_arg(array_merge($search_query_link_array, $datebook_custom_fields_array), '') : '';

				$posts_per_page_main = (isset($atts['quantity']) ? $atts['quantity'] : of_get_option('profiles_per_page')) ? of_get_option('profiles_per_page') : 18;

				$shortcode_border_width = (isset($atts['border_width']) ? $atts['border_width'] : of_get_option('featured_border_width_other')) ? of_get_option('featured_border_width_other') : 0; // 0, 1
				$shortcode_border_style = (isset($atts['border_style']) ? $atts['border_style'] : of_get_option('featured_border_style_other')) ? of_get_option('featured_border_style_other') : 1; // 0, 1
				$shortcode_border_color = (isset($atts['border_color']) ? $atts['border_color'] : of_get_option('featured_border_color_other')) ? of_get_option('featured_border_color_other') : ''; // 0, random, #FF6600
				$shortcode_color_gamma = (isset($atts['color_gamma']) ? $atts['color_gamma'] : of_get_option('featured_color_gamma_other')) ? of_get_option('featured_color_gamma_other') : ''; // 0, random, #FF6600

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}
				
				// Display profiles with images only
				$display_only_profiles_with_images_on_search = isset($atts['display_only_profiles_with_images']) ? $atts['display_only_profiles_with_images'] : (of_get_option('display_only_profiles_with_images_on_search') ? of_get_option('display_only_profiles_with_images_on_search') : 0);

				$options = array('current_user_id' => $current_user_id, 'paged' => $paged, 'r' => $total_found_array, 'posts_per_page_main' => $posts_per_page_main, 'search_query_link_array' => $search_query_link_array, 'show_no_found_message' => $show_no_found_message, 'display_only_profiles_with_images_on_search' => $display_only_profiles_with_images_on_search, 'border_width' => $shortcode_border_width, 'border_style' => $shortcode_border_style, 'border_color' => $shortcode_border_color, 'color_gamma' => $shortcode_color_gamma);

				// display found profiles
				return DateBook_Template_Loader::load('search/show-profiles', $options);

			} else if (of_get_option('if_search_results_empty') != 4) {

				// display message No Profiles found
				return DateBook_Template_Loader::load('search/no-profiles');

			}

		} else if (of_get_option('if_search_results_empty') != 4) {

			// display message No Profiles found
			return DateBook_Template_Loader::load('search/no-profiles');

		}
	}


	/**
	 * Show profiles
	 *
	 * @access private
	 * @return void
	 */
	public static function show_list_of_profiles() {

		// display message No Profiles found
		echo self::return_list_of_profiles();
	}


	/**
	 * Show Popup window with countries
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_countries_popup($alllocations, $displaycountries = 0, $counter_type = 'profile', $location_selected = 0) {

		if($displaycountries == 1){

			global $wpdb, $allowedposttags;

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

			// Display countries which have profiles or without
			$show_all_countries = isset($alllocations) && $alllocations == 1 ? 1 : 0;
	
			switch($counter_type) {
				case 'profile' : $counter_type = 'counter'; break;
				case 'classified' : $counter_type = 'class_counter'; break;
				case 'tour' : $counter_type = 'tour_counter'; break;
				default: $counter_type = 'counter'; break;
			}

			$counter = ($show_all_countries == 1) ? " AND " . $counter_type . " >= %d" : " AND " . $counter_type . " > %d";

			// Get all countries
			$query = "SELECT * FROM " . $table_name . " WHERE parent_id = %d AND active = %d " . $counter . " ORDER BY slug ASC";

			// Get city or region from the search form
			$search_location = $search_made = 0;
			if (isset($_REQUEST['city']) && $_REQUEST['city'] > 0) {
				$search_location = $_REQUEST['region'];
				$search_made = 1;
			} else if (isset($_REQUEST['region']) && $_REQUEST['region'] > 0) {
				$search_location = $_REQUEST['country'];
				$search_made = 1;
			} else if (isset($_REQUEST['country']) && $_REQUEST['country'] > 0) {
				$search_location = 0;
				$search_made = 1;
			}

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

			$count_items = $count_country = $count_region = $count_city = 0;
			$search_item = $search_title = $search_buttons = $country_name = '';

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

				// If only one country is active then display only regions of this country
				if (count($get_all_locations) == 1 && $search_made == 0) {

					$get_countries_only = $wpdb->get_results($wpdb->prepare($query, $get_all_locations[0]['id'], 1, 0), ARRAY_A);

				} else if ($get_all_locations[0]['level'] == 2) {

					$query = "SELECT * FROM " . $table_name . " WHERE id = %d AND active = %d " . $counter . " ORDER BY slug ASC";

					$get_all_locations = $wpdb->get_results($wpdb->prepare($query, $id, 1, 0), ARRAY_A);

				}

				if ($get_all_locations[0]['level'] > 0) {
					// if foreign language do not exist, then show title in English (en_US)
					$country_name_array = maybe_unserialize($get_all_locations[0]['name']);
					$country_name = isset($country_name_array[DATEBOOK_WPLANG]) && !empty($country_name_array[DATEBOOK_WPLANG]) ? ', ' . $country_name_array[DATEBOOK_WPLANG] : ', ' . $country_name_array['en_US'];
				}

				$sort_items = array();

				foreach($get_countries_only as $cat){

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

					$sort_items[] = array('id' => $cat['id'], 'name' => $cat_name, 'slug' => $cat['slug'], 'parent_id' => $cat['parent_id'], 'level' => $cat['level'], 'counter' => $cat['counter'], 'class_counter' => $cat['class_counter'], 'tour_counter' => $cat['tour_counter'], 'active' => $cat['active']);

				}
				
				function compareByName($a, $b) {
					return strcmp($a['name'], $b['name']);
					//return $a["name"] > $b["name"];
				}
				usort($sort_items, 'compareByName');

				/*usort($myArray, function($a, $b) {
					return $a['name'] <=> $b['name'];
				});*/


				$search_item .= '<div class="row datebook-countrymenu">';

				$count_countries = ceil(count($sort_items) / 3);

				foreach($sort_items as $cat){

					$count_items++;

					if($count_items == 1 || ($count_items == $count_countries + 1) || ($count_items == $count_countries + $count_countries + 1)){
						$search_item .= '<div class="col-lg-4 col-md-4 col-sm-4">';
					}

					if ($cat['level'] == 0) {
						$count_country++;
						$level_regionid_cityid = 'datebook-countryid';
					} else if ($cat['level'] == 1) {
						$count_region++;
						$level_regionid_cityid = 'datebook-regionid';
					} else if ($cat['level'] == 2) {
						$count_city++;
						$level_regionid_cityid = 'datebook-cityid';
					}

					// if foreign language do not exist, then show title in English (en_US)
					$cat_name = $cat['name'];

					$search_item .= '<a id="' . esc_attr($cat['id']) . '" class="d-block datebook-cat-item ' . $level_regionid_cityid . '" title="'.esc_attr($cat_name . $country_name).'" href="#" onclick="return false;">' . esc_attr($cat_name) . '</a>';

					if($count_items == $count_countries || ($count_items == $count_countries + $count_countries) || $count_items == count($sort_items)){
						$search_item .= '</div>';
					}
				}

			} else {
				
				$search_title .= esc_html__( 'No countries found', 'datebook' );

			}

			$search_item .= '</div>';


			if($count_country > 0){
				$search_title .= esc_html__( 'Select country', 'datebook' );
			} else if($count_region > 0){
				$search_title .= esc_html__( 'Select region', 'datebook' );
			} else if($count_city > 0){
				$search_title .= esc_html__( 'Select city', 'datebook' );
			}

			// Get city or region from the search form
			$search_location = $search_made = 0;
			$get_buttons = '';
			if(isset($_REQUEST['city']) && $_REQUEST['city'] > 0){
				$get_buttons .= ' <a class="btn blue-grey lighten-5 m-0 pl-2 pr-2 shadow-none datebook-regionback" href="#" onclick="return false;">' . esc_html__( 'change region', 'datebook' ).'</a>';
				$search_buttons .= ' <a class="btn btn-light btn-blue-grey m-0 pl-2 pr-2 shadow-none btn-close-country" href="#" onclick="return false;" data-dismiss="modal">'. esc_html__( 'selected', 'datebook' ) . '!</a>';
			} else if(isset($_REQUEST['region']) && $_REQUEST['region'] > 0){
				$get_buttons .= ' <a class="btn blue-grey lighten-5 m-0 pl-2 pr-2 shadow-none datebook-countryback" href="#" onclick="return false;">' . esc_html__( 'change country', 'datebook' ).'</a>';
				$search_buttons .= ' <a class="btn btn-light btn-blue-grey m-0 pl-2 pr-2 shadow-none btn-close-country" href="#" onclick="return false;" data-dismiss="modal">'. esc_html__( 'selected', 'datebook' ) . '</a>';
			} else {
				$search_buttons .= ' <a class="btn btn-light btn-blue-grey m-0 pl-2 pr-2 shadow-none btn-close-country" href="#" onclick="return false;" data-dismiss="modal">'. esc_html__( 'close', 'datebook' ) . '</a>';
			}

			$search_items_out = '';
			$search_items_out .= '<h5>';
			$search_items_out .= $search_title;
			$search_items_out .= $get_buttons;
			$search_items_out .= $search_buttons;
			$search_items_out .= '</h5>';

			$search_items_out .= $search_item;


			$layout = '';

			$layout .= '<div class="datebook-dropdownbox">';
			$layout .= '<div class="datebook-countrybox">';

			// Escape all fields but keep HTML tags
			$layout .= wp_kses(stripslashes_deep($search_items_out), $allowedposttags );

			$layout .= '</div>';

			$layout .= '</div>';

			$layout .= '<div class="datebook-city-proccess">';
			$layout .= '<div class="d-flex align-items-center">';
			$layout .= esc_html__( 'Loading cities', 'datebook' ).' <div class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></div>';
			$layout .= '</div>';
			$layout .= '</div>';

			$layout .= '<div class="datebook-region-proccess">';
			$layout .= '<div class="d-flex align-items-center">';
			$layout .= esc_html__( 'Loading regions', 'datebook' ).' <div class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></div>';
			$layout .= '</div>';
			$layout .= '</div>';

			$layout .= '<div class="datebook-country-proccess">';
			$layout .= '<div class="d-flex align-items-center">';
			$layout .= esc_html__( 'Loading countries', 'datebook' ).' <div class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></div>';
			$layout .= '</div>';
			$layout .= '</div>';

			// display the Countries list
			return $layout;

		} else {

			$empty_modal = 1;

			// display the Countries list
			include DateBook_Template_Loader::locate('search/countries-popup');

		}

	}


	/**
	 * Process ajax functions
	 *
	 * @access public
	 * @return
	 */
	public static function datebook_ajax_functions() {

		if (isset($_GET['action']) && $_GET['action'] == 'datebook_ajax_actions') {

			$get_items = $get_title = $get_buttons = $close_button = $country_name_2 = '';

			//Catch the whatisit - cities, logincheck, defaultimage, realphotodelete, activateprofile, logodelete, favoriteset, tourdelete, touredit
			$whatisit = isset($_GET['whatisit']) ? esc_attr($_GET['whatisit']) : '';
			
			$alllocations = isset($_GET['alllocations']) && $_GET['alllocations'] == 1 ? 1 : 0;
			$posttype = isset($_GET['posttype']) ? $_GET['posttype'] : 'profile';
			$location_selected = isset($_GET['id']) ? $_GET['id'] : 0;
			
			$showprocess = isset($_GET['showprocess']) ? $_GET['showprocess'] : 0;

			// Display countries
			if ($whatisit == 'countries') {

				$displaycountries = 1;

				// Get all countries
				$datebook_countries_popup = self::datebook_countries_popup($alllocations, $displaycountries, $posttype, $location_selected);

				if ($datebook_countries_popup != '') {

					$response = array(
						'status' => 200,
						'content' => $datebook_countries_popup
					);

				} else {

					$response = array(
						'status'  => 201,
						'content'  => esc_html__('Countries could not be loaded', 'datebook'),
					);
				}

				wp_send_json($response);

			} else if ($whatisit == 'cities') {
				
				// Display Cities

				global $wpdb;

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

				$countrystyle = $_GET['countrystyle'];

				switch($posttype) {
					case 'profile' : $counter_type = 'counter'; break;
					case 'classified' : $counter_type = 'class_counter'; break;
					case 'tour' : $counter_type = 'tour_counter'; break;
					default: $counter_type = 'counter'; break;
				}

				// Display countries which have profiles or without
				if ($alllocations == 1) {
					$counter = '';
				} else {
					$show_all_countries = of_get_option('search_show_empty_countries') ? 1 : 0;
					$counter = ($show_all_countries == 1) ? '' : " AND " . $counter_type . " > 0";
				}
				
				// DateBook Taxonomy method
				$query = "SELECT * FROM " . $table_name . " WHERE parent_id = %d AND active = %d " . $counter . " ORDER BY slug ASC";
				$get_prepared = $wpdb->prepare($query, $location_selected, 1);
				$get_countries_only = $wpdb->get_results($get_prepared, ARRAY_A);
				$get_all_locations = $get_countries_only;

				// Count Countries
				$count_locations = $wpdb->get_results($wpdb->prepare($query, 0, 1), ARRAY_A);
				$count_countries = count($count_locations);

				if ($count_countries == 1 && $countrystyle == 'regionback' && $get_all_locations[0]['level'] < 2) {

					$get_countries_only = $wpdb->get_results($wpdb->prepare($query, $get_all_locations[0]['id'], 1), ARRAY_A);

				}

				$country_name = '';

				if (isset($get_all_locations[0]['level']) && $get_all_locations[0]['level'] > 0) {
					$query = "SELECT * FROM " . $table_name . " WHERE id = %d AND active = %d " . $counter . " ORDER BY slug ASC";
					$get_all_locations = $wpdb->get_results($wpdb->prepare($query, $location_selected, 1), ARRAY_A);

					if ($get_all_locations[0]['level'] == 1) {
						$get_all_locations_2 = $wpdb->get_results($wpdb->prepare($query, $get_all_locations[0]['parent_id'], 1), ARRAY_A);
						// if foreign language do not exist, then show title in English (en_US)
						$country_name_array_2 = maybe_unserialize($get_all_locations_2[0]['name']);
						$country_name_2 = isset($country_name_array_2[DATEBOOK_WPLANG]) && !empty($country_name_array_2[DATEBOOK_WPLANG]) ? ', ' . $country_name_array_2[DATEBOOK_WPLANG] : ', ' . $country_name_array_2['en_US'];
					}
					
					// if foreign language do not exist, then show title in English (en_US)
					$country_name_array = maybe_unserialize($get_all_locations[0]['name']);
					$country_name = isset($country_name_array[DATEBOOK_WPLANG]) && !empty($country_name_array[DATEBOOK_WPLANG]) ? ', ' . $country_name_array[DATEBOOK_WPLANG] . $country_name_2 : ', ' . $country_name_array['en_US'] . $country_name_2;

				}

				// Get all cities
				if (is_array($get_countries_only)) {
					
					$sort_items = array();

					foreach($get_countries_only as $cat){

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

						$sort_items[] = array('id' => $cat['id'], 'name' => $cat_name, 'slug' => $cat['slug'], 'parent_id' => $cat['parent_id'], 'level' => $cat['level'], 'counter' => $cat['counter'], 'class_counter' => $cat['class_counter'], 'tour_counter' => $cat['tour_counter'], 'active' => $cat['active']);

					}

					function compareByName($a, $b) {
						return strcmp($a['name'], $b['name']);
						//return $a["name"] > $b["name"];
					}
					usort($sort_items, 'compareByName');

					if ($countrystyle == 'countryback') {

						$get_title .= esc_html__('Select country', 'datebook');

						$close_button .= ' <a class="btn btn-light btn-blue-grey m-0 pl-2 pr-2 shadow-none btn-close-country" href="#" onclick="return false;" data-dismiss="modal">' . esc_html__('close', 'datebook') . '</a>';

					} else if ($countrystyle == 'listregions' || $countrystyle == 'regionback') {

						$get_title .= esc_html__('Select region', 'datebook');

						$close_button .= ' <a class="btn btn-light btn-blue-grey m-0 pl-2 pr-2 shadow-none btn-close-country" href="#" onclick="return false;" data-dismiss="modal">' . esc_html__('selected', 'datebook') . '!</a>';

						if ($count_countries > 1) {

							$get_buttons .= ' <a class="btn btn-light blue-grey lighten-5 m-0 pl-2 pr-2 shadow-none datebook-countryback" href="#" onclick="return false;">' . esc_html__('change country', 'datebook') . '</a>';
						}

					} else if ($countrystyle == 'listcities') {

						$get_title .= esc_html__('Select city', 'datebook');

						$close_button .= ' <a class="btn btn-blue-grey m-0 pl-2 pr-2 shadow-none btn-close-country" href="#" onclick="return false;" data-dismiss="modal">' . esc_html__('selected', 'datebook') . '!</a>';

						$get_buttons .= ' <a id="' . absint($location_selected) . '" class="btn blue-grey lighten-5 m-0 pl-2 pr-2 shadow-none datebook-regionback" href="#" onclick="return false;">' . esc_html__('change region', 'datebook') . '</a>';
					}

					$get_items .= '<div class="datebook-dropdownbox">';
					$get_items .= '<div class="datebook-countrybox">';
					$get_items .= '<h5>';
					$get_items .= $get_title;
					$get_items .= $get_buttons;
					$get_items .= $close_button;
					$get_items .= '</h5>';
					$get_items .= '<div class="row clear datebook-countrymenu">';

					$count_items = 0;

					$count_countries = ceil(count($sort_items) / 3);

					foreach ($sort_items as $cat) {

						$count_items++;

						if ($count_items == 1 || ($count_items == $count_countries + 1) || ($count_items == $count_countries + $count_countries + 1)) {
							$get_items .= '<div class="col-sm-4 col-md-4 col-lg-4">';
						}

						if ($cat['level'] == 0) {
							$level_regionid_cityid = 'datebook-countryid';
						} else if ($cat['level'] == 1) {
							$level_regionid_cityid = 'datebook-regionid';
						} else if ($cat['level'] == 2) {
							$level_regionid_cityid = 'datebook-cityid';
						}

						// if foreign language do not exist, then show title in English (en_US)
						$cat_name = $cat['name'];

						$get_items .= '<a id="' . absint($cat['id']) . '" class="d-block ' . $level_regionid_cityid . '" title="' . esc_attr($cat_name . $country_name) . '" href="#" onclick="return false;">' . esc_html($cat_name) . '</a>';

						if ($count_items == $count_countries || ($count_items == $count_countries + $count_countries) || $count_items == count($sort_items)) {
							$get_items .= '</div>';
						}
					}

					$get_items .= '</div>';
					$get_items .= '</div>';
					$get_items .= '</div>';

					if ($showprocess == 1) {

						$get_items .= '<div class="datebook-city-proccess">';
						$get_items .= '<div class="d-flex align-items-center">';
						$get_items .= esc_html__( 'Loading cities', 'datebook' ).' <div class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></div>';
						$get_items .= '</div>';
						$get_items .= '</div>';

						$get_items .= '<div class="datebook-region-proccess">';
						$get_items .= '<div class="d-flex align-items-center">';
						$get_items .= esc_html__( 'Loading regions', 'datebook' ).' <div class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></div>';
						$get_items .= '</div>';
						$get_items .= '</div>';

						$get_items .= '<div class="datebook-country-proccess">';
						$get_items .= '<div class="d-flex align-items-center">';
						$get_items .= esc_html__( 'Loading countries', 'datebook' ).' <div class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></div>';
						$get_items .= '</div>';
						$get_items .= '</div>';

					}

					$response = array(
						'status' => 200,
						'content' => $get_items
					);

				} else {

					$response = array(
						'status'  => 201,
						'content' => esc_html__('No countries found', 'datebook')
					);
				}

				wp_send_json($response);
			}


			if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {

				die();
			}

			return $get_items;
		}
	}


	/**
	 * Process ajax queries
	 *
	 * @access public
	 * @return void
	 */
	public static function process_ajax_search() {

		if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

			// update all the input data
			add_action('wp_loaded', self::datebook_ajax_functions());
		} else {

			// update all the input data
			self::datebook_ajax_functions();
		}
	}


	/**
	 * Return search form
	 *
	 * @access public
	 * @return void
	 */
	public static function pre_search_form($atts = array()) {

		global $datebook_field_titles;
		set_query_var('datebook_field_titles', $datebook_field_titles);

		$is_shortcode = !empty($atts) && is_array($atts) ? 1 : (isset($atts['shortcode']) && $atts['shortcode'] == 1 ? 0 : 1);

		$is_front_page = is_front_page() ? 1 : 0;

		if(isset($atts['showtitle'])){
			$shortcode_showtitle = $atts['showtitle'];
		} else if ($is_front_page == 1 && of_get_option('display_header_search_form_front') == 1) {
			$shortcode_showtitle = 1;
		} else if ($is_front_page == 0 && of_get_option('display_header_search_form_other') == 1) {
			$shortcode_showtitle = 1;
		} else {
			$shortcode_showtitle = 0;
		}

		$shortcode_tooltip = isset($atts['tooltip']) ? $atts['tooltip'] : 1; // 0, 1
		$shortcode_style = isset($atts['style']) ? $atts['style'] : 1; // 1, 2, 3
		$shortcode_space = isset($atts['space']) ? $atts['space'] : 1; // 0, 1, 2
		$shortcode_align = isset($atts['align']) ? $atts['align'] : ''; // left, right

		$shortcode_color = isset($atts['color']) ? $atts['color'] : ''; // #FFF
		$shortcode_background = isset($atts['background']) ? $atts['background'] : ''; // #000

		if ($is_front_page == 1 && of_get_option('searchform_layout_front')) {
			$shortcode_layout = of_get_option('searchform_layout_front');
		} else if ($is_front_page == 0 && of_get_option('searchform_layout_other')) {
			$shortcode_layout = of_get_option('searchform_layout_other');
		} else {
			$shortcode_layout = '1'; // 1 = horizontal, 2 = vertical
		}
		$shortcode_layout = isset($atts['layout']) ? $atts['layout'] : $shortcode_layout; // 1, 2

		if ($is_front_page == 1 && of_get_option('show_advanced_fields_front')) {
			$show_advanced_fields = of_get_option('show_advanced_fields_front');
		} else if ($is_front_page == 0 && of_get_option('show_advanced_fields_other')) {
			$show_advanced_fields = of_get_option('show_advanced_fields_other');
		} else {
			$show_advanced_fields = '1'; // 1 = display, 2 = hide
		}
		$show_advanced_fields = isset($atts['show_advanced_fields']) ? $atts['show_advanced_fields'] : $show_advanced_fields; // 1, 2

		$shortcode_show_empty_countries = of_get_option('search_show_empty_countries') ? 1 : 0;

		$options = array(
			'shortcode' => $is_shortcode,
			'showtitle' => $shortcode_showtitle,
			'tooltip' => $shortcode_tooltip,
			'style' => $shortcode_style,
			'space' => $shortcode_space,
			'align' => $shortcode_align,
			'layout' => $shortcode_layout,
			'color' => $shortcode_color,
			'background' => $shortcode_background,
			'show_advanced_fields' => $show_advanced_fields,
			'show_empty_countries' => $shortcode_show_empty_countries
		);

		// display the Profiles Search form
		if ($shortcode_layout == '1') {
			return DateBook_Template_Loader::load('search/search-form-h', $options);
		} else {
			return DateBook_Template_Loader::load('search/search-form-v', $options);
		}
	}


	/**
	 * Show search form
	 *
	 * @access public
	 * @return void
	 */
	public static function show_search_form() {

		$atts = array('shortcode' => 0);

		// display the Profiles Search form
		echo self::pre_search_form($atts);
	}


	/**
	 * Show banner offering Top position
	 *
	 * @access public
	 * @return void
	 */
	public static function pre_offer_top_position() {

		if (is_user_logged_in() && DateBook_Utilities::check_if_gateway_activated()) {

			$top_active_in_plan = $suggest_top_count = 0;

			$profile_args = array();

			// Get Subscription plans
			$get_subscription_plans = get_option('datebook_subscription_plans');

			if (is_array($get_subscription_plans)) {

				global $wpdb;

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

				$profile_id = get_user_meta($current_user_id, 'profile_postid', true);

				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

				if (isset($datebook_get_data['profile_subscription'])) {

					$period_number_top_position = isset($get_subscription_plans['period_number_top_position']) ? $get_subscription_plans['period_number_top_position'] : 0;
					$period_top_position = isset($get_subscription_plans['period_top_position']) ? $get_subscription_plans['period_top_position'] : 0;

					$subscription_starts = isset($datebook_get_data['profile_subscription']['starts']) ? $datebook_get_data['profile_subscription']['starts'] : '';
					
					$top_times_total = isset($datebook_get_data['profile_subscription']['top_times_total']) && $datebook_get_data['profile_subscription']['top_times_total'] > 0 ? $datebook_get_data['profile_subscription']['top_times_total'] : 0;
					$top_times_left = isset($datebook_get_data['profile_subscription']['top_times_left']) && $datebook_get_data['profile_subscription']['top_times_left'] > 0 ? $datebook_get_data['profile_subscription']['top_times_left'] : 0;
					$topad_starts = isset($datebook_get_data['profile_subscription']['topad_starts']) && $datebook_get_data['profile_subscription']['topad_starts'] > 0 ? $datebook_get_data['profile_subscription']['topad_starts'] : 0;

					$profile_subscription_args = array(
						'profile_subscription_starts' => $subscription_starts,
						'topad_starts' => $topad_starts,
						'profile_top_times_total' => $top_times_total,
						'profile_top_times_left' => $top_times_left,
						'profile_id' => $profile_id
					);

					// Check if what Subscription plans offer Top position
					foreach ($get_subscription_plans as $key => $value) {

						if (isset($value['active']) && $value['active'] == 1 && (isset($value['top_position']) && $value['top_position'] == 1) && isset($datebook_get_data['profile_subscription']['plan']) && $datebook_get_data['profile_subscription']['plan'] == $value['subscription_id']) {

							$top_active_in_plan++;

							$profile_subscription_args['period_long_number_top_position'] = isset($value['period_long_number_top_position']) ? $value['period_long_number_top_position'] : 0;
							$profile_subscription_args['period_long_top_position'] = isset($value['period_long_top_position']) ? $value['period_long_top_position'] : 0;

							$profile_subscription_args['value'] = $value;
						}

						if (isset($value['suggest_top_position']) && $value['suggest_top_position'] == 1) {

							$suggest_top_count++;
						}
					}

					$member_subscriptions = datebook_get_member_subscriptions(array('user_id' => $current_user_id));
					$member_subscription_status = isset($member_subscriptions[0]->status) ? $member_subscriptions[0]->status : NULL;

					if ($member_subscription_status == 'active' || $member_subscription_status == 'completed') {

						if ($top_active_in_plan == 0 && $suggest_top_count > 0) {

							// display the panel suggesting Top position
							return DateBook_Template_Loader::load('search/offer-top-position');
						} else if ($top_active_in_plan > 0) {

							// display the panel with form to move profile Top position
							return DateBook_Template_Loader::load('search/offer-top-position-form', $profile_subscription_args);
						}
					}
				}
			}
		}
	}


	/**
	 * Show Top offer panel
	 *
	 * @access public
	 * @return void
	 */
	public static function offer_top_position() {

		echo self::pre_offer_top_position();
	}


	/**
	 * Show search form and profiles
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_show_search_on_search_page() {

		self::show_search_form();

		self::offer_top_position();

		self::show_list_of_profiles();
	}
}

DateBook_Search::init();