<?php

if (!defined('ABSPATH')) {
	exit;
}

class R123_WC_Settings {
	public const OPTION_KEY = 'r123_wc_settings';

	public static function init(): void {
		add_action('admin_init', [self::class, 'register_settings']);
	}

	public static function register_settings(): void {
		register_setting(
			'r123_wc_settings_group',
			self::OPTION_KEY,
			[
				'type'              => 'array',
				'sanitize_callback' => [self::class, 'sanitize'],
				'default'           => self::defaults(),
			]
		);

		add_settings_section(
			'r123_wc_main',
			'Osnovne nastavitve',
			static function () {
				echo '<p class="description">Vnesite Webhook URL in API ključ iz Račun123. Vtičnik pošlje podatke naročila neposredno v Račun123, ko WooCommerce naročilo označite kot Zaključeno (Completed).</p>';
			},
			'r123-wc-settings'
		);

		$fields = [
			'webhook_url' => 'Webhook URL',
			'api_key'     => 'API ključ',
		];

		foreach ($fields as $key => $label) {
			add_settings_field(
				$key,
				$label,
				[self::class, 'render_field'],
				'r123-wc-settings',
				'r123_wc_main',
				[
					'key'   => $key,
					'label' => $label,
				]
			);
		}
	}

	public static function defaults(): array {
		return [
			'webhook_url' => '',
			'api_key'     => '',
		];
	}

	public static function get(?string $key = null, $default = null) {
		$settings = get_option(self::OPTION_KEY, self::defaults());

		if ($key === null) {
			return $settings;
		}

		return $settings[$key] ?? $default;
	}

	public static function sanitize(array $input): array {
		$defaults = self::defaults();

		return [
			'webhook_url' => esc_url_raw($input['webhook_url'] ?? $defaults['webhook_url']),
			'api_key'     => sanitize_text_field($input['api_key'] ?? $defaults['api_key']),
		];
	}

	public static function render_field(array $args): void {
		$key   = $args['key'];
		$value = self::get($key, '');

		$type = ($key === 'api_key') ? 'password' : 'text';
		$autocomplete = ($key === 'api_key') ? 'new-password' : 'off';
		$placeholder = '';

		if ($key === 'webhook_url') {
			$placeholder = 'https://moj.racun123.si/api/integrations/woocommerce-plugin?companyId=YOUR_COMPANY_ID';
		}
		?>
		<input
			type="<?php echo esc_attr($type); ?>"
			class="regular-text"
			name="<?php echo esc_attr(self::OPTION_KEY . '[' . $key . ']'); ?>"
			value="<?php echo esc_attr((string) $value); ?>"
			placeholder="<?php echo esc_attr($placeholder); ?>"
			autocomplete="<?php echo esc_attr($autocomplete); ?>"
			spellcheck="false"
			autocapitalize="off"
			autocorrect="off"
			data-lpignore="true"
			data-1p-ignore="true"
		>
		<?php if ($key === 'webhook_url') : ?>
			<p class="description">Sem prilepite Webhook URL iz Račun123 WooCommerce Integracije.</p>
		<?php endif; ?>
		<?php if ($key === 'api_key') : ?>
			<p class="description">Sem prilepite API ključ iz Račun123 WooCommerce integracije.</p>
		<?php endif; ?>
		<?php
	}
}
