<?php
/**
 * Class ConnectionStatusField
 *
 * @package DhlPolska\WooCommerceSettings\Field
 */

namespace DhlPolska\WooCommerceSettings\Field;

use DhlPolska\WooCommerceSettings\SettingsAssets;
use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Register Connection Status Field.
 */
class ConnectionStatusField implements Hookable {

	public const FIELD_TYPE = 'dhl_polska_connection_status';

	/**
	 * Hooks.
	 */
	public function hooks() {
		add_action(
			'woocommerce_admin_field_' . self::FIELD_TYPE,
			[
				$this,
				'output_connection_status',
			]
		);
	}

	/**
	 * @param array $value .
	 *
	 * @return void
	 */
	public function output_connection_status( $value ) {
		$ajax = isset( $value['ajax'] ) && is_array( $value['ajax'] ) ? $value['ajax'] : [];

		wp_enqueue_script( SettingsAssets::HANDLE );
		wp_add_inline_script(
			SettingsAssets::HANDLE,
			sprintf(
				'window.dhlPolskaConnectionStatusQueue = window.dhlPolskaConnectionStatusQueue || []; window.dhlPolskaConnectionStatusQueue.push(%s);',
				wp_json_encode(
					[
						'result_field_id' => (string) ( $value['id'] ?? '' ) . '_result',
						'action'          => (string) ( $ajax['action'] ?? '' ),
						'nonce'           => (string) ( $ajax['nonce'] ?? '' ),
						'url'             => (string) ( $ajax['url'] ?? '' ),
					]
				)
			),
			'before'
		);

		include __DIR__ . '/views/html-connection-status-field.php';
	}
}
