<?php

namespace CelerSearch\Search;

use CelerSearch\Interfaces\IRegistrable;
use WP_Query;

/**
 * Redirects WordPress search to a user-chosen page with the [celersearch] shortcode
 *
 * When the "Replace Search Results Page" feature is enabled on the WordPress Public Search area
 * and a page is selected, this class redirects ?s=query to that page with ?q=query.
 */
class SearchPageOverride implements IRegistrable {

	/**
	 * Cached active area config
	 *
	 * @var array|null
	 */
	private ?array $active_area = null;

	/**
	 * Whether the active area has been resolved
	 *
	 * @var bool
	 */
	private bool $resolved = false;

	/**
	 * @inheritDoc
	 */
	public function register(): void {
		add_action( 'pre_get_posts', [ $this, 'maybe_skip_query_interception' ], 9 );
		add_action( 'template_redirect', [ $this, 'maybe_redirect' ] );
	}

	/**
	 * Redirect WordPress search to the configured search page
	 *
	 * @return void
	 */
	public function maybe_redirect(): void {
		if ( ! is_search() || is_admin() ) {
			return;
		}

		$area = $this->get_active_area();
		if ( ! $area ) {
			return;
		}

		$page_id = (int) ( $area['features']['search_page']['page_id'] ?? 0 );
		if ( ! $page_id ) {
			return;
		}

		// Prevent redirect loop
		if ( get_queried_object_id() === $page_id ) {
			return;
		}

		$page_url = get_permalink( $page_id );
		if ( ! $page_url ) {
			return;
		}

		$redirect_url = add_query_arg( 'q', rawurlencode( get_search_query() ), $page_url );
		wp_safe_redirect( $redirect_url, 302 );
		exit;
	}

	/**
	 * Get the active WordPress Public Search area with search_page feature enabled
	 *
	 * @return array|null
	 */
	private function get_active_area(): ?array {
		if ( $this->resolved ) {
			return $this->active_area;
		}
		$this->resolved = true;

		$settings = get_option( 'celersearch_settings', [] );
		if ( empty( $settings['enable_search'] ) ) {
			return null;
		}

		foreach ( $settings['search_areas'] ?? [] as $area ) {
			if ( ( $area['type'] ?? '' ) !== 'wordpress_public_search' ) {
				continue;
			}
			if ( empty( $area['enabled'] ) ) {
				continue;
			}

			$feature = $area['features']['search_page'] ?? false;
			$enabled = is_array( $feature ) ? ! empty( $feature['enabled'] ) : ! empty( $feature );
			if ( $enabled ) {
				$this->active_area = $area;
				return $area;
			}
		}

		return null;
	}

	/**
	 * Prevent QueryIntegration from intercepting the main search query
	 * when the search page replacement is active
	 *
	 * @param WP_Query $query
	 *
	 * @return void
	 */
	public function maybe_skip_query_interception( WP_Query $query ): void {
		if ( ! $query->is_main_query() || is_admin() || ! $query->get( 's' ) ) {
			return;
		}

		if ( $this->get_active_area() ) {
			$query->set( 'celersearch', false );
		}
	}
}
