<?php
/**
 * Handles API environments.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts;

use Northmill_Online_Shared\Abstract_Shared_Base;
use Northmill_Online_Shared\Helpers\Hook_Helpers;
use Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Settings;
use Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;

defined( 'ABSPATH' ) || exit;

/**
 * Class Envs
 */
class Envs {

	public const SETTING_NAME = 'sync_env';

	/**
	 * Validate passed API environment.
	 *
	 * @param null|string $env Environment to validate. Can be 'current' to get the current environment.
	 *
	 * @return null|string Valid environment. If $env is invalid, the default environment is returned.
	 */
	public static function validate_env( ?string $env ): ?string {
		if ( is_null( $env ) ) {
			return null;
		} elseif ( 'current' === $env ) {
			return self::get_current_env();
		} elseif ( self::is_env_valid( $env ) ) {
			return $env;
		} else {
			Abstract_Shared_Base::base_instance()->logger->log(
				'hub-accounts',
				'Fell back to default environment from invalid environment',
				array(
					'invalid-env' => $env,
				),
				Log_Level_Enum::ERROR
			);

			return self::get_default_env();
		}
	}

	/**
	 * Get current environment.
	 *
	 * @return string
	 */
	public static function get_current_env(): string {
		/**
		 * Shared instance.
		 *
		 * @var Abstract_Shared_Base $shared_instance
		 */
		$shared_instance = Hook_Helpers::apply_scoped_filters(
			'northmill_shared_instance_setting_up_hub_accounts',
			Abstract_Shared_Base::base_instance()
		);

		$env = $shared_instance->admin->settings->get_setting(
			self::SETTING_NAME,
			''
		);

		/**
		 * This is a fallback for when the environment was set to 'current' in settings.
		 * It should never happen, but if it does, it would cause a loop.
		 * So we will just set it to the default environment.
		 */
		if ( 'current' === $env ) {
			$env = self::get_default_env();
		}

		return self::validate_env( $env );
	}

	/**
	 * Get all valid environment.
	 *
	 * @return array Array of valid environments.
	 */
	public static function get_valid_envs(): array {
		return array(
			'prod' => __( 'Production', 'northmill-online-shared' ),
			'test' => __( 'Test', 'northmill-online-shared' ),
		);
	}

	/**
	 * Get key of the default API environment.
	 *
	 * @return string
	 */
	public static function get_default_env(): string {
		return 'test';
	}

	/**
	 * Check if an environment is valid.
	 *
	 * @param string $env The environment to check.
	 *
	 * @return bool
	 */
	public static function is_env_valid( string $env ): bool {
		$envs = self::get_valid_envs();

		return isset( $envs[ $env ] );
	}
}
