<?php
/**
 * Class SettingsAssets
 *
 * @package DhlPolska\WooCommerceSettings
 */

namespace DhlPolska\WooCommerceSettings;

use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Adds settings assets.
 */
class SettingsAssets implements Hookable {

	public const HANDLE = 'dhl_polska_admin_settings';

	private string $assets_url;

	private string $scripts_version;

	public function __construct( string $assets_url, string $scripts_version ) {
		$this->assets_url      = $assets_url;
		$this->scripts_version = $scripts_version;
	}

	/**
	 * @return void
	 */
	public function hooks() {
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
	}

	/**
	 * @return void
	 */
	public function enqueue_assets() {
		if ( ! $this->is_settings_page() ) {
			return;
		}

		$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

		wp_register_script(
			self::HANDLE,
			$this->assets_url . 'js/admin-settings' . $suffix . '.js',
			[],
			$this->scripts_version,
			true
		);
		wp_enqueue_script( self::HANDLE );
	}

	private function is_settings_page(): bool {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}

		$screen = get_current_screen();
		if ( ! $screen instanceof \WP_Screen ) {
			return false;
		}

		if ( 'woocommerce_page_wc-settings' !== $screen->id ) {
			return false;
		}

		global $current_tab, $current_section;

		return 'shipping' === (string) $current_tab
			&& WooCommerceDHLPolskaSettingsPage::SECTION_ID === (string) $current_section;
	}
}
