<?php //phpcs:ignore

/**
 * Class responsible for Autocomplete Settings.
 *
 * @package WLC\Algolia
 */

namespace wlc_algolia;

use function wlc_algolia\Helpers\wlc_retrieve_post_type_data;

defined( 'ABSPATH' ) || die( 'Direct file access is forbidden' );

/**
 * Autocomplete class
 */
class Autocomplete extends Client_Helper {
	/**
	 * Autocomplete configuration.
	 *
	 * @var array $autocomplete_configuration Autocomplete configuration.
	 */
	protected array $autocomplete_configuration;

	/**
	 * Init method.
	 *
	 * @return void`
	 */
	public function init(): void {
		$enable_autocomplete = '';

		$this->autocomplete_configuration = (array) get_option( 'wlc_algolia_settings_autocomplete' );
		if ( ! $this->wlc_check_algolia_api_credentials() ) {
			return;
		}

		if ( isset( $this->autocomplete_configuration['enable-autocomplete'] ) ) {
			$enable_autocomplete = esc_attr( $this->autocomplete_configuration['enable-autocomplete'] );
		}

		if ( '1' === $enable_autocomplete ) {
			add_filter( 'page_template', array( $this, 'wlc_algolia_search_page' ) );
		}

		$this->create_custom_page();
	}

	/**
	 * Create custom page.
	 *
	 * @return void
	 */
	public function create_custom_page(): void {
		$args = array(
			'post_type'      => 'page',
			'post_title'     => esc_html( __( 'Algolia Search', 'wlc-search-integration-with-algolia' ) ),
			'post_status'    => 'publish',
			'posts_per_page' => 1,
		);

		$existing_page = new \WP_Query( $args );

		if ( ! $existing_page->have_posts() ) {
			wp_insert_post(
				array(
					'post_title'  => esc_html( __( 'Algolia Search', 'wlc-search-integration-with-algolia' ) ),
					'post_status' => 'publish',
					'post_type'   => 'page',
				)
			);
		}
	}

	/**
	 * Display Algolia Search.
	 *
	 * Development purpose only.
	 *
	 * @param string $page_template The template to display.
	 *
	 * @return string
	 */
	public function wlc_algolia_search_page( string $page_template ): string {
		if ( is_page( 'algolia-search' ) ) {
			$page_template = WLC_ALGOLIA_PLUGIN_DIR_PATH . 'includes/templates/frontend/algolia-search.php';
		}

		return $page_template;
	}

	/**
	 * Prepare autocomplete settings for script
	 *
	 * @return array
	 */
	public function prepare_autocomplete_script_data(): array {
		$config   = array();
		$settings = array(
			'application_id' => (string) $this->algolia_settings->get_application_id(),
			'search_api_key' => (string) $this->algolia_settings->get_search_api_key(),
		);

		if ( ! empty( $this->autocomplete_configuration ) ) {
			foreach ( $this->autocomplete_configuration as $post_type => $autocomplete_config ) {
				$config[] = $autocomplete_config;
			}

			$settings['autocomplete'] = array(
				'sources' => $config,
			);
		}

		return $settings;
	}
}
