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

/**
 * Type of listings to display (buy or rent). 
 */
function wre_display() {
	$purpose = wre_option( 'display_purpose' );
	$default = strtolower(wre_option( 'display_default' ));

	$return = $purpose; // set default
	if( $purpose == 'both' ) {
		$return = $default ? $default : $purpose;
	}

	if( isset( $_GET['purpose'] ) && ! empty( $_GET['purpose'] ) ) {
		
		if( $purpose == 'both' ) {
			$return = $_GET['purpose'];
			if( $_GET['purpose'] == 'buy' ) {
				$return = 'sell';
			}
		}
	}
	return apply_filters( 'wre_default_display', $return );
}

/**
 * Post classes for listings.
 */
function wre_listing_post_class( $classes, $class = '', $post_id = '' ) {

	if ( ! $post_id || 'listing' !== get_post_type( $post_id ) ) {
		return $classes;
	}

	$listing = get_post( $post_id );

	if ( $listing ) {

		$classes[] = 'listing';
		$classes[] = 'listing-' . $listing->ID;

		if ( wre_meta( 'type' ) ) {
			$classes[] = strtolower( wre_meta( 'type' ) );
		}

		if ( wre_meta( 'status' ) ) {
			$classes[] = strtolower( wre_meta( 'status' ) );
		}

		if ( wre_meta( 'purpose' ) ) {
			$classes[] = strtolower( wre_meta( 'purpose' ) );
		}

		$images = wre_meta( 'image_gallery' );
		if ( $images ) {
			foreach ( $images as $key => $url ) {
				if( ! empty( $url ) ) {
					$classes[] = strtolower( 'has-thumbnail' );
					break;
				}
			}
		}

		if ( wre_meta( 'bedrooms' ) ) {
			$classes[] = 'beds-' . wre_meta( 'bedrooms' );
		}

		if ( wre_meta( 'bathrooms' ) ) {
			$classes[] = 'baths-' . wre_meta( 'bathrooms' );
		}

	}

	if ( false !== ( $key = array_search( 'hentry', $classes ) ) ) {
		unset( $classes[ $key ] );
	}

	return $classes;
}

/*
 * Show Archive Page title within page content area
 */
function wre_force_page_title() {
	$force = wre_option( 'archives_page_title' ) ? wre_option( 'archives_page_title' ) : 'no';
	return $force;
}

/*
 * Map height
 */
function wre_map_height() {
	$height = wre_option( 'map_height' ) ? wre_option( 'map_height' ) : '300';
	return apply_filters( 'wre_map_height', $height );
}

/*
 * Are we hiding an item
 */
function wre_hide_item( $item ) {
	$hide = wre_meta( 'hide' );
	if( ! $hide ) {
		return false;
	}
	return in_array( $item, $hide );
}

/*
 * Output the chosen tick
 */
function wre_tick() {
	$icon = get_option( 'wre_tick_icon' );
	$return = $icon != 'none' ? '<i class="wre-icon-' . esc_attr( $icon ) . '"></i>' : '';
	return $return;
}

/*
 * Get the URL of the first image of a listing
 */
function wre_get_first_image( $post_id = 0 ) {

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

	$gallery = wre_meta( 'image_gallery', $post_id );

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

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

/*
 * Get the listing status
 */
function wre_get_status() {

	$listing_status     = wre_meta( 'status' );
	$option_statuses    = wre_option( 'listing_status' );

	if( ! $listing_status )
		return;

	$status = null;
	if( !empty( $option_statuses ) ) {
		foreach ($option_statuses as $option_status) {
			$status_slug = strtolower( str_replace( ' ', '-', $option_status) );
			if( $listing_status == $status_slug ) {
				$status = isset( $option_status ) ? $option_status : null;
				if( $status ) {

					$status_bg_color = get_option( 'wre_status_'.$status_slug.'_bg_color' );
					$status_text_color = get_option( 'wre_status_'.$status_slug.'_text_color' );
					$status_icon_class = get_option( 'wre_status_'.$status_slug.'_icon_class' );

					$bg_color = $text_color = $icon = null;

					if($status_bg_color)
						$bg_color = $status_bg_color;

					if($status_text_color)
						$text_color = $status_text_color;

					if($status_icon_class)
						$icon = $status_icon_class;
				}
			}
		}
	}

	if( ! $status ) {
		$status 	= $listing_status;
		$bg_color 	= '#ffffff';
		$text_color = '#444444';
		$icon 		= '';
	}

	return array(
		'status'		=> $status,
		'bg_color'		=> $bg_color,
		'text_color'	=> $text_color,
		'icon'			=> $icon,
	);
}

/**
 * Do we include the decimals
 * @since  1.0.0
 * @return string
 */
function wre_include_decimals() {
	$include_decimals = wre_option( 'include_decimals' );
	$return = $include_decimals ? stripslashes( $include_decimals ) : 'no';
	return $return;
}

/**
 * Get the price format depending on the currency position.
 *
 * @return string
 */
function wre_format_price_format() {
	$currency_position = wre_option( 'currency_position' );
	$currency_pos = $currency_position ? $currency_position : 'left';
	$format = '%1$s%2$s';

	switch ( $currency_pos ) {
		case 'left' :
			$format = '%1$s%2$s';
		break;
		case 'right' :
			$format = '%2$s%1$s';
		break;
		case 'left_space' :
			$format = '%1$s&nbsp;%2$s';
		break;
		case 'right_space' :
			$format = '%2$s&nbsp;%1$s';
		break;
	}

	return apply_filters( 'wre_format_price_format', $format, $currency_pos );
}

/**
 * Return the currency_symbol for prices.
 * @since  1.0.0
 * @return string
 */
function wre_currency_symbol() {
	$currency_symbol = wre_option( 'currency_symbol' );
	$return = $currency_symbol ? get_wre_currency_symbol( $currency_symbol ) : '$';
	return $return;
}

/**
 * Return the thousand separator for prices.
 * @since  1.0.0
 * @return string
 */
function wre_thousand_separator() {
	$thousand_seperator = wre_option( 'thousand_separator' );
	$return = $thousand_seperator ? stripslashes( $thousand_seperator ) : ',';
	return $return;
}

/**
 * Return the decimal separator for prices.
 * @since  1.0.0
 * @return string
 */
function wre_decimal_separator() {
	$decimal_seperator = wre_option( 'decimal_separator' );
	$return = $decimal_seperator ? stripslashes( $decimal_seperator ) : '.';
	return $return;
}

/**
 * Return the number of decimals after the decimal point.
 * @since  1.0.0
 * @return int
 */
function wre_decimals() {
	$decimals = wre_option( 'decimals' );
	$return = $decimals ? $decimals : 2;
	return absint( $return );
}

/**
 * Trim trailing zeros off prices.
 *
 * @param mixed $price
 * @return string
 */
function wre_trim_zeros( $price ) {
	return preg_replace( '/' . preg_quote( wre_decimal_separator(), '/' ) . '0++$/', '', $price );
}

/**
 * Format the price with a currency symbol.
 *
 * @param float $price
 * @param array $args (default: array())
 * @return string
 */
function wre_format_price( $price, $args = array() ) {
	extract( apply_filters( 'wre_format_price_args', wp_parse_args( $args, array(
		'currency_symbol'		=> wre_currency_symbol(),
		'decimal_separator'		=> wre_decimal_separator(),
		'thousand_separator'	=> wre_thousand_separator(),
		'decimals'				=> wre_decimals(),
		'price_format'			=> wre_format_price_format(),
		'include_decimals'		=> wre_include_decimals()
	) ) ) );

	$return = null;
	if( $price != 0 ) {
		$negative	= $price < 0;
		$price		= apply_filters( 'wre_raw_price', floatval( $negative ? $price * -1 : $price ) );
		$price		= apply_filters( 'wre_formatted_price', number_format( $price, $decimals, $decimal_separator, $thousand_separator ), $price, $decimals, $decimal_separator, $thousand_separator );

		if ( $include_decimals == 'no' ) {
			$price = wre_trim_zeros( $price );
		}

		$formatted_price = ( $negative ? '-' : '' ) . sprintf( $price_format, '<span class="currency-symbol">' . $currency_symbol . '</span>', $price );
		$return = '<span class="price-amount">' . $formatted_price . '</span>';
	}

	return apply_filters( 'wre_format_price', $return, $price, $args );
}

/**
 * Format the price with a currency symbol.
 *
 * @param float $price
 * @param array $args (default: array())
 * @return string
 */
function wre_raw_price( $price ) {
	return strip_tags( wre_format_price( $price ) );
}

/*
 * Outputs the price HTML
 */
function wre_price( $price ) {
	$suffix = wre_meta( 'price_suffix' );
	return wre_format_price( $price ) . ' ' . $suffix;
}

add_filter( 'cmb2_override__wre_listing_agent_meta_save', 'wre_cpt_author_meta_save_override', 0, 4 );
/**
 * Override CPT author meta save in order to store as post author
 */
function wre_cpt_author_meta_save_override( $override, $data_args, $args, $field ) {
	// Checks to avoid infinite loops
	// @link	https://codex.wordpress.org/Function_Reference/wp_update_post#Caution_-_Infinite_loop
	if ( ! wp_is_post_revision( $data_args['id'] ) ) {
		// Remove filter to avoid loop
		remove_filter( 'cmb2_override__wre_listing_agent_meta_save', 'wre_cpt_author_meta_save_override', 0 );
		// Update post author
		// Will return non-null value to short-circuit normal meta save

		$override = wp_update_post( array(
			'ID'			=> $data_args['id'],
			'post_author'	=> $data_args['value'],
		));
		// Add filter back
		add_filter( 'cmb2_override__wre_listing_agent_meta_save', 'wre_cpt_author_meta_save_override', 0 );
	}
	return $override;
}

/**
 * Returns the listing statuses as set in the options.
 *
 * @return array
 */
function wre_listing_statuses() {
	$option = get_option('wre_options');
	$statuses = isset($option['listing_status']) ? $option['listing_status'] : '';
	$array = array();
	if ($statuses) {
		foreach ($statuses as $status) {
			$status_slug = strtolower(str_replace(' ', '-', $status));
			$array[$status_slug] = $status;
		}
	}
	return $array;
}

/**
 * Returns the listing internal features as set in the options.
 *
 * @return array
 */
function wre_listing_internal_features() {
	$option = get_option('wre_options');
	$datas = isset($option['internal_feature']) ? $option['internal_feature'] : '';
	$array = array();
	if ($datas) {
		foreach ($datas as $data) {
			$array[$data] = $data;
		}
	}
	return $array;
}

/**
 * Returns the listing external features as set in the options.
 *
 * @return array		
 */
function wre_listing_external_features() {
	$option = get_option('wre_options');
	$datas = isset($option['external_feature']) ? $option['external_feature'] : '';
	$array = array();
	if ($datas) {
		foreach ($datas as $data) {
			$array[$data] = $data;
		}
	}
	return $array;
}

/**
 * Returns array of all agents.
 * For use in dropdowns.
 */
function wre_admin_get_agents($field) {
	global $current_user, $post;
	
	if (in_array('wre_agent', $current_user->roles)) {
		$array[$current_user->ID] = $current_user->display_name;
	} else {
		$args = apply_filters('wre_agents_as_dropdown', 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);
		$array = array('' => __('No Agent', 'wp-real-estate'));
		if ($agents) {
			foreach ($agents as $agent) {
				$array[$agent->ID] = $agent->display_name;
			}
		}
	}
	if( !empty( $post ) ) {
		$array[$post->post_author] = get_the_author_meta( 'display_name', $post->post_author );
	}
	return $array;
}

/**
 * Output the map on the admin edit listing
 * @param  object $field_args Current field args
 * @param  object $field      Current field object
 */
function wre_admin_map($field_args, $field) {
	?>

	<div class="cmb-th"></div>
	<div class="cmb-td">
		<button id="wre-find" type="button" class="button button-small"><?php _e('Find', 'wp-real-estate'); ?></button>
		<button id="wre-reset" type="button" class="button button-small"><?php _e('Reset', 'wp-real-estate'); ?></button>
	</div>

	<div class="cmb-th"></div>
	<div class="cmb-td">
		<div class="wre-admin-map" style="height:220px"></div>
		<p class="cmb2-metabox-description map-desc">
			<?php if( wre_option( 'maps_api_key' ) ) { ?>
				<?php _e('Modify the marker\'s position by dragging it.', 'wp-real-estate'); ?>
			<?php } else { ?>
				<?php echo __( 'To show google map, please enter your API ', 'wp-real-estate' ). '<a href="'. admin_url('edit.php?post_type=listing&page=wre_options&tab=opt-tab-general') .'">'.__('here', 'wp-real-estate').'.</a>'; ?>
			<?php } ?>
		</p>
	</div>

	<?php
}

function wre_default_display_mode() {
	return $default_listing_mode = wre_option( 'wre_default_display_mode' ) ? wre_option( 'wre_default_display_mode' ) : 'grid-view';
}

function wre_default_posts_number() {
	return $default_listing_number = wre_option( 'archive_listing_number' ) ? wre_option( 'archive_listing_number' ) : 9;
}

function wre_default_grid_columns() {
	return $default_columns = wre_option( 'wre_grid_columns' ) ? wre_option( 'wre_grid_columns' ) : 3;
}

/**
 * Get formatted error/success message
 *
 * @return	string $message
 */
if( !function_exists('wre_se_message') ) {
	function wre_se_message( $message, $class='error' ) {
		$message = apply_filters( 'wre_messages_'.$class, '<div class="wre-message-box '. $class .'"><span>'. $message .'</span></div>' );
		return $message;
	}
}