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

if (!class_exists('WRE_Agency_Frontend')) :

	/**
	 * The main class
	 *
	 * @since 1.0.0
	 */
	class WRE_Agency_Frontend {

		public $archive_page = null;

		/**
		 * Main constructor
		 *
		 * @since 1.0.0
		 */
		public function __construct() {
			// Hook into actions & filters
			$this->archive_page = wre_option('agency_archives_page');
			$this->hooks();
		}

		/**
		 * Hook in to actions & filters
		 *
		 * @since 1.0.0
		 */
		public function hooks() {
			add_filter('is_wre', array($this, 'is_wre'));
			add_filter('wre_get_raw_address', array($this, 'get_agency_address'));
			add_filter('wre_archive_page_title', array($this, 'archive_page_title'));
			add_action('wp_ajax_wre_agency_orderby_value', array( $this, 'wre_orderby_data' ));
			add_action('wp_ajax_nopriv_wre_agency_orderby_value', array( $this, 'wre_orderby_data' ));
		}
		
		/**
		 * Orderby Ajax Filter
		 *
		 */
		public function wre_orderby_data() {
			$orderby = $_POST['order_by'];
			$paged = $_POST['search_data'];
			// Get order + orderby args from string
			$orderby_value = explode('-', $orderby);
			$orderby = esc_attr($orderby_value[0]);
			if ($orderby == 'date') {
				$order = 'desc';
			} else {
				$order = !empty($orderby_value[1]) ? $orderby_value[1] : 'asc';
				$orderby = strtolower($orderby);
				$order = strtoupper($order);
			}
			$posts_per_page = wre_default_posts_number();
			$agency_args = array(
				'post_type' => 'agency',
				'post_status' => 'publish',
				'posts_per_page' => $posts_per_page,
				'paged' => $paged,
				'orderby' => $orderby,
				'order' => $order
			);

			$agency_query = new WP_Query($agency_args);

			ob_start();

				while ($agency_query->have_posts()) : $agency_query->the_post();
					wre_get_part('content-agency.php');
				endwhile;

			echo $agencies = ob_get_clean();
			die();
		}

		/**
		 * Ensure our CSS and JS is loaded on agency pages
		 *
		 */
		public function is_wre($return) {
			if (is_page($this->archive_page) || is_post_type_archive('agency') || is_singular(array('agency'))) {
				$return = true;
			}
			return $return;
		}

		/**
		 * Modify the address used for the maps JS 
		 * get the agency address when on agency page
		 *
		 */
		public function get_agency_address($address) {
			if (is_singular(array('agency'))) {
				$address = wre_agency_meta('address');
			}
			return $address;
		}

		/**
		 * Get the archive page title
		 *
		 */
		public function archive_page_title($page_title) {
			if (is_page($this->archive_page)) {
				$page_title = get_the_title($this->archive_page);
			}
			return $page_title;
		}

	}

	endif;

return new WRE_Agency_Frontend();