<?php
/**
 * Documentation Class
 *
 * @package errigal
 * @since 1.1.0
 */

namespace Errigal\Admin;

defined( 'ABSPATH' ) || exit;

use Errigal\Constant\{
	Errigal_Documentation_Hook as Documentation_Hook,
	Errigal_Locale as Locale,
};
use Errigal\Shared\{
	Errigal_Theme_Info as Theme_Info,
	Errigal_Validator as Validator,
};

/**
 * This class is in charge of providing documentation settings and functions.
 *
 * @since 1.1.0
 */
class Errigal_Documentation {
	/**
	 * Locale path segments.
	 *
	 * @since 1.1.0
	 *
	 * @var string
	 */
	private const LOCALE_PATH_SEGMENTS = array(
		Locale::JAPANESE => 'jp',
	);

	/**
	 * Gets documentation URL.
	 *
	 * @since 1.1.0
	 *
	 * @param string $documentation_relative_url Documentation relative URL.
	 * @return string
	 */
	public static function get_documentation_url( $documentation_relative_url ) {
		if ( ! Validator::is_non_empty_string( $documentation_relative_url ) ) {
			return '';
		}

		/**
		 * Filters documentation root URL.
		 *
		 * @since 1.1.0
		 *
		 * @param string $documentation_root_url Documentation root URL.
		 */
		$documentation_root_url = apply_filters(
			Documentation_Hook::DOCUMENTATION_ROOT_URL,
			self::get_documentation_root_url()
		);

		if ( ! Validator::is_non_empty_string( $documentation_root_url ) ) {
			return '';
		}

		return esc_url(
			trailingslashit( $documentation_root_url ) .
			trailingslashit( $documentation_relative_url )
		);
	}

	/**
	 * Gets documentation root URL.
	 *
	 * @since 1.1.0
	 *
	 * @return string
	 */
	private static function get_documentation_root_url() {
		$documentation_root_url = trailingslashit( Theme_Info::get_theme_author_uri( Theme_Info::IS_PARENT ) );

		if ( ! Validator::is_non_empty_string( $documentation_root_url ) ) {
			return '';
		}

		$locale_path_segment = self::get_locale_path_segment();

		if ( ! Validator::is_non_empty_string( $locale_path_segment ) ) {
			return esc_url( $documentation_root_url );
		}

		return esc_url(
			$documentation_root_url .
			trailingslashit( $locale_path_segment )
		);
	}

	/**
	 * Gets locale path segment.
	 *
	 * @since 1.1.0
	 *
	 * @return string
	 */
	private static function get_locale_path_segment() {
		$locale = get_locale();

		if ( ! Validator::is_non_empty_string( $locale ) ) {
			return '';
		}

		/**
		 * Filters documentation locale path segments.
		 *
		 * @since 1.2.0
		 *
		 * @param array $documentation_locale_path_segments Associative array of documentation locale path segments.
		 */
		$locale_path_segments = apply_filters(
			Documentation_Hook::DOCUMENTATION_LOCALE_PATH_SEGMENTS,
			self::LOCALE_PATH_SEGMENTS
		);

		if ( ! Validator::has_array_key( $locale_path_segments, $locale ) ) {
			return '';
		}

		return sanitize_key( $locale_path_segments[ $locale ] );
	}
}
