<?php
/**
 * Live Filter features.
 * 
 * @since 1.3.0
 */
namespace Greyd\Query;

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

new Live_Filter($config);
class Live_Filter {

	/**
	 * Holds the plugin config
	 */
	private $config;

	/**
	 * Constructor
	 */
	public function __construct($config) {

		// check if Gutenberg is active.
		if (!function_exists('register_block_type')) return;

		// set config
		$this->config = (object) $config;

		// setup
		if (!function_exists('get_plugin_data')) require_once(ABSPATH . '/wp-admin/includes/plugin.php');
		$this->config->plugin_version = get_plugin_data($this->config->plugin_file)['Version'];

		// add live Filter feature
		add_action( 'rest_api_init', array( $this, 'register_route'), 1 );
	}
	
	/**
	 * Register the endpoint.
	 */
	public function register_route() {
		
		register_rest_route( GREYD_REST_NAMESPACE, '/livequery', array(
			'methods' => 'POST',
			'callback' => array($this, 'do_live_query'),
			'permission_callback' => '__return_true'
		));

	}

	/**
	 * Build new query
	 * 
	 * @param \WP_REST_Request $request
	 * 
	 * @return array
	 *      @property string block_content    rendered query as HTML string.
	 */
	public function do_live_query( $request ) {

		// get data from request
		$data = wp_parse_args($request->get_json_params());
		// var_error_log($data);

		$block = json_decode( $data['block'], true );
		// var_error_log($block);

		if (
			isset($block['attrs']['query']['query']['taxQueryRelationship']) &&
			$block['attrs']['query']['query']['taxQueryRelationship'] == 'OR'
		) {
			/**
			 * Add filter to set tax_query relationship to 'OR'
			 * this way the multiselect works as expected, selecting posts that have
			 * either term set.
			 * 
			 * @since 1.3.2
			 */
			add_filter( 'greyd_query_filter_tax_query_relationship', function( $relationship, $query_args ) {
				return 'OR';
			}, 10, 2 );
		}

		/**
		 * During rest requests, there is no global post object set.
		 * Advanced filters need this info, so we emulate it before rendering the new query.
		 * @since 1.14.0
		 */
		if (
			isset($block['attrs']['query']['advancedFilter']) &&
			isset($data['postId']) &&
			intval($data['postId']) > 0
		) {
			global $post;
			$post = get_post( intval($data['postId']) );
		}

		/**
		 * During rest requests, the global wp_query object is empty (not set).
		 * Conditional Content need this info, e.g. in archive templates,
		 * so we emulate it before rendering by combining the wp_query with the block query
		 * @since 1.14.0
		 */
		if ( isset($data['wp_query']) ) {
			global $wp_query;
			// block query
			$query_args = \Greyd\Dynamic\Dynamic_Helper::build_query( $block['attrs']['query'], 1 );
			// original wp_query
			$query_args = array_merge( $query_args, json_decode( $data['wp_query'], true ) );
			// new wp_query
			$wp_query = new \WP_Query( $query_args );
		}

		/**
		 * Get query tags after globals are set up.
		 * fixes disapearing pagination and other undesired effects after live-query reload.
		 * @since 2.1.0
		 */
		$tags = \Greyd\Dynamic\Render_Blocks::get_query_tags($block['attrs']['query']);
		$block['attrs']['queryTags'] = $tags;
		// debug($tags);

		// render
		$block_content = (new Query_Block( $block, '<ul' ))->render( array('update' => true) );

		/**
		 * Get core layout styles.
		 * Styles from the core/gutenberg style engine are not rendered in the block_content
		 * and may duplicate classes from the original page content.
		 * We replace these classes with unique ones and render the styles manually.
		 * @since 1.14.1
		 */
		$block_content = \Greyd\Enqueue::replace_core_css_classes_in_block_content( $block_content );
		$stylesheets   = \Greyd\Enqueue::get_all_custom_stylesheets();

		return array(
			'block_content' => $block_content . $stylesheets
		);

	}
}