<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @package    MaplePress
 * @subpackage MaplePress/includes
 */

class MaplePress_Public {

	/**
	 * The ID of this plugin.
	 *
	 * @var string
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @var string
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param string $plugin_name The name of the plugin.
	 * @param string $version     The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
		$this->version     = $version;
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 */
	public function enqueue_styles() {
		wp_enqueue_style(
			$this->plugin_name,
			MAPLEPRESS_PLUGIN_URL . 'assets/css/maplepress-public.css',
			array(),
			$this->version,
			'all'
		);
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 */
	public function enqueue_scripts() {
		wp_enqueue_script(
			$this->plugin_name,
			MAPLEPRESS_PLUGIN_URL . 'assets/js/maplepress-public.js',
			array( 'jquery' ),
			$this->version,
			false
		);
	}

	/**
	 * Intercept WordPress search and use MaplePress search instead.
	 *
	 * @param WP_Query $query The WordPress query object.
	 */
	public function intercept_search( $query ) {
		// Debug logging - detect if this is from CLI test
		$is_cli_test = isset( $_SERVER['HTTP_X_MAPLEPRESS_TEST'] );

		// Log every invocation when WP_DEBUG is on or when it's a CLI test
		if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
			error_log( '=== MaplePress intercept_search called ===' );
			error_log( 'is_main_query: ' . ( $query->is_main_query() ? 'true' : 'false' ) );
			error_log( 'is_search: ' . ( $query->is_search() ? 'true' : 'false' ) );
			error_log( 's param: ' . var_export( $query->get( 's' ), true ) );
			error_log( 'CLI test header: ' . ( $is_cli_test ? 'true' : 'false' ) );
		}

		// Only intercept main search queries
		// Check both is_search() and presence of 's' parameter to catch all search scenarios
		$is_search_query = $query->is_search() || ! empty( $query->get( 's' ) );

		if ( ! $query->is_main_query() || ! $is_search_query ) {
			if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
				error_log( 'MaplePress: Early return - not main query or not search' );
			}
			return;
		}

		// Check if MaplePress is enabled
		$options = get_option( 'maplepress_settings' );
		if ( empty( $options['enabled'] ) || empty( $options['api_url'] ) || empty( $options['api_key'] ) ) {
			// MaplePress not enabled or configured, use default WordPress search
			if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
				error_log( 'MaplePress: Early return - not enabled or not configured' );
				error_log( 'enabled: ' . var_export( $options['enabled'] ?? null, true ) );
				error_log( 'api_url: ' . var_export( $options['api_url'] ?? null, true ) );
				error_log( 'api_key present: ' . ( ! empty( $options['api_key'] ) ? 'yes' : 'no' ) );
			}
			return;
		}

		// Check if connection is verified
		if ( empty( $options['is_verified'] ) ) {
			if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
				error_log( 'MaplePress: Early return - connection not verified' );
			}
			return;
		}

		// Check if search is enabled for the current context
		// Speed test queries always proceed regardless of admin/frontend settings
		if ( ! $is_speed_test ) {
			$is_admin_area = is_admin();
			$frontend_search_enabled = isset( $options['enable_frontend_search'] ) ? $options['enable_frontend_search'] : true;
			$admin_search_enabled = isset( $options['enable_admin_search'] ) ? $options['enable_admin_search'] : false;

			// Skip if admin search is not enabled and we're in admin
			if ( $is_admin_area && ! $admin_search_enabled ) {
				// In admin but admin search not enabled
				if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
					error_log( 'MaplePress: Early return - admin search not enabled' );
				}
				return;
			}

			// Skip if frontend search is not enabled and we're on frontend
			if ( ! $is_admin_area && ! $frontend_search_enabled ) {
				// On frontend but frontend search not enabled
				if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
					error_log( 'MaplePress: Early return - frontend search not enabled' );
				}
				return;
			}
		} else {
			if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
				error_log( 'MaplePress: Speed test query - bypassing admin/frontend check' );
			}
		}

		// Get the search query
		// Try get_search_query() first, then fall back to direct query parameter
		$search_query = get_search_query();
		if ( empty( $search_query ) ) {
			$search_query = $query->get( 's' );
		}
		if ( empty( $search_query ) ) {
			if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
				error_log( 'MaplePress: Early return - empty search query' );
			}
			return;
		}

		if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
			error_log( 'MaplePress: Proceeding with search for: ' . $search_query );
		}

		// Call MaplePress search API
		require_once MAPLEPRESS_PLUGIN_DIR . 'includes/class-maplepress-api-client.php';
		$api_client = new MaplePress_API_Client( $options['api_url'], $options['api_key'] );

		$search_args = array(
			'limit'  => (int) $query->get( 'posts_per_page', 10 ),
			'offset' => (int) ( ( $query->get( 'paged', 1 ) - 1 ) * $query->get( 'posts_per_page', 10 ) ),
		);

		if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
			error_log( 'MaplePress: Calling API with query: ' . $search_query );
			error_log( 'MaplePress: API URL: ' . $options['api_url'] );
			error_log( 'MaplePress: Search args: ' . json_encode( $search_args ) );
		}

		$result = $api_client->search( $search_query, $search_args );

		if ( is_wp_error( $result ) ) {
			// API error - fall back to default WordPress search
			// Log the error for debugging
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'MaplePress search error: ' . $result->get_error_message() );
			}
			if ( $is_cli_test ) {
				error_log( 'MaplePress search error (CLI test): ' . $result->get_error_message() );
			}
			return;
		}

		if ( ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || $is_cli_test ) {
			error_log( 'MaplePress: API call successful, results: ' . json_encode( $result ) );
		}

		// Extract page IDs from MaplePress results
		$page_ids = array();
		if ( ! empty( $result['hits'] ) ) {
			foreach ( $result['hits'] as $result_item ) {
				// Meilisearch returns 'id' field, not 'page_id'
				if ( ! empty( $result_item['id'] ) ) {
					$page_ids[] = (int) $result_item['id'];
				}
			}
		}

		// If no results, show empty results
		if ( empty( $page_ids ) ) {
			$query->set( 'post__in', array( 0 ) ); // Force no results
		} else {
			// Set query to only return posts matching MaplePress results in the correct order
			$query->set( 'post__in', $page_ids );
			$query->set( 'orderby', 'post__in' ); // Maintain MaplePress result order

			// In admin context, respect the existing post_type filter (e.g., 'page' when in Pages list)
			// On frontend, allow any post type
			if ( ! is_admin() ) {
				$query->set( 'post_type', 'any' ); // Allow any post type on frontend
			}
			// Note: In admin, we preserve whatever post_type was already set by WordPress

			$query->set( 'post_status', 'publish' );

			// Disable the default search query
			$query->set( 's', '' );
		}

		// Store the original search query for display
		$query->set( 'maplepress_search_query', $search_query );

		// Store total results for pagination
		if ( ! empty( $result['total_hits'] ) ) {
			add_filter( 'found_posts', function( $found_posts, $query ) use ( $result ) {
				if ( $query->get( 'maplepress_search_query' ) ) {
					return (int) $result['total_hits'];
				}
				return $found_posts;
			}, 10, 2 );
		}
	}

	/**
	 * Restore the search query for display purposes.
	 *
	 * @param string $search_query The search query.
	 * @return string
	 */
	public function restore_search_query( $search_query ) {
		global $wp_query;
		$maplepress_query = $wp_query->get( 'maplepress_search_query' );
		if ( ! empty( $maplepress_query ) ) {
			return $maplepress_query;
		}
		return $search_query;
	}
}
