<?php
/**
 * Settings module.
 *
 * @package northmill-online-shared
 */

namespace Northmill_Online_Shared\Modules\Admin\Settings;

use Northmill_Online_Shared\Modules\Abstract_Module;
use Northmill_Online_Shared\Modules\Admin\Pages\Abstract_Admin_Page;

/**
 * Class Settings_Module
 */
class Settings_Module extends Abstract_Module {

	/**
	 * Settings array.
	 *
	 * @var array
	 */
	private array $settings;

	/**
	 * Get all settings from the main settings page.
	 *
	 * @return array|null
	 */
	public function get_settings(): ?array {
		if ( ! isset( $this->settings ) ) {
			$this->settings = $this->shared->admin->settings_fields->get_option(
				'setting',
				Abstract_Admin_Page::get_settings_id()
			);
		}
		return $this->settings;
	}

	/**
	 * Get specific setting from the main settings page.
	 *
	 * @param string $setting_key   Setting key.
	 * @param mixed  $default_value Value to return if setting not found.
	 *
	 * @return mixed|null
	 */
	public function get_setting( string $setting_key, mixed $default_value = null ): mixed {
		$settings = $this->get_settings();

		$setting = $settings[ $setting_key ] ?? $default_value;

		$setting = apply_filters(
			'northmill_online_shared_get_setting_' . $this->shared->package_info->get_service_name_underscored(),
			$setting,
			$setting_key,
			$default_value
		);

		return apply_filters(
			'northmill_online_shared_get_setting_' . $setting_key . '_' . $this->shared->package_info->get_service_name_underscored(),
			$setting,
			$default_value
		);
	}

	/**
	 * Set all settings.
	 *
	 * @param array $settings Settings to set.
	 *
	 * @return bool
	 */
	public function set_settings( array $settings ): bool {
		$updated = $this->shared->admin->settings_fields->update_option(
			'setting',
			Abstract_Admin_Page::get_settings_id(),
			$settings
		);
		if ( $updated ) {
			$this->settings = $settings;
		}

		return $updated;
	}

	/**
	 * Set a specific setting.
	 *
	 * @param string $setting_key Setting key.
	 * @param mixed  $value       Setting value.
	 *
	 * @return bool
	 */
	public function set_setting( string $setting_key, mixed $value ): bool {
		$settings                 = $this->get_settings();
		$settings[ $setting_key ] = $value;
		return $this->set_settings( $settings );
	}

	/**
	 * Check if a setting is enabled.
	 *
	 * @param string $key Setting key.
	 *
	 * @return bool
	 */
	public function is_setting_enabled( string $key ): bool {
		$setting = $this->get_setting( $key );
		return '1' === $setting || true === $setting || 'enabled' === $setting;
	}
}
