<?php
/**
 * Icon Libraries extension — global and per-library enable flags.
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Extensions\IconLibraries {

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

/**
 * WordPress option helpers for Icon Libraries settings.
 */
final class ExtensionSettings {

	/**
	 * @return bool
	 */
	public static function is_extension_enabled(): bool {
		$general = get_option( 'dsm_general', array() );

		if ( ! is_array( $general ) ) {
			return false;
		}

		if ( ! array_key_exists( 'dsm_use_icon_libraries', $general ) ) {
			return false;
		}

		return 'on' === $general['dsm_use_icon_libraries'];
	}

	/**
	 * Per-library enable flags (`dsm_icon_libraries` option).
	 *
	 * @return array<string, string>
	 */
	public static function get_library_settings(): array {
		$saved = get_option( 'dsm_icon_libraries', array() );

		if ( ! is_array( $saved ) ) {
			$saved = array();
		}

		IconLibraryRegistry::boot();

		/** @var array<string, string> $defaults */
		$defaults = array();

		foreach ( IconLibraryRegistry::all() as $library_id => $library ) {
			unset( $library );

			$defaults[ $library_id ] = 'tabler' === $library_id ? 'on' : 'off';
		}

		/** @var array<string, string> $merged */
		$merged = wp_parse_args( $saved, $defaults );

		return $merged;
	}

	/**
	 * @param string $library_id Library slug (e.g. tabler, phosphor).
	 * @return bool
	 */
	public static function is_library_enabled( string $library_id ): bool {
		if ( ! self::is_extension_enabled() ) {
			return false;
		}

		$settings = self::get_library_settings();

		return isset( $settings[ $library_id ] ) && 'on' === $settings[ $library_id ];
	}
}

}

namespace {

use DiviSupreme\Extensions\IconLibraries\ExtensionSettings;

if ( ! function_exists( 'dsm_is_icon_libraries_extension_enabled' ) ) {
	/** @return bool */
	function dsm_is_icon_libraries_extension_enabled(): bool {
		return ExtensionSettings::is_extension_enabled();
	}
}

if ( ! function_exists( 'dsm_get_icon_libraries_settings' ) ) {
	/** @return array<string, string> */
	function dsm_get_icon_libraries_settings(): array {
		return ExtensionSettings::get_library_settings();
	}
}

if ( ! function_exists( 'dsm_is_icon_library_enabled' ) ) {
	/** @return bool */
	function dsm_is_icon_library_enabled( string $library_id ): bool {
		return ExtensionSettings::is_library_enabled( $library_id );
	}
}

}
