<?php //phpcs:disable
/**
 * Class responsible for retrieving settings for Algolia.
 *
 * @package WLC_Algolia
 */

namespace wlc_algolia;

/**
 * Class Algolia_Settings_Options.
 *
 */
class Algolia_Settings_Options {
 //phpcs:enable
	/**
	 * Algolia Settings Options.
	 *
	 * @var ?Algolia_Settings_Options $algolia_settings_options
	 */
	protected static ?Algolia_Settings_Options $algolia_settings_options = null;

	/**
	 * Settings option name.
	 *
	 * @var string $option_name
	 */
	protected static string $algolia_settings_name = 'wlc_algolia_settings_general';

	/**
	 * Settings Options Instance.
	 *
	 * @return Algolia_Settings_Options|null
	 */
	public static function settings_options_instance(): ?Algolia_Settings_Options {
		if ( null === self::$algolia_settings_options ) {
			self::$algolia_settings_options = new Algolia_Settings_Options();
		}

		return self::$algolia_settings_options;
	}

	/**
	 * Get Settings value.
	 *
	 * @param string $tab Tab name.
	 * @param string $key Settings key name.
	 *
	 * @return string
	 */
	public function get_settings_option_value( string $tab, string $key ): string {
		$value = self::get_algolia_settings( $key, $tab );

		return $value ? esc_attr( (string) $value ) : '';
	}

	/**
	 * Retrieve Algolia Settings.
	 *
	 * @param string $key Settings key name.
	 * @param string $tab the name of tab to retrieve settings from.
	 *
	 * @return array
	 */
	public static function get_algolia_settings( string $key, string $tab = 'general' ): mixed {
		$settings = get_option( self::$algolia_settings_name );

		if ( ! empty( $settings[ $tab ][ $key ] ) ) {
			return $settings[ $tab ][ $key ];
		}

		return '';
	}

	/**
	 * Get Application ID.
	 *
	 * @return string
	 */
	public function get_application_id(): string {
		return esc_attr( self::get_algolia_settings( 'application_id' ) );
	}

	/**
	 * Get Write API Key.
	 *
	 * @return string
	 */
	public function get_write_api_key(): string {
		return esc_attr( self::get_algolia_settings( 'write_api_key' ) );
	}

	/**
	 * Get Search API Key.
	 *
	 * @return string
	 */
	public function get_search_api_key(): string {
		return esc_attr( self::get_algolia_settings( 'search_api_key' ) );
	}

	/**
	 * Get Index Name.
	 *
	 * @return string
	 */
	public function get_index_name(): string {
		return esc_attr( self::get_algolia_settings( 'index_name' ) );
	}

	/**
	 * Get pagination limit (Algolia paginationLimitedTo).
	 *
	 * @return int
	 */
	public function get_pagination_limited_to(): int {
		$value = absint( (string) self::get_algolia_settings( 'pagination_limited_to' ) );
		if ( 0 === $value ) {
			$value = 1000;
		}

		return (int) max( 1000, min( 20000, $value ) );
	}
}
