<?php
if (!defined('ABSPATH')) {
	exit;
} // Exit if accessed directly.

/**
 * Get the id af any item (used only to localize address for shortcodes)
 */
function wre_get_ID() {
	$post_id = null;

	if (!$post_id)
		$post_id = wre_shortcode_att('id', 'wre_listing');

	if (!$post_id)
		$post_id = wre_shortcode_att('id', 'wre_agent');

	if (!$post_id)
		$post_id = get_the_ID();

	return $post_id;
}

/**
 * Get the meta af any item
 */
function wre_meta($meta, $post_id = 0) {
	if (!$post_id)
		$post_id = get_the_ID();

	$meta_key = '_wre_listing_' . $meta;
	if( $meta == 'content' ) {
		$meta_key = $meta;
	}

	if ($meta == 'type' || $meta == 'listing-type') {
		$data = wp_get_post_terms($post_id, 'listing-type', array("fields" => "slugs"));
		if (!empty($data))
			$data = $data[0];
	} else if( $meta == 'building_unit' || $meta == 'land_unit' ){
		$data = get_post_meta($post_id, $meta_key, true);
		$feature_fields =  cmb2_get_metabox( '_wre_listing_features' )->prop( 'fields' );
		if( isset( $feature_fields[$meta_key]['options'] ) && array_key_exists( $data, $feature_fields[$meta_key]['options'] ) ){
			$data = $feature_fields[$meta_key]['options'][$data];
		}
	} else {
		$data = get_post_meta($post_id, $meta_key, true);
	}

	return $data;
}

/**
 * Get any option
 */
function wre_option($option) {
	$options = get_option('wre_options');
	$return = isset($options[$option]) ? $options[$option] : false;
	return $return;
}

/**
 * Return an attribute value from any shortcode
 */
function wre_shortcode_att($attribute, $shortcode) {

	global $post;

	if (!$attribute && !$shortcode)
		return;

	if ($post && has_shortcode($post->post_content, $shortcode)) {
		$pattern = get_shortcode_regex();
		if (preg_match_all('/' . $pattern . '/s', $post->post_content, $matches) && array_key_exists(2, $matches) && in_array($shortcode, $matches[2])) {
			$key = array_search($shortcode, $matches[2], true);

			if ($matches[3][$key]) {
				$att = str_replace($attribute . '="', "", trim($matches[3][$key]));
				$att = str_replace('"', '', $att);

				if (isset($att)) {
					return $att;
				}
			}
		}
	}
}

/**
 * is_wre_admin - Returns true if on a listings page in the admin
 */
function is_wre_admin() {
	$post_type = get_post_type();
	$screen = get_current_screen();
	$return = false;

	if ( in_array( $post_type, array( 'listing', 'listing-enquiry', 'agency' ) ) ) {
		$return = true;
	}

	if (in_array($screen->id, array('listing', 'edit-listing', 'listing-enquiry', 'edit-listing-enquiry', 'wre-subscription', 'wre-edit-subscription', 'listing_page_wre_options', 'listing_page_wre_import_export', 'listing_page_wre-idx-listing'))) {
		$return = true;
	}

	return apply_filters('wre_is_admin', $return);
}

/**
 * is_wre - Returns true if a page uses wre templates
 */
function is_wre() {

	// include on agents page
	$is_agent = false;
	if (is_author()) {
		$user = new WP_User(wre_agent_ID());
		$user_roles = $user->roles;
		$listings_count = wre_agent_listings_count(wre_agent_ID());
		if (in_array('wre_agent', $user_roles) || $listings_count > 0) {
			$is_agent = true;
		}
	}

	$result = apply_filters('is_wre', ( is_wre_archive() || is_single_wre() || is_wre_search() || is_wre_active_widget() || $is_agent ) ? true : false );

	return $result;
}

/**
 * is_wre_archive - Returns true when viewing the listing type archive.
 */
if (!function_exists('is_wre_archive')) {

	function is_wre_archive() {
		return ( is_post_type_archive('listing') );
	}

}

/**
 * is_lisitng - Returns true when viewing a single listing.
 */
if (!function_exists('is_single_wre')) {

	function is_single_wre() {
		$result = false;
		if (is_singular('listing')) {
			$result = true;
		}

		return apply_filters('is_single_wre', $result);
	}

}
/**
 * is_lisitng - Returns true when viewing listings search results page
 */
if (!function_exists('is_wre_search')) {

	function is_wre_search() {
		if (!is_search())
			return false;
		$current_page = sanitize_post($GLOBALS['wp_the_query']->get_queried_object());
		if ($current_page)
			return $current_page->name == 'listing';

		return false;
	}

}

/**
 * is_wre_active_widget - Returns true when viewing wre widget.
 */
if (!function_exists('is_wre_active_widget')) {

	function is_wre_active_widget() {
		if (is_active_widget('', '', 'wre-agents') || is_active_widget('', '', 'wre-recent-listings') || is_active_widget('', '', 'wre-search-listings') || is_active_widget('', '', 'wre-nearby-listings')) {
			return true;
		}
		return false;
	}

}

add_action('init', 'wre_add_new_image_sizes', 11);

function wre_add_new_image_sizes() {
	add_theme_support('post-thumbnails');
	add_image_size('wre-lge', 800, 600, array('center', 'center')); //main
	add_image_size('wre-sml', 400, 300, array('center', 'center')); //thumb
}

/*
 * Run date formatting through here
 */

function wre_format_date($date) {
	$timestamp = strtotime($date);
	$date = date_i18n(get_option('date_format'), $timestamp, false);
	return apply_filters('wre_format_date', $date, $timestamp);
}
function wre_map_key() {
	return $key = wre_option('maps_api_key') ? wre_option('maps_api_key') : false;
}

/*
 * Build Google maps URL
 */

function wre_google_maps_url() {
	$api_url = 'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places';
	$key = wre_map_key();
	if ($key) {
		$api_url = $api_url . '&key=' . $key;
	}
	return $api_url;
}

/*
 * Build Google maps Geocode URL
 */

function wre_google_geocode_maps_url($address) {
	$api_url = "https://maps.google.com/maps/api/geocode/json?address={$address}";
	$key = wre_map_key();
	$country = wre_search_country();
	if (!empty($key)) {
		$api_url = $api_url . '&key=' . $key;
	}

	if (!empty($country)) {
		$api_url = $api_url . '&components=country:' . $country;
	}

	return apply_filters('wre_google_geocode_maps_url', $api_url);
}

/*
 * Get search country
 */

function wre_search_country() {
	$country = wre_option('search_country') ? wre_option('search_country') : '';
	return apply_filters('wre_search_country', $country);
}

/*
 * Get distance measurement
 */

function wre_distance_measurement() {
	$measurement = wre_option('distance_measurement') ? wre_option('distance_measurement') : 'kilometers';
	return apply_filters('wre_distance_measurement', $measurement);
}

/*
 * Get search radius
 */

function wre_search_radius() {
	$search_radius = wre_option('search_radius') ? wre_option('search_radius') : 20;
	return apply_filters('wre_search_radius', $search_radius);
}

/*
 * Validate Select value
 */

function wre_sanitize_select($input, $setting) {

	//input must be a slug: lowercase alphanumeric characters, dashes and underscores are allowed only
	$input = sanitize_key($input);

	//get the list of possible select options
	$choices = $setting->manager->get_control($setting->id)->choices;

	//return input if valid or return default option
	return ( array_key_exists($input, $choices) ? $input : $setting->default );
}

function wre_nearby_listings_callback() {
	$content = '';
	$flag = false;

	$data = $_POST['data'];
	$max_listings = $data['number'];
	$compact = $data['compact'];

	$measurement = $data['measurement'] ? $data['measurement'] : 'kilometers';
	$distance = $data['radius'] ? $data['radius'] : 50;
	$lat = $data['current_lat'];
	$lng = $data['current_lng'];
	$radius = $measurement == 'kilometers' ? 6371 : 3950;
	$view = $data['view'] ? $data['view'] : 'list-view';
	// latitude boundaries
	$maxlat = $lat + rad2deg($distance / $radius);
	$minlat = $lat - rad2deg($distance / $radius);

	// longitude boundaries (longitude gets smaller when latitude increases)
	$maxlng = $lng + rad2deg($distance / $radius / cos(deg2rad($lat)));
	$minlng = $lng - rad2deg($distance / $radius / cos(deg2rad($lat)));
	$related_args = array(
		'post_type' => 'listing',
		'posts_per_page' => $max_listings,
		'post_status' => 'publish',
		'post__not_in' => array(wre_get_ID()),
		'fields' => 'ids'
	);
	$related_args['meta_query'][] = array(
		'key' => '_wre_listing_lat',
		'value' => array($minlat, $maxlat),
		'type' => 'DECIMAL(10,5)',
		'compare' => 'BETWEEN',
	);
	$related_args['meta_query'][] = array(
		'key' => '_wre_listing_lng',
		'value' => array($minlng, $maxlng),
		'type' => 'DECIMAL(10,5)',
		'compare' => 'BETWEEN',
	);
	$related_posts = get_posts($related_args);
	if (!empty($related_posts)) {
		$related_posts = implode(',', $related_posts);
		$content = do_shortcode('[wre_listings number="' . $max_listings . '" view="'. $view .'" ids="' . $related_posts . '" order="desc" compact="' . $compact . '"]');
		$flag = true;
	} else {
		$content = __('Sorry, no listings were found.', 'wp-real-estate');
	}
	echo wp_send_json(array('flag' => true, 'data' => $content));
	die(0);
}

add_action('wp_ajax_wre_nearby_listings', 'wre_nearby_listings_callback');
add_action('wp_ajax_nopriv_wre_nearby_listings', 'wre_nearby_listings_callback');

function wre_agency_meta($meta, $post_id = 0) {
	if (!$post_id)
		$post_id = get_the_ID();
	$meta_key = '_wre_agency_' . $meta;
	if( $meta == 'content' )
		$meta_key = $meta;

	$data = get_post_meta($post_id, $meta_key, true);
	return $data;
}

function wre_package_meta($meta, $post_id = 0) {
	if (!$post_id)
		$post_id = get_the_ID();
	$meta_key = '_wre_package_' . $meta;

	$data = get_post_meta($post_id, $meta_key, true);
	return $data;
}

/*
 * Get the URL of image of an agency - or blank
 */

function wre_agency_image() {

	$cover = wre_agency_meta('cover');
	$id = wre_agency_meta('cover_id');

	if (empty($cover)) {
		$sml = apply_filters('wre_agency_no_image_url', WRE_PLUGIN_URL . 'assets/images/no-image.jpg');
		$alt = '';
	} else {
		$sml = wp_get_attachment_image_url($id, 'wre-sml');
		$alt = get_post_meta($id, '_wp_attachment_image_alt', true);
	}

	return array(
		'alt' => $alt,
		'sml' => $sml,
	);
}

function wre_admin_agency_get_agents($field = null) {

	$args = apply_filters('wre_admin_agency_get_agents', array(
		'role' => '',
		'role__in' => array('wre_agent', 'administrator'),
		'role__not_in' => array(),
		'meta_key' => '',
		'meta_value' => '',
		'meta_compare' => '',
		'meta_query' => array(),
		'date_query' => array(),
		'include' => array(),
		'exclude' => array(),
		'orderby' => 'display_name',
		'order' => 'ASC',
		'offset' => '',
		'search' => '',
		'number' => '',
		'count_total' => false,
		'fields' => array('display_name', 'ID'),
		'who' => '',
	));

	$agents = get_users($args);
	if ($agents) {
		foreach ($agents as $agent) {
			$email = ' <span class="light">(' . get_the_author_meta('email', $agent->ID) . ')</span>';
			$array[$agent->ID] = $agent->display_name . $email;
		}
	}

	return $array;
}

if (!function_exists('wre_get_agent_attachment_url')) {

	function wre_get_agent_attachment_url($agent_id, $size = 'wre-sml') {
		global $wpdb;
		$upload_url = get_the_author_meta('wre_upload_meta', $agent_id);

		if ($upload_url) {

			$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $upload_url));
			if (!empty($attachment)) {
				$upload_url = wp_get_attachment_image_src($attachment[0], $size);
				$upload_url = $upload_url[0];
			} else
				$upload_url = '';
		}

		if (!$upload_url)
			$upload_url = get_avatar_url($agent_id, array('size' => 512));

		return $upload_url;
	}

}

if (!function_exists('wre_get_comparison_data')) {

	function wre_get_comparison_data() {

		$compared_listings = false;
		if (isset($_COOKIE['wre_compare_listings']) && !empty($_COOKIE['wre_compare_listings'])) {
			$compared_listings = (array) json_decode(stripslashes($_COOKIE['wre_compare_listings']));
		}
		return $compared_listings;
	}

}

if (!function_exists('wre_get_comparison_content')) {

	function wre_get_comparison_content($listing_id) {

		if (!$listing_id)
			return;

		ob_start();
		$listing_image = wre_get_first_image($listing_id);
		?>

		<li>
			<img src="<?php echo esc_url($listing_image['sml']); ?>" />
			<a href="#" class="remove-listing" data-id="<?php echo esc_attr($listing_id); ?>">
				<i class="wre-icon-close"></i>
			</a>
			<h3 class="wre-compare-title"><?php echo get_the_title($listing_id); ?></h3>
		</li>

		<?php
		return ob_get_clean();
	}

}

if (!function_exists('wre_is_theme_compatible')) {

	function wre_is_theme_compatible() {
		$wre_theme_compatible = wre_option('wre_theme_compatibility') ? wre_option('wre_theme_compatibility') : 'enable';
		if ($wre_theme_compatible == 'disable') {
			$wre_theme_compatible = false;
		} else {
			$wre_theme_compatible = true;
		}
		return $wre_theme_compatible;
	}

}

function wre_compare_listings_callback() {

	$listing_id = $_POST['listing_id'];
	$compared_listings = '';
	$flag = false;
	$message = $image = '';
	$compared_listings = wre_get_comparison_data();

	if ($compared_listings) {

		if (count($compared_listings) > 3) {
			$message = __('You have reached the maximum of four listings per comparison.', 'wp-real-estate');
		} else {
			if (!in_array($listing_id, $compared_listings)) {
				array_push($compared_listings, $listing_id);
				$flag = true;
			}
		}
	} else {
		$compared_listings[] = $listing_id;
		$flag = true;
	}
	if ($flag) {
		$cookie = setcookie('wre_compare_listings', json_encode($compared_listings), '0', '/');
		$message = wre_get_comparison_content($listing_id);
	}

	echo wp_send_json(array('flag' => $flag, 'message' => $message));
	die(0);
}

add_action('wp_ajax_wre_compare_listings', 'wre_compare_listings_callback');
add_action('wp_ajax_nopriv_wre_compare_listings', 'wre_compare_listings_callback');

function wre_remove_compare_listings_callback() {

	$listing_id = $_POST['listing_id'];
	$compared_listings = wre_get_comparison_data();
	if ($compared_listings) {

		$compared_listings = array_diff($compared_listings, array($listing_id));
		$cookie = setcookie('wre_compare_listings', json_encode($compared_listings), '0', "/");
	}

	echo wp_send_json(array('flag' => $cookie));
	die(0);
}

add_action('wp_ajax_wre_remove_compare_listings', 'wre_remove_compare_listings_callback');
add_action('wp_ajax_nopriv_wre_remove_compare_listings', 'wre_remove_compare_listings_callback');


add_filter('the_content', 'wre_overwrite_content');

if (!function_exists('wre_overwrite_content')) {

	function wre_overwrite_content($content) {

		if( wre_is_theme_compatible() ) {

			if (is_singular('listing')) {

				ob_start();
				/**
				 * @hooked wre_output_content_wrapper (outputs opening divs for the content)
				 */
				do_action('wre_before_main_content');

				wre_get_part('content-single-listing.php');

				/*
				 * @hooked wre_output_content_wrapper_end (outputs closing divs for the content)
				 */
				do_action('wre_after_main_content');
				$content = ob_get_clean();
			} else if (is_singular('agency')) {

				ob_start();
					/**
					 * @hooked wre_output_content_wrapper (outputs opening divs for the content)
					 *
					 */
					do_action('wre_before_main_content');

						wre_get_part('content-single-agency.php');

					/**
					 * @hooked wre_output_content_wrapper_end (outputs closing divs for the content)
					 *
					 */
					do_action('wre_after_main_content');

				$content = ob_get_clean();
			}

		}

		return $content;
	}

}

if (!function_exists('wre_get_contextual_query')) {

	function wre_get_contextual_query( $listing_type = '' ) {

		global $wp_query, $post;
		static $contextual_query;
		if( $listing_type == 'my-listings' ) {
			$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
			$current_user_id = get_current_user_id();
			$posts_per_page = wre_default_posts_number();
			$listings_args = array(
				'post_type' => 'listing',
				'author' => $current_user_id,
				'post_status' => 'any',
				'posts_per_page' => $posts_per_page,
				'paged' => $paged,
				'orderby' => 'date'
			);
			return $contextual_query = new WP_Query( $listings_args );
		} else if (!is_archive()) {

			$archive_listings_page = wre_option('archives_page');
			$archive_agency_page = wre_option('agency_archives_page');

			if (is_page($archive_listings_page)) {
				$contextual_query = new WRE_Archive_Listings();
				$contextual_query = $contextual_query->build_query();
			} else if (is_page($archive_agency_page)) {
				$contextual_query = new WRE_Agencies();
				$contextual_query = $contextual_query->build_query();
			}
			return $contextual_query;
		}

		return $wp_query;
	}

}

/*
 * Set the path to be used in the theme folder.
 * Templates in this folder will override the plugins frontend templates.
 */

function wre_template_path() {
	return apply_filters('wre_template_path', 'wp-real-estate/');
}

function wre_get_part($part, $id = null) {

	if ($part) {

		// Look within passed path within the theme - this is priority.
		$template = locate_template(
				array(
					trailingslashit(wre_template_path()) . $part,
					$part,
				)
		);

		// Get template from plugin directory
		if (!$template) {

			$check_dirs = apply_filters('wre_template_directory', array(
				WRE_PLUGIN_DIR . 'templates/',
			));
			foreach ($check_dirs as $dir) {
				if (file_exists(trailingslashit($dir) . $part)) {
					$template = $dir . $part;
				}
			}
		}

		include( $template );
	}
}

/**
 * Locate a template and return the path for inclusion.
 *
 * This is the load order:
 *
 *		yourtheme		/	$template_path	/	$template_name
 *		yourtheme		/	$template_name
 *		$default_path	/	$template_name
 *
 * @access public
 * @param string $template_name
 * @param string $template_path (default: '')
 * @param string $default_path (default: '')
 * @return string
 */
function wre_locate_template( $template_name, $template_path = '', $default_path = '' ) {
	if ( ! $template_path ) {
		$template_path = wre_template_path();
	}

	if ( ! $default_path ) {
		$default_path = WRE_PLUGIN_DIR . 'templates/';
	}

	// Look within passed path within the theme - this is priority.
	$template = locate_template(
		array(
			trailingslashit( $template_path ) . $template_name,
			$template_name,
		)
	);

	// Get default template/
	if ( ! $template ) {
		$template = $default_path . $template_name;
	}

	// Return what we found.
	return apply_filters( 'wre_locate_template', $template, $template_name, $template_path );
}

/**
 * Wrapper for wre_doing_it_wrong.
 *
 * @since  3.0.0
 * @param  string $function
 * @param  string $version
 * @param  string $replacement
 */
function wre_doing_it_wrong( $function, $message, $version ) {
	$message .= ' Backtrace: ' . wp_debug_backtrace_summary();

	if ( is_ajax() ) {
		do_action( 'doing_it_wrong_run', $function, $message, $version );
		error_log( "{$function} was called incorrectly. {$message}. This message was added in version {$version}." );
	} else {
		_doing_it_wrong( $function, $message, $version );
	}
}

/**
 * Get other templates (e.g. product attributes) passing attributes and including the file.
 *
 * @access public
 * @param string $template_name
 * @param array $args (default: array())
 * @param string $template_path (default: '')
 * @param string $default_path (default: '')
 */
function wre_get_template( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
	if ( ! empty( $args ) && is_array( $args ) ) {
		extract( $args );
	}

	$located = wre_locate_template( $template_name, $template_path, $default_path );

	if ( ! file_exists( $located ) ) {
		wre_doing_it_wrong( __FUNCTION__, sprintf( __( '%s does not exist.', 'wp-real-estate' ), '<code>' . $located . '</code>' ), '2.1' );
		return;
	}

	// Allow 3rd party plugin filter template file from their plugin.
	$located = apply_filters( 'wre_get_template', $located, $template_name, $args, $template_path, $default_path );

	do_action( 'wre_before_template_part', $template_name, $template_path, $located, $args );

	include( $located );

	do_action( 'wre_after_template_part', $template_name, $template_path, $located, $args );
}

/**
 * Get shortlisted listings.
 *
 * @return array $shortlisted_listings
 */
if (!function_exists('wre_get_shortlisted_listings')) {

	function wre_get_shortlisted_listings() {

		$shortlisted_listings = array();
		if (isset($_COOKIE['wre_shortlisted_listings']) && !empty($_COOKIE['wre_shortlisted_listings'])) {
			$shortlisted_listings = (array) json_decode(stripslashes($_COOKIE['wre_shortlisted_listings']));
		}
		return $shortlisted_listings;
	}

}

function wre_shortlisted_listings_callback() {
	$listing_id = $_POST['listing_id'];
	$shortlisted_listings = wre_get_shortlisted_listings();
	$flag = true;
	if(in_array($listing_id, $shortlisted_listings) ) {
		if(($key = array_search($listing_id, $shortlisted_listings)) !== false) {
			unset($shortlisted_listings[$key]);
			$flag = false;
		}
	} else {
		array_push( $shortlisted_listings, $listing_id );
	}

	setcookie('wre_shortlisted_listings', json_encode($shortlisted_listings), '0', "/");
	echo $flag;
	die(0);
}

add_action('wp_ajax_wre_shortlisted_listings', 'wre_shortlisted_listings_callback');
add_action('wp_ajax_nopriv_wre_shortlisted_listings', 'wre_shortlisted_listings_callback');

/**
 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
 * Non-scalar values are ignored.
 * @param string|array $var
 * @return string|array
 */
function wre_clean( $var ) {
	if ( is_array( $var ) ) {
		return array_map( 'wre_clean', $var );
	} else {
		return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
	}
}

function count_user_posts_by_type( $userid, $post_type )  {
	$args = array(
		'numberposts'   => -1,
		'post_type'     => $post_type,
		'post_status'   => array( 'publish', 'private', 'draft', 'pending' ),
		'author'        => $userid,
		'fields'		=> 'ID'
	);
	$count_posts = count( get_posts( $args ) );
	return $count_posts;
}

/**
 * Get full list of currency codes.
 *
 * @return array
 */
function get_wre_currencies() {
	return array_unique(
		apply_filters( 'wre_currencies',
			array(
				'AED' => __( 'United Arab Emirates dirham', 'wp-real-estate' ),
				'AFN' => __( 'Afghan afghani', 'wp-real-estate' ),
				'ALL' => __( 'Albanian lek', 'wp-real-estate' ),
				'AMD' => __( 'Armenian dram', 'wp-real-estate' ),
				'ANG' => __( 'Netherlands Antillean guilder', 'wp-real-estate' ),
				'AOA' => __( 'Angolan kwanza', 'wp-real-estate' ),
				'ARS' => __( 'Argentine peso', 'wp-real-estate' ),
				'AUD' => __( 'Australian dollar', 'wp-real-estate' ),
				'AWG' => __( 'Aruban florin', 'wp-real-estate' ),
				'AZN' => __( 'Azerbaijani manat', 'wp-real-estate' ),
				'BAM' => __( 'Bosnia and Herzegovina convertible mark', 'wp-real-estate' ),
				'BBD' => __( 'Barbadian dollar', 'wp-real-estate' ),
				'BDT' => __( 'Bangladeshi taka', 'wp-real-estate' ),
				'BGN' => __( 'Bulgarian lev', 'wp-real-estate' ),
				'BHD' => __( 'Bahraini dinar', 'wp-real-estate' ),
				'BIF' => __( 'Burundian franc', 'wp-real-estate' ),
				'BMD' => __( 'Bermudian dollar', 'wp-real-estate' ),
				'BND' => __( 'Brunei dollar', 'wp-real-estate' ),
				'BOB' => __( 'Bolivian boliviano', 'wp-real-estate' ),
				'BRL' => __( 'Brazilian real', 'wp-real-estate' ),
				'BSD' => __( 'Bahamian dollar', 'wp-real-estate' ),
				'BTC' => __( 'Bitcoin', 'wp-real-estate' ),
				'BTN' => __( 'Bhutanese ngultrum', 'wp-real-estate' ),
				'BWP' => __( 'Botswana pula', 'wp-real-estate' ),
				'BYR' => __( 'Belarusian ruble', 'wp-real-estate' ),
				'BZD' => __( 'Belize dollar', 'wp-real-estate' ),
				'CAD' => __( 'Canadian dollar', 'wp-real-estate' ),
				'CDF' => __( 'Congolese franc', 'wp-real-estate' ),
				'CHF' => __( 'Swiss franc', 'wp-real-estate' ),
				'CLP' => __( 'Chilean peso', 'wp-real-estate' ),
				'CNY' => __( 'Chinese yuan', 'wp-real-estate' ),
				'COP' => __( 'Colombian peso', 'wp-real-estate' ),
				'CRC' => __( 'Costa Rican col&oacute;n', 'wp-real-estate' ),
				'CUC' => __( 'Cuban convertible peso', 'wp-real-estate' ),
				'CUP' => __( 'Cuban peso', 'wp-real-estate' ),
				'CVE' => __( 'Cape Verdean escudo', 'wp-real-estate' ),
				'CZK' => __( 'Czech koruna', 'wp-real-estate' ),
				'DJF' => __( 'Djiboutian franc', 'wp-real-estate' ),
				'DKK' => __( 'Danish krone', 'wp-real-estate' ),
				'DOP' => __( 'Dominican peso', 'wp-real-estate' ),
				'DZD' => __( 'Algerian dinar', 'wp-real-estate' ),
				'EGP' => __( 'Egyptian pound', 'wp-real-estate' ),
				'ERN' => __( 'Eritrean nakfa', 'wp-real-estate' ),
				'ETB' => __( 'Ethiopian birr', 'wp-real-estate' ),
				'EUR' => __( 'Euro', 'wp-real-estate' ),
				'FJD' => __( 'Fijian dollar', 'wp-real-estate' ),
				'FKP' => __( 'Falkland Islands pound', 'wp-real-estate' ),
				'GBP' => __( 'Pound sterling', 'wp-real-estate' ),
				'GEL' => __( 'Georgian lari', 'wp-real-estate' ),
				'GGP' => __( 'Guernsey pound', 'wp-real-estate' ),
				'GHS' => __( 'Ghana cedi', 'wp-real-estate' ),
				'GIP' => __( 'Gibraltar pound', 'wp-real-estate' ),
				'GMD' => __( 'Gambian dalasi', 'wp-real-estate' ),
				'GNF' => __( 'Guinean franc', 'wp-real-estate' ),
				'GTQ' => __( 'Guatemalan quetzal', 'wp-real-estate' ),
				'GYD' => __( 'Guyanese dollar', 'wp-real-estate' ),
				'HKD' => __( 'Hong Kong dollar', 'wp-real-estate' ),
				'HNL' => __( 'Honduran lempira', 'wp-real-estate' ),
				'HRK' => __( 'Croatian kuna', 'wp-real-estate' ),
				'HTG' => __( 'Haitian gourde', 'wp-real-estate' ),
				'HUF' => __( 'Hungarian forint', 'wp-real-estate' ),
				'IDR' => __( 'Indonesian rupiah', 'wp-real-estate' ),
				'ILS' => __( 'Israeli new shekel', 'wp-real-estate' ),
				'IMP' => __( 'Manx pound', 'wp-real-estate' ),
				'INR' => __( 'Indian rupee', 'wp-real-estate' ),
				'IQD' => __( 'Iraqi dinar', 'wp-real-estate' ),
				'IRR' => __( 'Iranian rial', 'wp-real-estate' ),
				'IRT' => __( 'Iranian toman', 'wp-real-estate' ),
				'ISK' => __( 'Icelandic kr&oacute;na', 'wp-real-estate' ),
				'JEP' => __( 'Jersey pound', 'wp-real-estate' ),
				'JMD' => __( 'Jamaican dollar', 'wp-real-estate' ),
				'JOD' => __( 'Jordanian dinar', 'wp-real-estate' ),
				'JPY' => __( 'Japanese yen', 'wp-real-estate' ),
				'KES' => __( 'Kenyan shilling', 'wp-real-estate' ),
				'KGS' => __( 'Kyrgyzstani som', 'wp-real-estate' ),
				'KHR' => __( 'Cambodian riel', 'wp-real-estate' ),
				'KMF' => __( 'Comorian franc', 'wp-real-estate' ),
				'KPW' => __( 'North Korean won', 'wp-real-estate' ),
				'KRW' => __( 'South Korean won', 'wp-real-estate' ),
				'KWD' => __( 'Kuwaiti dinar', 'wp-real-estate' ),
				'KYD' => __( 'Cayman Islands dollar', 'wp-real-estate' ),
				'KZT' => __( 'Kazakhstani tenge', 'wp-real-estate' ),
				'LAK' => __( 'Lao kip', 'wp-real-estate' ),
				'LBP' => __( 'Lebanese pound', 'wp-real-estate' ),
				'LKR' => __( 'Sri Lankan rupee', 'wp-real-estate' ),
				'LRD' => __( 'Liberian dollar', 'wp-real-estate' ),
				'LSL' => __( 'Lesotho loti', 'wp-real-estate' ),
				'LYD' => __( 'Libyan dinar', 'wp-real-estate' ),
				'MAD' => __( 'Moroccan dirham', 'wp-real-estate' ),
				'MDL' => __( 'Moldovan leu', 'wp-real-estate' ),
				'MGA' => __( 'Malagasy ariary', 'wp-real-estate' ),
				'MKD' => __( 'Macedonian denar', 'wp-real-estate' ),
				'MMK' => __( 'Burmese kyat', 'wp-real-estate' ),
				'MNT' => __( 'Mongolian t&ouml;gr&ouml;g', 'wp-real-estate' ),
				'MOP' => __( 'Macanese pataca', 'wp-real-estate' ),
				'MRO' => __( 'Mauritanian ouguiya', 'wp-real-estate' ),
				'MUR' => __( 'Mauritian rupee', 'wp-real-estate' ),
				'MVR' => __( 'Maldivian rufiyaa', 'wp-real-estate' ),
				'MWK' => __( 'Malawian kwacha', 'wp-real-estate' ),
				'MXN' => __( 'Mexican peso', 'wp-real-estate' ),
				'MYR' => __( 'Malaysian ringgit', 'wp-real-estate' ),
				'MZN' => __( 'Mozambican metical', 'wp-real-estate' ),
				'NAD' => __( 'Namibian dollar', 'wp-real-estate' ),
				'NGN' => __( 'Nigerian naira', 'wp-real-estate' ),
				'NIO' => __( 'Nicaraguan c&oacute;rdoba', 'wp-real-estate' ),
				'NOK' => __( 'Norwegian krone', 'wp-real-estate' ),
				'NPR' => __( 'Nepalese rupee', 'wp-real-estate' ),
				'NZD' => __( 'New Zealand dollar', 'wp-real-estate' ),
				'OMR' => __( 'Omani rial', 'wp-real-estate' ),
				'PAB' => __( 'Panamanian balboa', 'wp-real-estate' ),
				'PEN' => __( 'Peruvian nuevo sol', 'wp-real-estate' ),
				'PGK' => __( 'Papua New Guinean kina', 'wp-real-estate' ),
				'PHP' => __( 'Philippine peso', 'wp-real-estate' ),
				'PKR' => __( 'Pakistani rupee', 'wp-real-estate' ),
				'PLN' => __( 'Polish z&#x142;oty', 'wp-real-estate' ),
				'PRB' => __( 'Transnistrian ruble', 'wp-real-estate' ),
				'PYG' => __( 'Paraguayan guaran&iacute;', 'wp-real-estate' ),
				'QAR' => __( 'Qatari riyal', 'wp-real-estate' ),
				'RON' => __( 'Romanian leu', 'wp-real-estate' ),
				'RSD' => __( 'Serbian dinar', 'wp-real-estate' ),
				'RUB' => __( 'Russian ruble', 'wp-real-estate' ),
				'RWF' => __( 'Rwandan franc', 'wp-real-estate' ),
				'SAR' => __( 'Saudi riyal', 'wp-real-estate' ),
				'SBD' => __( 'Solomon Islands dollar', 'wp-real-estate' ),
				'SCR' => __( 'Seychellois rupee', 'wp-real-estate' ),
				'SDG' => __( 'Sudanese pound', 'wp-real-estate' ),
				'SEK' => __( 'Swedish krona', 'wp-real-estate' ),
				'SGD' => __( 'Singapore dollar', 'wp-real-estate' ),
				'SHP' => __( 'Saint Helena pound', 'wp-real-estate' ),
				'SLL' => __( 'Sierra Leonean leone', 'wp-real-estate' ),
				'SOS' => __( 'Somali shilling', 'wp-real-estate' ),
				'SRD' => __( 'Surinamese dollar', 'wp-real-estate' ),
				'SSP' => __( 'South Sudanese pound', 'wp-real-estate' ),
				'STD' => __( 'S&atilde;o Tom&eacute; and Pr&iacute;ncipe dobra', 'wp-real-estate' ),
				'SYP' => __( 'Syrian pound', 'wp-real-estate' ),
				'SZL' => __( 'Swazi lilangeni', 'wp-real-estate' ),
				'THB' => __( 'Thai baht', 'wp-real-estate' ),
				'TJS' => __( 'Tajikistani somoni', 'wp-real-estate' ),
				'TMT' => __( 'Turkmenistan manat', 'wp-real-estate' ),
				'TND' => __( 'Tunisian dinar', 'wp-real-estate' ),
				'TOP' => __( 'Tongan pa&#x2bb;anga', 'wp-real-estate' ),
				'TRY' => __( 'Turkish lira', 'wp-real-estate' ),
				'TTD' => __( 'Trinidad and Tobago dollar', 'wp-real-estate' ),
				'TWD' => __( 'New Taiwan dollar', 'wp-real-estate' ),
				'TZS' => __( 'Tanzanian shilling', 'wp-real-estate' ),
				'UAH' => __( 'Ukrainian hryvnia', 'wp-real-estate' ),
				'UGX' => __( 'Ugandan shilling', 'wp-real-estate' ),
				'USD' => __( 'United States dollar', 'wp-real-estate' ),
				'UYU' => __( 'Uruguayan peso', 'wp-real-estate' ),
				'UZS' => __( 'Uzbekistani som', 'wp-real-estate' ),
				'VEF' => __( 'Venezuelan bol&iacute;var', 'wp-real-estate' ),
				'VND' => __( 'Vietnamese &#x111;&#x1ed3;ng', 'wp-real-estate' ),
				'VUV' => __( 'Vanuatu vatu', 'wp-real-estate' ),
				'WST' => __( 'Samoan t&#x101;l&#x101;', 'wp-real-estate' ),
				'XAF' => __( 'Central African CFA franc', 'wp-real-estate' ),
				'XCD' => __( 'East Caribbean dollar', 'wp-real-estate' ),
				'XOF' => __( 'West African CFA franc', 'wp-real-estate' ),
				'XPF' => __( 'CFP franc', 'wp-real-estate' ),
				'YER' => __( 'Yemeni rial', 'wp-real-estate' ),
				'ZAR' => __( 'South African rand', 'wp-real-estate' ),
				'ZMW' => __( 'Zambian kwacha', 'wp-real-estate' ),
			)
		)
	);
}

/**
 * Get Currency symbol.
 *
 * @param string $currency (default: '')
 * @return string
 */
function get_wre_currency_symbol( $currency = '' ) {

	$symbols = apply_filters( 'wre_currency_symbols', array(
		'AED' => '&#x62f;.&#x625;',
		'AFN' => '&#x60b;',
		'ALL' => 'L',
		'AMD' => 'AMD',
		'ANG' => '&fnof;',
		'AOA' => 'Kz',
		'ARS' => '&#36;',
		'AUD' => '&#36;',
		'AWG' => 'Afl.',
		'AZN' => 'AZN',
		'BAM' => 'KM',
		'BBD' => '&#36;',
		'BDT' => '&#2547;&nbsp;',
		'BGN' => '&#1083;&#1074;.',
		'BHD' => '.&#x62f;.&#x628;',
		'BIF' => 'Fr',
		'BMD' => '&#36;',
		'BND' => '&#36;',
		'BOB' => 'Bs.',
		'BRL' => '&#82;&#36;',
		'BSD' => '&#36;',
		'BTC' => '&#3647;',
		'BTN' => 'Nu.',
		'BWP' => 'P',
		'BYR' => 'Br',
		'BZD' => '&#36;',
		'CAD' => '&#36;',
		'CDF' => 'Fr',
		'CHF' => '&#67;&#72;&#70;',
		'CLP' => '&#36;',
		'CNY' => '&yen;',
		'COP' => '&#36;',
		'CRC' => '&#x20a1;',
		'CUC' => '&#36;',
		'CUP' => '&#36;',
		'CVE' => '&#36;',
		'CZK' => '&#75;&#269;',
		'DJF' => 'Fr',
		'DKK' => 'DKK',
		'DOP' => 'RD&#36;',
		'DZD' => '&#x62f;.&#x62c;',
		'EGP' => 'EGP',
		'ERN' => 'Nfk',
		'ETB' => 'Br',
		'EUR' => '&euro;',
		'FJD' => '&#36;',
		'FKP' => '&pound;',
		'GBP' => '&pound;',
		'GEL' => '&#x10da;',
		'GGP' => '&pound;',
		'GHS' => '&#x20b5;',
		'GIP' => '&pound;',
		'GMD' => 'D',
		'GNF' => 'Fr',
		'GTQ' => 'Q',
		'GYD' => '&#36;',
		'HKD' => '&#36;',
		'HNL' => 'L',
		'HRK' => 'Kn',
		'HTG' => 'G',
		'HUF' => '&#70;&#116;',
		'IDR' => 'Rp',
		'ILS' => '&#8362;',
		'IMP' => '&pound;',
		'INR' => '&#8377;',
		'IQD' => '&#x639;.&#x62f;',
		'IRR' => '&#xfdfc;',
		'IRT' => '&#x062A;&#x0648;&#x0645;&#x0627;&#x0646;',
		'ISK' => 'kr.',
		'JEP' => '&pound;',
		'JMD' => '&#36;',
		'JOD' => '&#x62f;.&#x627;',
		'JPY' => '&yen;',
		'KES' => 'KSh',
		'KGS' => '&#x441;&#x43e;&#x43c;',
		'KHR' => '&#x17db;',
		'KMF' => 'Fr',
		'KPW' => '&#x20a9;',
		'KRW' => '&#8361;',
		'KWD' => '&#x62f;.&#x643;',
		'KYD' => '&#36;',
		'KZT' => 'KZT',
		'LAK' => '&#8365;',
		'LBP' => '&#x644;.&#x644;',
		'LKR' => '&#xdbb;&#xdd4;',
		'LRD' => '&#36;',
		'LSL' => 'L',
		'LYD' => '&#x644;.&#x62f;',
		'MAD' => '&#x62f;.&#x645;.',
		'MDL' => 'MDL',
		'MGA' => 'Ar',
		'MKD' => '&#x434;&#x435;&#x43d;',
		'MMK' => 'Ks',
		'MNT' => '&#x20ae;',
		'MOP' => 'P',
		'MRO' => 'UM',
		'MUR' => '&#x20a8;',
		'MVR' => '.&#x783;',
		'MWK' => 'MK',
		'MXN' => '&#36;',
		'MYR' => '&#82;&#77;',
		'MZN' => 'MT',
		'NAD' => '&#36;',
		'NGN' => '&#8358;',
		'NIO' => 'C&#36;',
		'NOK' => '&#107;&#114;',
		'NPR' => '&#8360;',
		'NZD' => '&#36;',
		'OMR' => '&#x631;.&#x639;.',
		'PAB' => 'B/.',
		'PEN' => 'S/.',
		'PGK' => 'K',
		'PHP' => '&#8369;',
		'PKR' => '&#8360;',
		'PLN' => '&#122;&#322;',
		'PRB' => '&#x440;.',
		'PYG' => '&#8370;',
		'QAR' => '&#x631;.&#x642;',
		'RMB' => '&yen;',
		'RON' => 'lei',
		'RSD' => '&#x434;&#x438;&#x43d;.',
		'RUB' => '&#8381;',
		'RWF' => 'Fr',
		'SAR' => '&#x631;.&#x633;',
		'SBD' => '&#36;',
		'SCR' => '&#x20a8;',
		'SDG' => '&#x62c;.&#x633;.',
		'SEK' => '&#107;&#114;',
		'SGD' => '&#36;',
		'SHP' => '&pound;',
		'SLL' => 'Le',
		'SOS' => 'Sh',
		'SRD' => '&#36;',
		'SSP' => '&pound;',
		'STD' => 'Db',
		'SYP' => '&#x644;.&#x633;',
		'SZL' => 'L',
		'THB' => '&#3647;',
		'TJS' => '&#x405;&#x41c;',
		'TMT' => 'm',
		'TND' => '&#x62f;.&#x62a;',
		'TOP' => 'T&#36;',
		'TRY' => '&#8378;',
		'TTD' => '&#36;',
		'TWD' => '&#78;&#84;&#36;',
		'TZS' => 'Sh',
		'UAH' => '&#8372;',
		'UGX' => 'UGX',
		'USD' => '&#36;',
		'UYU' => '&#36;',
		'UZS' => 'UZS',
		'VEF' => 'Bs F',
		'VND' => '&#8363;',
		'VUV' => 'Vt',
		'WST' => 'T',
		'XAF' => 'Fr',
		'XCD' => '&#36;',
		'XOF' => 'Fr',
		'XPF' => 'Fr',
		'YER' => '&#xfdfc;',
		'ZAR' => '&#82;',
		'ZMW' => 'ZK',
	) );

	$currency_symbol = isset( $symbols[ $currency ] ) ? $symbols[ $currency ] : '';

	return apply_filters( 'wp-real-estate_currency_symbol', $currency_symbol, $currency );
}

function wre_theme_activation($oldname, $oldtheme=false) {

	$new_colors = array();
	$icon_colors = apply_filters( 'wre_default_colors', $new_colors );
	if( !empty( $icon_colors ) ) {
		foreach( $icon_colors as $key => $icon_color ) {
			update_option( $key, $icon_color );
		}
	}

	$wre_options = get_option('wre_options');
	$theme_compatible = apply_filters('wre_theme_compatibility', wre_option('wre_theme_compatibility'));
	if( $theme_compatible ) {
		$theme_compatible = 'enable';
	} else {
		$theme_compatible = 'disable';
	}
	$wre_options['wre_theme_compatibility'] = $theme_compatible;

	$wre_options['wre_default_display_mode'] = apply_filters('wre_default_display_mode', wre_option('wre_default_display_mode'));
	$wre_options['wre_grid_columns'] = apply_filters('wre_grid_columns', wre_option('wre_grid_columns'));
	$wre_options['archive_listing_number'] = apply_filters('wre_default_archive_number', wre_option('archive_listing_number'));
	$wre_options['wre_hide_in_content_sidebar'] = apply_filters('wre_hide_in_content_sidebar', wre_option('wre_hide_in_content_sidebar'));

	$wre_options['wre_agents_mode'] = apply_filters('wre_agents_mode', wre_option('wre_agents_mode'));
	$wre_options['wre_archive_agents_columns'] = apply_filters('wre_archive_agents_columns', wre_option('wre_archive_agents_columns'));
	$wre_options['agents_archive_max_agents'] = apply_filters('wre_max_archive_agents', wre_option('agents_archive_max_agents'));
	$wre_options['agents_archive_allow_pagination'] = apply_filters('wre_agents_archive_allow_pagination', wre_option('agents_archive_allow_pagination'));

	$wre_options['show_agents_listings'] = apply_filters('wre_show_agents_listings', wre_option('show_agents_listings'));
	$wre_options['wre_agent_mode'] = apply_filters('wre_agent_mode', wre_option('wre_agent_mode'));
	$wre_options['wre_agent_columns'] = apply_filters('wre_agent_columns', wre_option('wre_agent_columns'));
	$wre_options['agent_max_listings'] = apply_filters('wre_agent_max_listings', wre_option('agent_max_listings'));

	$wre_options['rl_show_listings'] = apply_filters('wre_show_rl', wre_option('rl_show_listings'));
	$wre_options['rl_mode'] = apply_filters('wre_rl_mode', wre_option('rl_mode'));
	$wre_options['rl_columns'] = apply_filters('wre_rl_columns', wre_option('rl_columns'));
	$wre_options['rl_max_listings'] = apply_filters('wre_max_rl', wre_option('rl_max_listings'));

	update_option( 'wre_options', $wre_options );
}
add_action("after_switch_theme", "wre_theme_activation", 10 , 2);

function wre_check_image_file( $file ) {
	$check = false;
	$filetype = wp_check_filetype( $file );
	$valid_exts = array( 'jpg', 'jpeg', 'gif', 'png', 'jpeg' );
	if ( in_array( strtolower( $filetype['ext'] ), $valid_exts ) ) {
		$check = true;
	}

	return $check;
}

function wre_download_image_file( $file, $post_id = '' ) {
	// Need to require these files
	if (!function_exists('media_handle_upload')) {
		require_once( ABSPATH . 'wp-admin/includes/image.php' );
		require_once( ABSPATH . 'wp-admin/includes/file.php' );
		require_once( ABSPATH . 'wp-admin/includes/media.php' );
	}

	if (!empty($file)) {
		// Download file to temp location
		$tmp = download_url($file);

		// If error storing temporarily, unlink
		if (is_wp_error($tmp)) {
			@unlink($file_array['tmp_name']);
			$file_array['tmp_name'] = '';
			return false;
		}

		// Set variables for storage, fix file filename for query strings.
		preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $file, $matches);

		if ( empty( $matches ) ) {
			return false;
		}

		$file_array['name'] = basename($matches[0]);
		$file_array['tmp_name'] = $tmp;

		$tmp_ext  = pathinfo( $tmp, PATHINFO_EXTENSION );
		if($tmp_ext == 'tmp') {
			$path = pathinfo( $tmp );
			// $headers = wp_get_http_headers( $file );
			// $mime_type = $headers['content-type'];
			$fileextension = image_type_to_extension(exif_imagetype($file));
			$filename = preg_replace('"\.(bmp|tmp)$"', $fileextension, $tmp);
			rename($tmp, $filename);
			$tmp = $filename;
			$file_array['name'] = pathinfo( $tmp, PATHINFO_FILENAME )  . $fileextension;
			$file_array['tmp_name'] = $tmp;
		}

		$desc = $file_array['name'];
		$id = media_handle_sideload($file_array, $post_id, $desc);
		// If error storing permanently, unlink
		if (is_wp_error($id)) {
			@unlink($file_array['tmp_name']);
			return false;
		}

		return $id;
	}
}

/**
 * wre_is_premium_agency - Returns true if premium listings exists.
 */
if (!function_exists('wre_is_premium_agency')) {
	function wre_is_premium_agency($id) {
		$agents = wre_agency_meta( 'agents', $id );
		foreach($agents as $agent) {
			$is_premium_agent = wre_is_premium_agent( $agent );
			if($is_premium_agent) return true;
		}
		return false;
	}
}

/**
 * wre_is_premium_agent - Returns true if premium listings exists.
 */
if (!function_exists('wre_is_premium_agent')) {
	function wre_is_premium_agent($user_id) {

		$user_listings = get_posts( array(
			'post_type' => 'listing',
			'posts_per_page' => 1,
			'post_status' => 'publish',
			'fields' => 'ids',
			'author' => $user_id,
			'meta_query' => array(
				array(
					'key'     => '_wre_listing_premium',
					'value'   => '',
					'compare' => '!=',
				)
			),
		) );

		if( !empty($user_listings) ) return true;

		return false;
	}
}

// GDPR Compliant - Export User Information
if(!function_exists('wre_agent_data_exporter')) {
	function wre_agent_data_exporter( $email_address, $page = 1 ) {

		$export_items = array();
		$user_id = email_exists($email_address);

		if($user_id) {

			$agent = new WRE_Agent();
			$meta_fields = $agent->get_customer_meta_fields();
			$meta_fields = $meta_fields['agent_profile'];
			$group_label = $meta_fields['title'];
			$meta_fields['fields']['wre_upload_meta'] = array('label' => 'Agent Profile Photo');
			$data = array();

			foreach($meta_fields['fields'] as $key => $meta_field) {
				$value = get_user_meta($user_id, $key, true);
				if($value) {
					$data[] = array(
						'name'	=> $meta_field['label'],
						'value'	=> $value
					);
				}
			}
			if(!empty($data)) {
				$export_items[] = array(
					'group_id'	=> 'wre_user_data',
					'group_label'	=> apply_filters('wre_export_user_data_label', $group_label),
					'item_id'	=> 'wre_agent_info',
					'data'	=> $data,
				);
			}

			//Subscription Details
			$subscriptions = wre_get_subscriptions_by_id($subscriber_id);

			if(!empty($subscriptions)) {
				foreach($subscriptions as $subscription) {
					$subscription_data = array();
					$subscription_details = get_post_meta($subscription, '_wre_subscription_details', true);
					if(!empty($subscription_details)) {
						foreach($subscription_details as $key => $subscription_detail) {
							$subscription_data[] = array(
								'name' => $key,
								'value' => $subscription_detail
							);
						}
						$export_items[] = array(
							'group_id'	=> 'wre_subscription_data'.$subscription,
							'group_label'	=> get_the_title($subscription),
							'item_id'	=> 'wre_subscription_info'.$subscription,
							'data'	=> $subscription_data,
						);
					}
				}
			}
		}

		//Enquiry Details
		$enquiries = wre_get_enquiries_by_email($email_address);

		if(!empty($enquiries)) {
			$enquiry_meta_fields = apply_filters( 'wre_enquiry_meta_fields', array(
				'_wre_enquiry_name' => __('Name', 'wp-real-estate'),
				'_wre_enquiry_email' => __('Email', 'wp-real-estate'),
				'_wre_enquiry_phone' => __('Phone Number', 'wp-real-estate'),
				'_wre_enquiry_message' => __('Message', 'wp-real-estate'),
				'_wre_consent' => __('Consent', 'wp-real-estate'),
			));
			foreach($enquiries as $enquiry) {
				$enqury_data = array();
				$enqury_data[] = array( 'name'	=> __('Title', 'wp-real-estate'), 'value'	=> get_the_title($enquiry) );
				foreach($enquiry_meta_fields as $meta_key => $enquiry_meta_field) {
					$value = get_post_meta($enquiry, $meta_key, true);
					if($value) {
						$enqury_data[] = array( 'name'	=> $enquiry_meta_field, 'value'	=> $value );
					}
				}

				$export_items[] = array(
					'group_id'	=> 'wre_enquiry_data'.$enquiry,
					'group_label'	=> apply_filters('wre_export_enquiry_data_label', 'Enquiry #'.$enquiry),
					'item_id'	=> 'wre_enquiry_info'.$enquiry,
					'data'	=> $enqury_data,
				);
			}
		}

		return array(
			'data'	=> $export_items,
			'done'	=> true,
		);
	}
}

// Filter function to register data exporter
if(!function_exists('wre_register_data_exporter')) {

	function wre_register_data_exporter( $exporters ) {
		$exporters[] = array(
			'exporter_friendly_name'	=> apply_filters('wre_exporter_friendly_name', __( 'WRE Data', 'wp-real-estate' )),
			'callback'	=> 'wre_agent_data_exporter',
		);
		return $exporters;
	}

}

add_filter( 'wp_privacy_personal_data_exporters', 'wre_register_data_exporter', 10 );

// GDPR Compliant - Erase User Information
function wre_agent_data_eraser( $email_address, $page = 1 ) {

	$default_eraser_data = array(
		'items_removed'		=> false,
		'items_retained'	=> false,
		'messages'				=> array(),
		'done'						=> true,
	);

	if ( empty( $email_address ) ) {
		return $default_eraser_data;
	}

	$items_removed = false;
	$items_retained = false;
	$messages = array();

	$user_id = email_exists($email_address);
	if($user_id) {

		$agent = new WRE_Agent();
		$meta_fields = $agent->get_customer_meta_fields();
		$meta_fields = $meta_fields['agent_profile'];
		$group_label = $meta_fields['title'];
		$meta_fields['fields']['wre_upload_meta'] = array('label' => 'Agent Profile Photo');
		$data = array();
		foreach($meta_fields['fields'] as $key => $meta_field) {
			$meta_value = get_user_meta($user_id, $key, true);
			if($meta_value) {
				delete_user_meta($user_id, $key);
				$items_removed = true;
			}
		}

		if($items_removed) $messages[] = apply_filters('wre_data_eraser_message', __('Removed Agent Profile Information', 'wp-real-estate'));

		$items_removed = false;

		$anonymize_subscription = apply_filters('wre_anonymize_subscriptions', 'yes');
		if($anonymize_subscription === 'yes') {
			$subscriptions = wre_get_subscriptions_by_id($user_id);

			if(!empty($subscriptions)) {
				foreach($subscriptions as $subscription) {
					$subscription_details = get_post_meta($subscription, '_wre_subscription_details', true);
					if(!empty($subscription_details)) {
						if($subscription_details['subscriber_ip_address']) {
							$subscription_details['subscriber_ip_address'] = wp_privacy_anonymize_data( 'ip', $subscription_details['subscriber_ip_address'] );
							update_post_meta($subscription, '_wre_subscription_details', $subscription_details);
						}
					}
					delete_post_meta($subscription, '_wre_subscriber_id');
					$items_removed = true;
					$messages[] = apply_filters('wre_anonymize_subscription_message', sprintf(__('Anonymized Subscription #%s for email %s', 'wp-real-estate'), $subscription, $email_address), $subscription, $email_address);
				}
				$items_removed = false;
			}
		}
	}

	$anonymize_enquiries = apply_filters('wre_anonymize_enquiries', 'yes');
	if($anonymize_enquiries === 'yes') {
		$enquiries = wre_get_enquiries_by_email($email_address);
		if(!empty($enquiries)) {
			foreach($enquiries as $enquiry) {
				delete_post_meta($enquiry, '_wre_enquiry_email');
				delete_post_meta($enquiry, '_wre_enquiry_phone');
				$items_removed = true;
				$messages[] = apply_filters('wre_anonymize_enquiry_message', sprintf(__('Anonymized Enquiry #%s for email %s', 'wp-real-estate'), $enquiry, $email_address), $enquiry, $email_address);
			}
		}
	}

	if(!empty($messages)) {
		return array(
			'items_removed'	=> $items_removed,
			'items_retained' => $items_retained,
			'messages'	=> $messages,
			'done'	=> true,
		);
	}

	return $default_eraser_data;
}

//Filter function to register data eraser
if(!function_exists('wre_register_data_eraser')) {
	function wre_register_data_eraser( $erasers ) {
		$erasers[] = array(
			'eraser_friendly_name'	=> apply_filters('wre_eraser_friendly_name', __( 'WRE Data', 'wp-real-estate' )),
			'callback'	=> 'wre_agent_data_eraser',
		);
		return $erasers;
	}
}
add_filter( 'wp_privacy_personal_data_erasers', 'wre_register_data_eraser', 10 );

function wre_get_enquiries_by_email($email) {
	return get_posts(
			array (
				'posts_per_page' => -1,
				'post_type' => 'listing-enquiry',
				'meta_key' => '_wre_enquiry_email',
				'meta_value' => $email,
				'fields' => 'ids'
			)
		);
}

function wre_get_subscriptions_by_id($id) {
	return get_posts(
		array (
			'posts_per_page' => -1,
			'post_type' => 'wre-subscription',
			'meta_key' => '_wre_subscriber_id',
			'meta_value' => $id,
			'fields' => 'ids'
		)
	);
}
