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

class WRE_Shortcodes {

	public function __construct() {
		add_filter( 'wp', array( $this, 'has_shortcode' ) );
		add_shortcode( 'wre_listing', array( $this, 'listing' ) );
		add_shortcode( 'wre_listings', array( $this, 'listings' ) );
		add_shortcode( 'wre_agent', array( $this, 'agent' ) );
		add_shortcode( 'wre_nearby_listings', array( $this, 'nearby_listings' ) );
		add_shortcode( 'wre_agents', array( $this, 'wre_agents' ) );
		add_shortcode( 'wre_shortlisted_listings', array( $this, 'wre_shortlisted_listings' ) );
		add_shortcode( 'wre_mortgage_calculator', array( $this, 'wre_mortgage_calculator' ) );
	}

	/**
	 * Check if we have the shortcode displayed
	 */
	public function has_shortcode() {
			global $post;
			if ( is_a( $post, 'WP_Post' ) &&
				( has_shortcode( $post->post_content, 'wre_listing') ||
				has_shortcode( $post->post_content, 'wre_listings') ||
				has_shortcode( $post->post_content, 'wre_agent') ||
				has_shortcode( $post->post_content, 'wre_search' ) ||
				has_shortcode( $post->post_content, 'wre_contact_form' ) ||
				has_shortcode( $post->post_content, 'wre_nearby_listings' ) ||
				has_shortcode( $post->post_content, 'wre_shortlisted_listings' ) ||
				has_shortcode( $post->post_content, 'wre_mortgage_calculator' ) ||
				has_shortcode( $post->post_content, 'wre_agents' ) )
			)
			{
				add_filter( 'is_wre', array( $this, 'return_true' ) );
			}

			if ( is_a( $post, 'WP_Post' ) &&
				has_shortcode( $post->post_content, 'wre_listing') )
			{
				add_filter( 'is_single_wre', array( $this, 'return_true' ) );
			}
	}

	/**
	 * Add this as a wre page
	 *
	 * @param bool $return
	 * @return bool
	 */
	public function return_true( $return ) {
		return true;
	}

	/**
	 * Loop over found listings.
	 * @param  array $query_args
	 * @param  array $atts
	 * @param  string $loop_name
	 * @return string
	 */
	private static function listing_loop( $query_args, $atts, $loop_name ) {

		$listings = new WP_Query( apply_filters( 'wre_shortcode_query', $query_args, $atts, $loop_name ) );

		$display_mode = $atts['view'] ? $atts['view'] : 'grid-view';
		$columns = $atts['columns'] ? $atts['columns'] : 3;
		ob_start();

			if ( $listings->have_posts() ) { ?>
				<?php do_action( "wre_shortcode_before_{$loop_name}_loop" ); ?>

					<ul class="wre-items <?php echo esc_attr( $display_mode ); ?>">

						<?php
						while ( $listings->have_posts() ) : $listings->the_post();
							wre_get_content_listings_data( $columns );
						endwhile; // end of the loop.

						?>

					</ul>
				<?php
				if( $atts['allow_pagination'] == 'yes' ) {
					if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); }
					elseif ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }
					else { $paged = 1; }
					do_action( 'wre_shortcode_listings_pagination', $paged, $listings->max_num_pages );
				}
				do_action( "wre_shortcode_after_{$loop_name}_loop" );

			} else {
				do_action( "wre_shortcode_{$loop_name}_loop_no_results" );
			}

		wp_reset_postdata();

		return ob_get_clean();
	}

	/**
	 * List multiple listings shortcode.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function listings( $atts ) {
		$atts = shortcode_atts( array(
			'orderby'	=> 'date',
			'order'		=> 'desc',
			'number'	=> '9',
			'view'		=> 'grid-view',
			'allow_pagination'	=> 'no',
			'columns'	=> 3,
			'agent'		=> '', // id of the agent
			'ids'		=> '',
			'compact'	=> 'false',
			'type'      => '',
		), $atts );
		if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); }
		elseif ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }
		else { $paged = 1; }
		$query_args = array(
			'post_type'				=> 'listing',
			'post_status'			=> 'publish',
			'ignore_sticky_posts'	=> 1,
			'orderby'				=> $atts['orderby'],
			'order'					=> $atts['order'],
			'posts_per_page'		=> $atts['number'],
			'paged'					=> $paged
		);

		if ($atts['orderby'] == 'price') {
			$query_args['meta_key'] = '_wre_listing_price';
			$query_args['orderby'] = 'meta_value_num';
		}

		if ( ! empty( $atts['ids'] ) ) {
			$query_args['post__in'] = array_map( 'trim', explode( ',', $atts['ids'] ) );
		}

		if ( ! empty( $atts['agent'] ) ) {
			$query_args['meta_key']     = '_wre_listing_agent';
			$query_args['meta_value']   = absint( $atts['agent'] );
			$query_args['meta_compare'] = '=';
		}

		if ( ! empty( $atts['type'] ) ) {
			$query_args['tax_query'] = array(
				array(
					'taxonomy' => 'listing-type',
					'field'    => is_numeric( $atts['type'] ) ? 'term_id' : 'slug',
					'terms'    => $atts['type'],
				)
			);
		}

		// if we are in compact mode
		if ( ! empty( $atts['compact'] ) && $atts['compact'] == 'true' ) {
			remove_action( 'wre_before_listings_loop_item_wrapper', 'wre_before_listings_loop_item_wrapper', 10 );
			remove_action( 'wre_after_listings_loop_item_wrapper', 'wre_after_listings_loop_item_wrapper', 10 );

			remove_action( 'wre_listings_loop_item', 'wre_template_loop_at_a_glance', 40 );
			remove_action( 'wre_listings_loop_item', 'wre_template_loop_description', 50 );
			remove_action( 'wre_listings_loop_item', 'wre_template_loop_compare', 60 );
			remove_action('wre_before_listings_loop_image', 'wre_template_loop_shortlisted', 10);
			remove_action('wre_before_listings_loop_image', 'wre_template_loop_premium', 20);
			add_filter( 'post_class', array( __CLASS__, 'listings_compact_mode' ), 20, 3 );
		}
		do_action( 'wre_enqueue_plugin_scripts' );
		return self::listing_loop( $query_args, $atts, 'listings' );
	}

	/**
	 * List nearby listings shortcode.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function nearby_listings( $atts ) {
		$atts = shortcode_atts( array(
			'distance'	=> 'miles',
			'radius'	=> '50',
			'number'	=> '3',
			'compact'	=> 'true',
			'view'		=> 'list-view',
			'columns'	=> '3'
		), $atts );

		$key = wre_map_key();
		if( ! $key ) return;

		ob_start();
		?>
			<div class="nearby-listings-wrapper" data-listing-view="<?php echo esc_attr( $atts['view'] ); ?>" data-columns="<?php echo esc_attr( $atts['columns'] ); ?>" data-distance="<?php echo esc_attr( $atts['distance'] ); ?>" data-radius="<?php echo esc_attr( $atts['radius'] ); ?>" data-number="<?php echo esc_attr( $atts['number'] ); ?>" data-compact="<?php echo esc_attr( $atts['compact'] ); ?>">
				<img src="<?php echo WRE_PLUGIN_URL ?>/assets/images/loading.svg" />
			</div>
		<?php
			do_action( 'wre_enqueue_plugin_scripts' );
		return ob_get_clean();
	}

	/**
	 * List Agents shortcode.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function wre_agents( $atts ) {
		$atts = shortcode_atts( array(
			'view'				=> 'lists',
			'number'			=> wre_option('agents_archive_max_agents') ? wre_option('agents_archive_max_agents') : 10,
			'allow_pagination'	=> wre_option('agents_archive_allow_pagination') ? wre_option('agents_archive_allow_pagination') : 'yes',
			'items'				=> '2',
			'autoplay'			=> true,
			'effect'			=> 'slide',
			'dots'				=> true,
			'agents-view'		=> wre_option('wre_agents_mode') ? wre_option('wre_agents_mode') : 'list-view',
			'agent-columns'		=> wre_option('wre_archive_agents_columns') ? wre_option('wre_archive_agents_columns') : 2,
			'controls'			=> true,
			'loop'				=> true,
		), $atts );

		$agent_details = array();

		$agents_args = array(
			'role__in'	=> array( 'wre_agent', 'administrator' ),
			'number'	=> -1,
			'fields'	=> array( 'ID', 'user_email', 'display_name', 'user_url' )
		);

		$agents = get_users( $agents_args );
		if( !empty( $agents ) ) {
			foreach( $agents as $agent ) {
				if( user_can( $agent->ID, 'wre_agent' )) {
					$agent_details[] = array($agent);
				} else if( count_user_posts( $agent->ID, 'listing' ) > 0 ) {
					$agent_details[] = array($agent);
				}
			}
			if( !empty( $agent_details ) ) {
				$number = $atts['number'];
				$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
				if( $atts['view'] == 'lists' ) {
					$atts['total_agents'] = count( $agent_details );
					$agent_details = array_chunk($agent_details, $number, true);
					$agent_details = isset($agent_details[$paged-1]) ? $agent_details[$paged-1] : '';
				}

				if( $atts['view'] == 'carousel') {
					$agent_details = array_slice( $agent_details, 0, $number );
				}
			}
		}

		ob_start();
			do_action( 'wre_archive_agents', $agent_details, $atts );

			if( $atts['view'] == 'carousel' ) {
				wp_enqueue_style('wp-real-estate-lightslider');
				wp_enqueue_script('wp-real-estate-lightslider');
			}
			do_action( 'wre_enqueue_plugin_scripts' );
		return ob_get_clean();
	}

	/**
	 * Add the compact class to the listings
	 */
	public static function listings_compact_mode( $classes, $class = '', $post_id = '' ) {
		$classes[] = 'compact';
		return $classes;
	}

	/**
	 * Display a single listing.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function listing( $atts ) {
		if ( empty( $atts ) ) {
			return '';
		}

		$args = array(
			'post_type'			=> 'listing',
			'posts_per_page'	=> 1,
			'no_found_rows'		=> 1,
			'post_status'		=> 'publish',
		);

		if ( isset( $atts['id'] ) ) {
			$args['p'] = $atts['id'];
		}

		ob_start();

			$listings = new WP_Query( apply_filters( 'wre_shortcode_query', $args, $atts ) );

			if ( $listings->have_posts() ) : ?>

				<div id="listing-<?php the_ID(); ?>" class="wre-single">

					<?php while ( $listings->have_posts() ) : $listings->the_post(); ?>

						<?php wre_get_part( 'content-single-listing.php' ); ?>

					<?php endwhile; // end of the loop. ?>

				</div>

			<?php endif;

			wp_reset_postdata();

			do_action( 'wre_enqueue_plugin_scripts' );
		return ob_get_clean();
	}

	/**
	 * Display a single agent.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function agent( $atts ) {
		if ( empty( $atts ) ) {
			return '';
		}
		do_action( 'wre_enqueue_plugin_scripts' );
		return wre_get_single_agent_data( $atts['id'] );
	}

	/**
	 * List shortlisted listings shortcode.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function wre_shortlisted_listings( $atts ) {

		ob_start();
			$shortlisted_listings = wre_get_shortlisted_listings();
			if( ! empty( $shortlisted_listings ) ) {
				$shortlisted_listings = implode(",",$shortlisted_listings);
				echo '<div class="wre-shortlisted-wrapper">';
					echo do_shortcode('[wre_listings ids="' . $shortlisted_listings . '"]');
				echo '</div>';
			} else {
				_e('You haven\'t added any favorites.', 'wp-real-estate');
			}
			do_action( 'wre_enqueue_plugin_scripts' );
		return ob_get_clean();
	}

	/**
	 * Mortgage Calculator shortcode.
	 *
	 * @param array $atts
	 * @return string
	 */
	public static function wre_mortgage_calculator( $atts ) {

		ob_start();
		$amount = '';
		if( is_singular( 'listing' ) ) {
			$amount = absint( wre_meta( 'price' ) );
		}
		?>

			<form id="wre_mcalc_form" action="#" method="post">

				<div class="form-field">
					<label><?php _e( 'Price:', 'wp-real-estate' ); ?></label>
					<span>
						<input type="number" id="wre_mcalc_total_price" name="wre_mcalc_total_price" value="<?php echo esc_attr( $amount ); ?>" />
						<span><?php echo wre_currency_symbol(); ?></span>
					</span>
				</div>

				<div class="form-field">
					<label class="wre-long-label"><?php _e( 'Down Payment:', 'wp-real-estate' ); ?></label>
					<span style="display: none;">
						<input type="text" id="wre_mcalc_down_payment" name="wre_mcalc_down_payment" value="" />
						<span><?php echo wre_currency_symbol(); ?></span>
					</span>

					<span>
						<input id="wre_mcalc_down_payment_percent" name="wre_mcalc_down_payment_percent" type="number" step="1" min="0" max="100" size="5" value="10" />
						<span>%</span>
					</span>
				</div>

				<div class="form-field">
					<label><?php _e( 'Loan Term:', 'wp-real-estate' ); ?></label>
					<span>
						<input id="wre_mcalc_loan_term" name="wre_mcalc_loan_term" type="number" step="1" min="0" max="100" size="5" value="10" />
						<span><?php _e( 'years/fixed', 'wp-real-estate' ); ?></span>
					</span>
				</div>

				<div class="form-field">
					<label><?php _e( 'Interest Rate:', 'wp-real-estate' ); ?></label>
					<span>
						<input id="wre_mcalc_interest_rate" name="wre_mcalc_interest_rate" type="number" step="0.5" min="0" max="100" size="5" value="1" />
						<span>%</span>
					</span>
				</div>

				<div class="form-field">
					<label><?php _e( 'Tax:', 'wp-real-estate' ); ?></label>
					<span style="display: none;">
						<input type="text" id="wre_mcalc_property_tax" name="wre_mcalc_property_tax" value="" />
						<span><?php echo wre_currency_symbol(); ?></span>
					</span>

					<span class="wre-mortgage-percent">
						<input id="wre_mcalc_property_tax_percent" name="wre_mcalc_property_tax_percent" type="number" step="0.5" min="0" max="100" size="5" value="1" />
						<span><i>%</i><i><?php _e( 'per year', 'wp-real-estate' ); ?></i></span>
					</span>
				</div>

				<div class="form-field">
					<label><?php _e( 'Insurance:', 'wp-real-estate' ); ?></label>
					<span style="display: none;">
						<input type="text" id="wre_mcalc_property_insurance" name="wre_mcalc_property_insurance" value="" />
						<span><?php echo wre_currency_symbol(); ?></span>
					</span>

					<span class="wre-mortgage-percent">
						<input id="wre_mcalc_property_insurance_percent" name="wre_mcalc_property_insurance_percent" type="number" step="0.5" min="0" max="100" size="5" value="1" />
						<span><i>%</i><i><?php _e( 'per year', 'wp-real-estate' ); ?></i></span>
					</span>
				</div>

				<div class="form-result form-field">
					<p class="wre_pay_per_month">
						<span><?php echo __( 'Est. Payment:', 'wp-real-estate' ) . ' ' . wre_currency_symbol(); ?></span>
						<span class="wre-payment-response"></span>
						<span><?php _e( '/ per month', 'wp-real-estate' ); ?></span>
					</p>
					<span class="wre-payment-description"><?php _e( '(Payments are an estimate and may vary by lender)', 'wp-real-estate' ); ?></span>
				</div>

			</form>

		<?php
		do_action( 'wre_enqueue_plugin_scripts' );
		return ob_get_clean();
	}

}

return new WRE_Shortcodes();
