<?php
/**
 * Admin settings page.
 *
 * @package Kramar
 * @since   1.0.0
 */

declare( strict_types=1 );

namespace Kramar;

// Prevent direct access.
defined( 'ABSPATH' ) || exit;

/**
 * Settings class.
 *
 * @since 1.0.0
 */
final class Settings {

	/**
	 * Option name in the database.
	 *
	 * @since 1.0.0
	 */
	public const OPTION_NAME = 'kramar_settings';

	/**
	 * Settings group name for the Settings API.
	 *
	 * @since 1.0.0
	 */
	private const SETTINGS_GROUP = 'kramar';

	/**
	 * Settings page slug.
	 *
	 * @since 1.0.0
	 */
	private const PAGE_SLUG    = 'kramar';
	private const MODULES_SLUG = 'kramar-modules';

	/**
	 * Tools sub-page slug.
	 *
	 * @since 1.0.0
	 */

	/**
	 * Settings sub-page slug.
	 */
	private const SETTINGS_SUBPAGE_SLUG = 'kramar-settings';

	/**
	 * Hook suffix returned by add_menu_page().
	 *
	 * @since 1.0.0
	 */
	private string $hook_suffix    = '';
	private string $modules_hook   = '';

	/**
	 * Hook suffix for the tools page.
	 *
	 * @since 1.0.0
	 */
	private string $settings_hook_suffix = '';

	/**
	 * Human-readable labels for module categories.
	 *
	 * @since 1.0.0
	 * @var array<string, string>
	 */
	private const CATEGORY_LABELS = [
		'performance' => 'Performance',
		'checkout'    => 'Checkout',
		'orders'      => 'Orders',
		'products'    => 'Products',
		'compliance'  => 'Compliance',
		'marketing'   => 'Marketing',
		'email'       => 'Email',
		'account'     => 'Account',
		'shipping'    => 'Shipping',
	];

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param Plugin $plugin Main plugin instance.
	 */
	public function __construct( private Plugin $plugin ) {}

	/**
	 * Register all admin hooks.
	 *
	 * @since 1.0.0
	 */
	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'add_settings_page' ] );
		add_action( 'admin_init', [ $this, 'register_settings' ] );
		add_action( 'admin_init', [ $this, 'preserve_active_tab' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
		add_filter( 'plugin_action_links_' . KRAMAR_BASENAME, [ $this, 'add_plugin_settings_link' ] );
		add_action( 'wp_ajax_kramar_dismiss_setup', [ $this, 'ajax_dismiss_setup' ] );
	}

	/**
	 * Register the top-level Kramar menu and its sub-pages.
	 *
	 * @since 1.0.0
	 */
	public function add_settings_page(): void {
		$this->hook_suffix = (string) add_menu_page(
			__( 'Kramar', 'kramar' ),
			__( 'Kramar', 'kramar' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render_dashboard' ],
			'dashicons-superhero',
			58
		);

		add_submenu_page(
			self::PAGE_SLUG,
			__( 'Dashboard', 'kramar' ),
			__( 'Dashboard', 'kramar' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render_dashboard' ]
		);

		$this->modules_hook = (string) add_submenu_page(
			self::PAGE_SLUG,
			__( 'Modules', 'kramar' ),
			__( 'Modules', 'kramar' ),
			'manage_options',
			self::MODULES_SLUG,
			[ $this, 'render_settings_page' ]
		);

		$this->settings_hook_suffix = (string) add_submenu_page(
			self::PAGE_SLUG,
			__( 'Settings', 'kramar' ),
			__( 'Settings', 'kramar' ),
			'manage_options',
			self::SETTINGS_SUBPAGE_SLUG,
			[ $this, 'render_settings_subpage' ]
		);
	}

	/**
	 * Append the active tab to the redirect URL after a settings save.
	 *
	 * @since 1.0.0
	 */
	public function preserve_active_tab(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by options.php; we only read a tab slug.
		if ( ! isset( $_POST['option_page'] ) || self::SETTINGS_GROUP !== $_POST['option_page'] ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$tab = isset( $_POST['kramar_active_tab'] ) ? sanitize_key( wp_unslash( $_POST['kramar_active_tab'] ) ) : '';
		if ( '' === $tab ) {
			return;
		}

		add_filter(
			'wp_redirect',
			static function ( string $location ) use ( $tab ): string {
				if ( str_contains( $location, 'page=kramar' ) ) {
					return add_query_arg( 'tab', $tab, $location );
				}
				return $location;
			}
		);
	}

	/**
	 * Register the setting with the Settings API.
	 *
	 * @since 1.0.0
	 */
	public function register_settings(): void {
		register_setting(
			self::SETTINGS_GROUP,
			self::OPTION_NAME,
			[
				'type'              => 'array',
				'sanitize_callback' => [ $this, 'sanitize_settings' ],
				'default'           => $this->plugin->get_defaults(),
			]
		);
	}

	/**
	 * Sanitize settings before saving to the database.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $input Raw form input.
	 * @return array<string, mixed> Sanitized settings.
	 */
	public function sanitize_settings( mixed $input ): array {
		$sanitized = [];

		if ( ! is_array( $input ) ) {
			return $this->plugin->get_defaults();
		}

		foreach ( $this->plugin->get_modules() as $module ) {
			$category     = $module->get_category();
			$slug         = $module->get_slug();
			$module_input = $input[ $category ][ $slug ] ?? [];

			$sanitized[ $category ][ $slug ] = $module->sanitize_settings(
				is_array( $module_input ) ? $module_input : []
			);
		}

		$sanitized['_full_cleanup'] = ! empty( $input['_full_cleanup'] );

		return $sanitized;
	}

	/**
	 * Enqueue settings page CSS and JS.
	 *
	 * @since 1.0.0
	 *
	 * @param string $hook_suffix The current admin page hook suffix.
	 */
	public function enqueue_assets( string $hook_suffix ): void {
		if ( ! in_array( $hook_suffix, [ $this->hook_suffix, $this->modules_hook, $this->settings_hook_suffix ], true ) ) {
			return;
		}

		wp_enqueue_style(
			'kramar-admin',
			KRAMAR_URL . 'assets/css/admin.css',
			[],
			KRAMAR_VERSION
		);

		if ( $hook_suffix === $this->hook_suffix ) {
			// Dashboard: dismiss-setup AJAX.
			wp_register_script( 'kramar-dashboard', false, [], KRAMAR_VERSION, true );
			wp_enqueue_script( 'kramar-dashboard' );
			wp_localize_script(
				'kramar-dashboard',
				'kramarDismissSetup',
				[
					'ajaxUrl' => admin_url( 'admin-ajax.php' ),
					'nonce'   => wp_create_nonce( 'kramar_dismiss_setup' ),
				]
			);
			wp_add_inline_script(
				'kramar-dashboard',
				'(function(){
	var btn = document.querySelector(\'.kramar-setup__dismiss\');
	if (!btn) return;
	btn.addEventListener(\'click\', function(){
		document.getElementById(\'kramar-setup\').style.display = \'none\';
		fetch(kramarDismissSetup.ajaxUrl, {
			method: \'POST\',
			headers: {\'Content-Type\':\'application/x-www-form-urlencoded\'},
			body: \'action=kramar_dismiss_setup&_ajax_nonce=\' + kramarDismissSetup.nonce
		});
	});
})();'
			);
		}

		if ( $hook_suffix === $this->modules_hook ) {
			wp_enqueue_script(
				'kramar-tabs',
				KRAMAR_URL . 'assets/js/tabs.js',
				[],
				KRAMAR_VERSION,
				true
			);
			wp_enqueue_script(
				'kramar-modules-admin',
				KRAMAR_URL . 'assets/js/modules-admin.js',
				[],
				(string) filemtime( KRAMAR_DIR . 'assets/js/modules-admin.js' ),
				true
			);
		}

		if ( $hook_suffix === $this->settings_hook_suffix ) {
			wp_enqueue_media();
			wp_enqueue_style(
				'kramar-email-manager',
				KRAMAR_URL . 'assets/css/email-manager.css',
				[],
				(string) filemtime( KRAMAR_DIR . 'assets/css/email-manager.css' )
			);
			wp_enqueue_script(
				'kramar-email-manager',
				KRAMAR_URL . 'assets/js/email-manager.js',
				[],
				(string) filemtime( KRAMAR_DIR . 'assets/js/email-manager.js' ),
				true
			);
			wp_localize_script(
				'kramar-email-manager',
				'kramarEmailManager',
				[
					'ajaxUrl' => admin_url( 'admin-ajax.php' ),
					'nonce'   => wp_create_nonce( 'kramar_email_manager' ),
					'i18n'    => [
						'saved'       => __( 'Settings saved.', 'kramar' ),
						'saving'      => __( 'Saving...', 'kramar' ),
						'saved_ok'    => __( 'Saved!', 'kramar' ),
						'save_error'  => __( 'Error', 'kramar' ),
						'save_all'    => __( 'Save All Settings', 'kramar' ),
						'media_wait'  => __( 'Media library is still loading — please try again in a moment.', 'kramar' ),
						'media_title' => __( 'Select Brand Logo', 'kramar' ),
						'media_btn'   => __( 'Use this logo', 'kramar' ),
					],
				]
			);
			wp_add_inline_script(
				'kramar-email-manager',
				'(function(){
	var btn = document.querySelector(\'.kramar-settings-save\');
	if (!btn) return;
	var ajaxUrl = kramarEmailManager.ajaxUrl;
	var nonce   = kramarEmailManager.nonce;
	var i18n    = kramarEmailManager.i18n;
	btn.addEventListener(\'click\', function(){
		btn.disabled = true;
		btn.textContent = i18n.saving;
		var forms = document.querySelectorAll(\'.kramar-settings-form\');
		var pending = forms.length;
		var ok = true;
		forms.forEach(function(form){
			var data = new FormData(form);
			data.append(\'action\', form.getAttribute(\'data-save-action\'));
			data.append(\'_ajax_nonce\', nonce);
			fetch(ajaxUrl, { method:\'POST\', body: new URLSearchParams(data) })
				.then(function(r){ return r.json(); })
				.then(function(res){ if (!res.success) ok = false; })
				.catch(function(){ ok = false; })
				.finally(function(){
					pending--;
					if (pending === 0) {
						btn.disabled = false;
						btn.textContent = ok ? i18n.saved_ok : i18n.save_error;
						setTimeout(function(){ btn.textContent = i18n.save_all; }, 2000);
					}
				});
		});
	});
})();

(function(){
	var wrap = document.querySelector(\'.kramar-bd-logo\');
	if (!wrap) return;
	var input   = wrap.querySelector(\'input[name="logo_url"]\');
	var preview = wrap.querySelector(\'.kramar-bd-logo__preview\');
	var upload  = wrap.querySelector(\'.kramar-bd-logo__upload\');
	var remove  = wrap.querySelector(\'.kramar-bd-logo__remove\');
	var frame;
	var i18n = kramarEmailManager.i18n;

	upload.addEventListener(\'click\', function(){
		if (typeof wp === \'undefined\' || !wp.media) {
			window.alert(i18n.media_wait);
			return;
		}
		if (frame) { frame.open(); return; }
		frame = wp.media({
			title: i18n.media_title,
			button: { text: i18n.media_btn },
			library: { type: \'image\' },
			multiple: false
		});
		frame.on(\'select\', function(){
			var a = frame.state().get(\'selection\').first().toJSON();
			var url = (a.sizes && a.sizes.medium) ? a.sizes.medium.url : a.url;
			input.value = url;
			preview.src = url;
			preview.style.display = \'\';
			remove.style.display = \'\';
		});
		frame.open();
	});

	remove.addEventListener(\'click\', function(){
		input.value = \'\';
		preview.src = \'\';
		preview.style.display = \'none\';
		remove.style.display = \'none\';
	});
})();',
				'after'
			);
		}
	}

	/**
	 * Add a "Settings" link on the Plugins list page.
	 *
	 * @since 1.0.0
	 *
	 * @param array<string, string> $links Existing plugin action links.
	 * @return array<string, string> Modified links with Settings prepended.
	 */
	public function add_plugin_settings_link( array $links ): array {
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=' . self::MODULES_SLUG ) ),
			esc_html__( 'Settings', 'kramar' )
		);

		array_unshift( $links, $settings_link );

		return $links;
	}

	public function render_dashboard(): void {
		$modules  = $this->plugin->get_modules();
		$settings = $this->plugin->get_settings();
		$biz      = get_option( 'kramar_business_details', [] );
		$global   = get_option( 'kramar_email_settings', [] );
		$overrides = get_option( 'kramar_email_overrides', [] );

		// ── Gather module data ──
		$enabled_count = 0;
		$by_category   = [];
		$active_impact = [];
		$privacy_mod   = null;

		foreach ( $modules as $module ) {
			$cat  = $module->get_category();
			$slug = $module->get_slug();
			$on   = ! empty( $settings[ $cat ][ $slug ]['enabled'] );
			if ( $on ) {
				$enabled_count++;
			}
			$by_category[ $cat ] = ( $by_category[ $cat ] ?? 0 ) + ( $on ? 1 : 0 );
			if ( $module instanceof \Kramar\Modules\Compliance\Privacy_Hardening && $on ) {
				$privacy_mod = $module;
			}
		}

		// ── Active module impact lines ──
		$s = $settings;
		if ( ! empty( $s['performance']['cart-fragments']['enabled'] ) ) {
			$active_impact[] = __( 'Cart fragments disabled on non-cart pages', 'kramar' );
		}
		if ( ! empty( $s['performance']['dequeue-assets']['enabled'] ) ) {
			$active_impact[] = __( 'Unnecessary WC CSS/JS removed from frontend', 'kramar' );
		}
		if ( ! empty( $s['performance']['wc-cleanup']['enabled'] ) ) {
			$active_impact[] = __( 'WC admin bloat, remote logging & marketing stripped', 'kramar' );
		}
		if ( ! empty( $s['compliance']['legal-checkboxes']['enabled'] ) ) {
			$active_impact[] = __( 'EU legal checkboxes on checkout (terms, privacy, digital waiver)', 'kramar' );
		}
		if ( ! empty( $s['compliance']['order-button']['enabled'] ) ) {
			$btn_text = $s['compliance']['order-button']['button_text'] ?? '';
			$active_impact[] = $btn_text
				/* translators: %s is the custom order button label text */
				? sprintf( __( 'Order button: "%s"', 'kramar' ), $btn_text )
				: __( 'Custom order button text', 'kramar' );
		}
		if ( ! empty( $s['compliance']['privacy-hardening']['enabled'] ) ) {
			$active_impact[] = __( 'IP anonymization, PII cleanup crons active', 'kramar' );
		}
		if ( ! empty( $s['checkout']['address-validation']['enabled'] ) ) {
			$active_impact[] = __( 'NL/BE/DE house number validation on checkout', 'kramar' );
		}
		if ( ! empty( $s['checkout']['vat-id']['enabled'] ) ) {
			$active_impact[] = __( 'VAT ID field with format validation', 'kramar' );
		}
		if ( ! empty( $s['checkout']['field-editor']['enabled'] ) ) {
			$field_count = count( array_merge(
				(array) get_option( 'kramar_checkout_fields_billing', [] ),
				(array) get_option( 'kramar_checkout_fields_shipping', [] ),
				(array) get_option( 'kramar_checkout_fields_additional', [] )
			) );
			$active_impact[] = $field_count
				/* translators: %d is the number of custom checkout fields */
				? sprintf( __( '%d custom checkout fields', 'kramar' ), $field_count )
				: __( 'Checkout field editor active', 'kramar' );
		}
		if ( ! empty( $s['orders']['sequential-numbers']['enabled'] ) ) {
			$prefix = $s['orders']['sequential-numbers']['prefix'] ?? '';
			$active_impact[] = $prefix
				/* translators: %s is the order number prefix string */
				? sprintf( __( 'Sequential order numbering (prefix: %s)', 'kramar' ), $prefix )
				: __( 'Sequential order numbering active', 'kramar' );
		}
		if ( ! empty( $s['orders']['custom-statuses']['enabled'] ) ) {
			$status_count = count( get_option( 'kramar_custom_order_statuses', [] ) );
			if ( $status_count ) {
				/* translators: %d is the number of custom order statuses */
				$active_impact[] = sprintf( __( '%d custom order status(es)', 'kramar' ), $status_count );
			}
		}
		if ( ! empty( $s['orders']['refund-return']['enabled'] ) ) {
			$active_impact[] = __( 'EU 14-day withdrawal/return system active', 'kramar' );
		}
		if ( ! empty( $s['products']['omnibus']['enabled'] ) ) {
			$active_impact[] = __( 'Omnibus 30-day price history tracking', 'kramar' );
		}
		if ( ! empty( $s['products']['swatches']['enabled'] ) ) {
			$active_impact[] = __( 'Color/image swatches on product pages', 'kramar' );
		}
		if ( ! empty( $s['email']['email-manager']['enabled'] ) ) {
			$customized = count( array_filter( array_keys( $overrides ), fn( $k ) => '_template' !== $k && ! empty( $overrides[ $k ]['blocks'] ) ) );
			$active_impact[] = $customized
				/* translators: %d is the number of customized email templates */
				? sprintf( __( 'Email builder active, %d email(s) customized', 'kramar' ), $customized )
				: __( 'Email builder active', 'kramar' );
		}

		// ── Action items ──
		$actions = [];

		$biz_required = [ 'company_name', 'kvk_number', 'vat_number', 'company_address', 'email' ];
		$biz_missing  = array_filter( $biz_required, fn( $k ) => empty( $biz[ $k ] ?? '' ) );
		if ( ! empty( $biz_missing ) ) {
			/* translators: %s is a comma-separated list of missing business detail field names */
			$actions[] = [ 'severity' => 'error', 'text' => sprintf( __( 'Missing business details: %s', 'kramar' ), implode( ', ', $biz_missing ) ), 'link' => admin_url( 'admin.php?page=' . self::SETTINGS_SUBPAGE_SLUG ) ];
		}

		if ( ! is_ssl() ) {
			$actions[] = [ 'severity' => 'error', 'text' => __( 'No HTTPS — customer data transmitted unencrypted', 'kramar' ), 'link' => '' ];
		}

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			$actions[] = [ 'severity' => 'warn', 'text' => __( 'Debug mode on — WC logs may contain customer PII', 'kramar' ), 'link' => '' ];
		}

		if ( $privacy_mod ) {
			foreach ( $privacy_mod->get_retention_warnings() as $w ) {
				$actions[] = [ 'severity' => 'warn', 'text' => $w, 'link' => admin_url( 'admin.php?page=wc-settings&tab=account' ) ];
			}
		}

		$tpl = $overrides['_template'] ?? [];
		if ( empty( $tpl['header_blocks'] ) && empty( $tpl['footer_blocks'] ) ) {
			$actions[] = [ 'severity' => 'info', 'text' => __( 'Email header & footer not customized yet', 'kramar' ), 'link' => admin_url( 'admin.php?page=kramar-email-builder&email_id=_template' ) ];
		}

		// ── EU Compliance checklist ──
		$compliance = [
			[ ! empty( $biz['company_name'] ) && ! empty( $biz['kvk_number'] ), __( 'KVK on correspondence', 'kramar' ), __( 'Handelsregisterwet Art. 29', 'kramar' ) ],
			[ ! empty( $biz['vat_number'] ), __( 'VAT number on invoices', 'kramar' ), __( 'VAT Directive Art. 226', 'kramar' ) ],
			[ ! empty( $biz['email'] ), __( 'Business email in emails', 'kramar' ), __( 'eCommerce Directive Art. 5', 'kramar' ) ],
			[ ! empty( $biz['company_address'] ), __( 'Address on correspondence', 'kramar' ), __( 'Handelsregisterwet Art. 29', 'kramar' ) ],
			// Enabled isn't enough: a checkbox whose {..._link} placeholder has no
			// page behind it renders the document name as plain, unclickable
			// text, and the right of withdrawal has to be reachable at the point
			// of purchase. Fail the check so this surfaces where compliance is
			// actually reviewed, not only on the module's own panel.
			[
				! empty( $s['compliance']['legal-checkboxes']['enabled'] )
					&& ! \Kramar\Modules\Compliance\Legal_Checkboxes::has_unlinked_placeholder(),
				__( 'Legal checkboxes on checkout', 'kramar' ),
				__( 'GDPR Art. 7 · CRD Art. 6(1)(h)', 'kramar' ),
			],
			[ ! empty( $s['compliance']['order-button']['enabled'] ), __( 'Order button with payment obligation', 'kramar' ), __( 'CRD Art. 8(2)', 'kramar' ) ],
			[ ! empty( $s['orders']['refund-return']['enabled'] ), __( 'Withdrawal/return system', 'kramar' ), __( 'BW Art. 6:230o', 'kramar' ) ],
			[ ! empty( $s['compliance']['privacy-hardening']['enabled'] ), __( 'Privacy hardening', 'kramar' ), __( 'GDPR Art. 25', 'kramar' ) ],
			[ is_ssl(), __( 'HTTPS encryption', 'kramar' ), __( 'GDPR Art. 32', 'kramar' ) ],
		];
		$compliance_passed = count( array_filter( $compliance, fn( $c ) => $c[0] ) );

		// ── Setup steps ──
		$tpl          = $overrides['_template'] ?? [];
		$tpl_done     = ! empty( $tpl['header_blocks'] ) || ! empty( $tpl['footer_blocks'] );
		$sender_done  = ! empty( $global['from_name'] ) || ! empty( $global['from_email'] );
		$biz_done     = ! empty( $biz['company_name'] ) && ! empty( $biz['kvk_number'] ) && ! empty( $biz['vat_number'] ) && ! empty( $biz['company_address'] ) && ! empty( $biz['email'] );
		$compliance_on = ! empty( $s['compliance']['legal-checkboxes']['enabled'] ) && ! empty( $s['compliance']['order-button']['enabled'] );
		$dismissed    = get_option( 'kramar_setup_dismissed', false );

		$setup_steps = [
			[ 'done' => $enabled_count > 0,  'label' => __( 'Enable modules', 'kramar' ),               'desc' => __( 'Choose which features to activate', 'kramar' ),                          'link' => admin_url( 'admin.php?page=' . self::MODULES_SLUG ) ],
			[ 'done' => $biz_done,            'label' => __( 'Business details', 'kramar' ),             'desc' => __( 'Company name, KVK, VAT — legally required', 'kramar' ),                   'link' => admin_url( 'admin.php?page=' . self::SETTINGS_SUBPAGE_SLUG ) ],
			[ 'done' => $sender_done,         'label' => __( 'Email sender', 'kramar' ),                 'desc' => __( 'Set your from name and email address', 'kramar' ),                        'link' => admin_url( 'admin.php?page=' . self::SETTINGS_SUBPAGE_SLUG ) ],
			[ 'done' => $tpl_done,            'label' => __( 'Email template', 'kramar' ),               'desc' => __( 'Add your logo and customize header/footer', 'kramar' ),                   'link' => admin_url( 'admin.php?page=kramar-email-builder&email_id=_template' ) ],
			[ 'done' => $compliance_on,       'label' => __( 'Checkout compliance', 'kramar' ),           'desc' => __( 'Legal checkboxes and order button text', 'kramar' ),                     'link' => admin_url( 'admin.php?page=' . self::MODULES_SLUG . '&tab=compliance' ) ],
		];
		$setup_done  = count( array_filter( $setup_steps, fn( $s ) => $s['done'] ) );
		$setup_total = count( $setup_steps );
		$setup_complete = $setup_done === $setup_total;

		// ── Render ──
		$order_count   = (int) wp_count_posts( 'shop_order' )->{'wc-completed'} + (int) wp_count_posts( 'shop_order' )->{'wc-processing'};
		$product_count = (int) wp_count_posts( 'product' )->publish;
		if ( class_exists( 'Automattic\WooCommerce\Utilities\OrderUtil' ) && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
			$order_count = (int) wc_orders_count( 'completed' ) + (int) wc_orders_count( 'processing' );
		}

		?>
		<div class="wrap kramar-settings">
			<h1><?php esc_html_e( 'Kramar', 'kramar' ); ?></h1>

			<?php if ( ! $dismissed || ! $setup_complete ) : ?>
				<div class="kramar-setup" id="kramar-setup">
					<div class="kramar-setup__header">
						<div>
							<h2><?php echo $setup_complete ? esc_html__( 'Setup complete!', 'kramar' ) : esc_html__( 'Get started', 'kramar' ); ?></h2>
							<span class="kramar-setup__progress"><?php echo esc_html( $setup_done . '/' . $setup_total ); ?></span>
						</div>
						<?php if ( $setup_complete ) : ?>
							<button type="button" class="kramar-setup__dismiss" title="<?php esc_attr_e( 'Dismiss', 'kramar' ); ?>">&times;</button>
						<?php endif; ?>
					</div>
					<div class="kramar-setup__bar">
						<div class="kramar-setup__bar-fill" style="width:<?php echo esc_attr( (string) round( $setup_done / $setup_total * 100 ) ); ?>%;"></div>
					</div>
					<div class="kramar-setup__steps">
						<?php foreach ( $setup_steps as $i => $step ) : ?>
							<div class="kramar-setup__step <?php echo $step['done'] ? 'kramar-setup__step--done' : ''; ?>">
								<span class="kramar-setup__step-num"><?php echo $step['done'] ? '<span class="dashicons dashicons-yes-alt"></span>' : esc_html( (string) ( $i + 1 ) ); ?></span>
								<div class="kramar-setup__step-body">
									<strong><?php echo esc_html( $step['label'] ); ?></strong>
									<span><?php echo esc_html( $step['desc'] ); ?></span>
								</div>
								<?php if ( ! $step['done'] ) : ?>
									<a href="<?php echo esc_url( $step['link'] ); ?>" class="button button-small"><?php esc_html_e( 'Set up', 'kramar' ); ?></a>
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>

			<div class="kramar-dash-metrics">
				<div class="kramar-metric">
					<span class="kramar-metric__value"><?php echo esc_html( $enabled_count . '/' . count( $modules ) ); ?></span>
					<span class="kramar-metric__label"><?php esc_html_e( 'Modules Active', 'kramar' ); ?></span>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . self::MODULES_SLUG ) ); ?>" class="kramar-metric__link"><?php esc_html_e( 'Manage', 'kramar' ); ?></a>
				</div>
				<div class="kramar-metric">
					<span class="kramar-metric__value kramar-metric__value--<?php echo $compliance_passed === count( $compliance ) ? 'green' : ( $compliance_passed >= 6 ? 'amber' : 'red' ); ?>"><?php echo esc_html( $compliance_passed . '/' . count( $compliance ) ); ?></span>
					<span class="kramar-metric__label"><?php esc_html_e( 'EU Compliance', 'kramar' ); ?></span>
					<a href="#kramar-compliance" class="kramar-metric__link"><?php esc_html_e( 'Details', 'kramar' ); ?></a>
				</div>
				<div class="kramar-metric">
					<span class="kramar-metric__value"><?php echo esc_html( (string) $product_count ); ?></span>
					<span class="kramar-metric__label"><?php esc_html_e( 'Products', 'kramar' ); ?></span>
				</div>
				<div class="kramar-metric">
					<span class="kramar-metric__value"><?php echo esc_html( (string) $order_count ); ?></span>
					<span class="kramar-metric__label"><?php esc_html_e( 'Orders', 'kramar' ); ?></span>
				</div>
			</div>

			<div class="kramar-dash-main">
				<div class="kramar-dash-left">
					<?php if ( ! empty( $actions ) ) : ?>
						<div class="kramar-dashboard-card">
							<h2><?php esc_html_e( 'Action Required', 'kramar' ); ?></h2>
							<div class="kramar-checklist">
								<?php foreach ( $actions as $a ) : ?>
									<div class="kramar-check kramar-check--<?php echo esc_attr( $a['severity'] ); ?>">
										<span class="kramar-check__icon dashicons <?php echo 'error' === $a['severity'] ? 'dashicons-dismiss' : ( 'warn' === $a['severity'] ? 'dashicons-warning' : 'dashicons-info-outline' ); ?>"></span>
										<span class="kramar-check__body"><?php echo esc_html( $a['text'] ); ?></span>
										<?php if ( $a['link'] ) : ?>
											<a href="<?php echo esc_url( $a['link'] ); ?>" class="kramar-check__link"><?php esc_html_e( 'Fix', 'kramar' ); ?></a>
										<?php endif; ?>
									</div>
								<?php endforeach; ?>
							</div>
						</div>
					<?php endif; ?>

					<div class="kramar-dashboard-card">
						<h2><?php esc_html_e( 'What Kramar Is Doing', 'kramar' ); ?></h2>
						<?php if ( empty( $active_impact ) ) : ?>
							<p style="color:#787c82;margin:0;"><?php esc_html_e( 'No modules enabled yet.', 'kramar' ); ?> <a href="<?php echo esc_url( admin_url( 'admin.php?page=' . self::MODULES_SLUG ) ); ?>"><?php esc_html_e( 'Enable modules', 'kramar' ); ?></a></p>
						<?php else : ?>
							<ul class="kramar-impact-list">
								<?php foreach ( $active_impact as $line ) : ?>
									<li><?php echo esc_html( $line ); ?></li>
								<?php endforeach; ?>
							</ul>
						<?php endif; ?>
					</div>
				</div>

				<div class="kramar-dash-right">
					<div class="kramar-dashboard-card" id="kramar-compliance">
						<h2><?php esc_html_e( 'EU Compliance', 'kramar' ); ?></h2>
						<div class="kramar-checklist">
							<?php foreach ( $compliance as $c ) : ?>
								<div class="kramar-check <?php echo $c[0] ? 'kramar-check--ok' : 'kramar-check--error'; ?>">
									<span class="kramar-check__icon dashicons <?php echo $c[0] ? 'dashicons-yes-alt' : 'dashicons-no-alt'; ?>"></span>
									<div class="kramar-check__body">
										<strong><?php echo esc_html( $c[1] ); ?></strong>
										<span class="kramar-check__value"><?php echo esc_html( $c[2] ); ?></span>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					</div>

					<div class="kramar-dashboard-card kramar-dash-env">
						<h2><?php esc_html_e( 'Environment', 'kramar' ); ?></h2>
						<div class="kramar-env-list">
							<div><span>WooCommerce</span><span><?php echo esc_html( defined( 'WC_VERSION' ) ? WC_VERSION : '—' ); ?></span></div>
							<div><span>HPOS</span><span><?php echo class_exists( 'Automattic\WooCommerce\Utilities\OrderUtil' ) && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ? 'Enabled' : 'Disabled'; ?></span></div>
							<div><span>PHP</span><span><?php echo esc_html( PHP_VERSION ); ?></span></div>
							<div><span>WordPress</span><span><?php echo esc_html( get_bloginfo( 'version' ) ); ?></span></div>
							<div><span>Theme</span><span><?php echo esc_html( wp_get_theme()->get( 'Name' ) ); ?></span></div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the modules settings page.
	 *
	 * @since 1.0.0
	 */
	public function render_settings_page(): void {
		$categories = [];
		foreach ( $this->plugin->get_modules() as $module ) {
			$categories[ $module->get_category() ][] = $module;
		}

		$enabled_count = 0;
		$total_count   = 0;
		foreach ( $categories as $mods ) {
			foreach ( $mods as $m ) {
				$total_count++;
				if ( $m->is_enabled() ) {
					$enabled_count++;
				}
			}
		}

		$full_cleanup = ! empty( $this->plugin->get_settings()['_full_cleanup'] );

		?>
		<div class="wrap kramar-settings kramar-modules-page">
			<div class="kramar-modules-header">
				<div class="kramar-modules-header__left">
					<h1><?php esc_html_e( 'Modules', 'kramar' ); ?></h1>
					<span class="kramar-modules-header__count"><?php echo esc_html( $enabled_count . '/' . $total_count ); ?></span>
				</div>
				<div class="kramar-modules-header__right">
					<input type="search" class="kramar-modules-search" placeholder="<?php esc_attr_e( 'Search modules...', 'kramar' ); ?>" id="kramar-module-search" />
					<button type="submit" form="kramar-modules-form" class="button button-primary"><?php esc_html_e( 'Save', 'kramar' ); ?></button>
				</div>
			</div>

			<div class="kramar-modules-layout">
				<nav class="kramar-modules-nav">
					<?php foreach ( $categories as $cat_slug => $mods ) : ?>
						<a href="#kramar-cat-<?php echo esc_attr( $cat_slug ); ?>" class="kramar-modules-nav__link"><?php echo esc_html( self::CATEGORY_LABELS[ $cat_slug ] ?? ucfirst( $cat_slug ) ); ?><span><?php echo esc_html( (string) count( $mods ) ); ?></span></a>
					<?php endforeach; ?>
					<a href="#kramar-cat-data" class="kramar-modules-nav__link kramar-modules-nav__link--muted"><?php esc_html_e( 'Data & Uninstall', 'kramar' ); ?></a>
				</nav>

				<div class="kramar-modules-content">
					<form method="post" action="options.php" id="kramar-modules-form">
						<?php settings_fields( self::SETTINGS_GROUP ); ?>

						<?php foreach ( $categories as $cat_slug => $mods ) : ?>
							<div class="kramar-modules-section" id="kramar-cat-<?php echo esc_attr( $cat_slug ); ?>">
								<h2 class="kramar-modules-section__title"><?php echo esc_html( self::CATEGORY_LABELS[ $cat_slug ] ?? ucfirst( $cat_slug ) ); ?></h2>
								<?php foreach ( $mods as $module ) : ?>
									<?php $this->render_module_card( $module ); ?>
								<?php endforeach; ?>
							</div>
						<?php endforeach; ?>

						<div class="kramar-modules-section" id="kramar-cat-data">
							<h2 class="kramar-modules-section__title"><?php esc_html_e( 'Data & Uninstall', 'kramar' ); ?></h2>
							<div class="kramar-module kramar-module--danger">
								<div class="kramar-module__row">
									<div class="kramar-module__toggle">
										<label class="kramar-toggle" for="kramar-full-cleanup">
											<input type="checkbox" id="kramar-full-cleanup" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[_full_cleanup]" value="1" <?php checked( $full_cleanup ); ?> />
											<span class="kramar-toggle__slider"></span>
										</label>
									</div>
									<div class="kramar-module__info">
										<h3 class="kramar-module__name"><?php esc_html_e( 'Remove all data on delete', 'kramar' ); ?></h3>
										<p class="kramar-module__description"><?php esc_html_e( 'Wipe all settings and data when the plugin is deleted from the Plugins screen. Irreversible.', 'kramar' ); ?></p>
									</div>
								</div>
							</div>
						</div>
					</form>

					<?php
					foreach ( $categories as $cat_slug => $cat_modules ) {
						foreach ( $cat_modules as $module ) {
							$module->render_management_ui( '' );
						}
					}
					?>
				</div>
			</div>
		</div>

		<?php
	}

	/**
	 * Render the Tools placeholder page.
	 *
	 * @since 1.0.0
	 */
	public function render_settings_subpage(): void {
		$global  = [];
		$biz     = [];

		// Pull settings from Email Manager if it exists.
		foreach ( $this->plugin->get_modules() as $module ) {
			if ( $module instanceof \Kramar\Modules\Email\Email_Manager ) {
				$global = $module->get_global_settings();
				$biz    = $module->get_business_details();
				break;
			}
		}

		$biz_fields = [
			'company_name'    => [ __( 'Company Name (Handelsnaam)', 'kramar' ), 'text', __( 'Required on all business correspondence (Handelsregisterwet Art. 29)', 'kramar' ) ],
			'statutory_name'  => [ __( 'Statutory Name (Statutaire naam)', 'kramar' ), 'text', __( 'Required for BV/NV if different from trade name (BW Art. 2:177)', 'kramar' ) ],
			'company_address' => [ __( 'Address (Vestigingsadres)', 'kramar' ), 'textarea', __( 'Required on invoices and all emails (Art. 226 + Handelsregisterwet)', 'kramar' ) ],
			'statutory_seat'  => [ __( 'Statutory Seat (Statutaire zetel)', 'kramar' ), 'text', __( 'Required for BV/NV (BW Art. 2:177)', 'kramar' ) ],
			'kvk_number'      => [ __( 'KVK Number', 'kramar' ), 'text', __( 'Required on ALL correspondence incl. emails. Non-compliance = fine up to &euro;25,750.', 'kramar' ) ],
			'vat_number'      => [ __( 'VAT Number (BTW-ID)', 'kramar' ), 'text', __( 'Required on invoices (Art. 226) + emails (eCommerce Directive Art. 5). ZZP: use BTW-ID, NOT OB-nummer.', 'kramar' ) ],
			'legal_form'      => [ __( 'Legal Form (Rechtsvorm)', 'kramar' ), 'text', __( 'B.V., N.V., VOF, Eenmanszaak, etc. Required for BV/NV.', 'kramar' ) ],
			'iban'            => [ __( 'IBAN', 'kramar' ), 'text', __( 'Not legally required but standard practice on invoices.', 'kramar' ) ],
			'email'           => [ __( 'Business Email', 'kramar' ), 'email', __( 'Required in emails (eCommerce Directive Art. 5)', 'kramar' ) ],
			'phone'           => [ __( 'Phone', 'kramar' ), 'tel', __( 'Required in order confirmation (CRD Art. 6(1)(c))', 'kramar' ) ],
		];

		?>
		<div class="wrap kramar-settings">
			<div style="display:flex;align-items:center;justify-content:space-between;margin:0 0 20px;">
				<h1 style="margin:0;padding:0;"><?php esc_html_e( 'Settings', 'kramar' ); ?></h1>
				<button type="button" class="button button-primary kramar-settings-save"><?php esc_html_e( 'Save All Settings', 'kramar' ); ?></button>
			</div>

			<div class="kramar-settings-grid">
				<div class="kramar-settings-card">
					<h2><?php esc_html_e( 'Email Sender', 'kramar' ); ?></h2>
					<p class="kramar-settings-card__desc"><?php esc_html_e( 'Default sender for all outgoing emails. Per-email overrides available.', 'kramar' ); ?></p>
					<form class="kramar-em-global-form kramar-settings-form" data-save-action="kramar_email_save_global">
						<div class="kramar-settings-field">
							<label for="kramar-from-name"><?php esc_html_e( 'From Name', 'kramar' ); ?></label>
							<input type="text" id="kramar-from-name" name="from_name" value="<?php echo esc_attr( $global['from_name'] ?? '' ); ?>" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" />
						</div>
						<div class="kramar-settings-field">
							<label for="kramar-from-email"><?php esc_html_e( 'From Email', 'kramar' ); ?></label>
							<input type="email" id="kramar-from-email" name="from_email" value="<?php echo esc_attr( $global['from_email'] ?? '' ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>" />
						</div>
						<div class="kramar-settings-field">
							<label for="kramar-reply-to"><?php esc_html_e( 'Reply-To', 'kramar' ); ?></label>
							<input type="email" id="kramar-reply-to" name="reply_to" value="<?php echo esc_attr( $global['reply_to'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'Same as From', 'kramar' ); ?>" />
						</div>
						<div class="kramar-settings-field">
							<label for="kramar-admin-email"><?php esc_html_e( 'Admin Recipients', 'kramar' ); ?></label>
							<input type="text" id="kramar-admin-email" name="admin_recipients" value="<?php echo esc_attr( $global['admin_recipients'] ?? '' ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>" />
							<p class="description"><?php esc_html_e( 'Where Kramar sends notifications meant for the shop — withdrawal requests, and any custom email addressed to the admin. WooCommerce\'s own emails keep the recipients set in WooCommerce.', 'kramar' ); ?></p>
						</div>
						<div class="kramar-settings-field">
							<label for="kramar-bcc"><?php esc_html_e( 'Global BCC', 'kramar' ); ?></label>
							<input type="text" id="kramar-bcc" name="global_bcc" value="<?php echo esc_attr( $global['global_bcc'] ?? '' ); ?>" placeholder="<?php esc_html_e( 'E.g., bookkeeper@company.nl', 'kramar' ); ?>" />
						</div>
					</form>
				</div>

				<div class="kramar-settings-card">
					<h2><?php esc_html_e( 'Business Details', 'kramar' ); ?></h2>
					<p class="kramar-settings-card__desc"><?php esc_html_e( 'Used in email footers and PDF invoices. Legally required (Handelsregisterwet Art. 29, EU VAT Directive Art. 226).', 'kramar' ); ?></p>
					<form class="kramar-em-business-form kramar-settings-form" data-save-action="kramar_email_save_business">
						<div class="kramar-settings-field">
							<label for="kramar-bd-logo_url"><?php esc_html_e( 'Brand Logo', 'kramar' ); ?></label>
							<p class="description" style="margin:0 0 6px;"><?php esc_html_e( 'Shown on PDF invoices and email headers. PNG, JPG or SVG.', 'kramar' ); ?></p>
							<div class="kramar-bd-logo" style="display:flex;align-items:center;gap:12px;">
								<img src="<?php echo esc_url( $biz['logo_url'] ?? '' ); ?>" alt="" class="kramar-bd-logo__preview" style="max-height:48px;max-width:160px;<?php echo empty( $biz['logo_url'] ) ? 'display:none;' : ''; ?>border:1px solid #e0e0e0;border-radius:4px;padding:4px;background:#fff;" />
								<input type="hidden" id="kramar-bd-logo_url" name="logo_url" value="<?php echo esc_url( $biz['logo_url'] ?? '' ); ?>" />
								<button type="button" class="button kramar-bd-logo__upload"><?php esc_html_e( 'Choose Logo', 'kramar' ); ?></button>
								<button type="button" class="button-link kramar-bd-logo__remove" style="color:#b32d2e;<?php echo empty( $biz['logo_url'] ) ? 'display:none;' : ''; ?>"><?php esc_html_e( 'Remove', 'kramar' ); ?></button>
							</div>
						</div>
						<?php foreach ( $biz_fields as $key => $field ) : ?>
							<div class="kramar-settings-field">
								<label for="kramar-bd-<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $field[0] ); ?></label>
								<?php if ( 'textarea' === $field[1] ) : ?>
									<textarea id="kramar-bd-<?php echo esc_attr( $key ); ?>" name="<?php echo esc_attr( $key ); ?>" rows="2"><?php echo esc_textarea( $biz[ $key ] ?? '' ); ?></textarea>
								<?php else : ?>
									<input type="<?php echo esc_attr( $field[1] ); ?>" id="kramar-bd-<?php echo esc_attr( $key ); ?>" name="<?php echo esc_attr( $key ); ?>" value="<?php echo esc_attr( $biz[ $key ] ?? '' ); ?>" />
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
					</form>
				</div>
			</div>
		</div>

		<?php
	}

	public function ajax_dismiss_setup(): void {
		check_ajax_referer( 'kramar_dismiss_setup' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}
		update_option( 'kramar_setup_dismissed', true );
		wp_send_json_success();
	}

	/**
	 * Render a single module card with toggle switch.
	 *
	 * @since 1.0.0
	 *
	 * @param Module $module The module to render.
	 */
	private function render_module_card( Module $module ): void {
		$field_name  = sprintf( '%s[%s][%s][enabled]', self::OPTION_NAME, $module->get_category(), $module->get_slug() );
		$field_id    = sprintf( 'kramar-%s-%s', $module->get_category(), $module->get_slug() );
		$is_enabled  = $module->is_enabled();
		$available   = $module->is_available();
		ob_start();
		if ( $available ) {
			$module->render_extra_settings( self::OPTION_NAME );
		}
		$extra_html = ob_get_clean();
		$has_extra  = '' !== trim( $extra_html );

		?>
		<div class="kramar-module<?php echo $available ? '' : ' kramar-module--unavailable'; ?><?php echo $is_enabled ? ' kramar-module--on' : ''; ?>">
			<div class="kramar-module__row">
				<div class="kramar-module__toggle">
					<label class="kramar-toggle" for="<?php echo esc_attr( $field_id ); ?>">
						<input type="checkbox" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $field_name ); ?>" value="1" <?php checked( $is_enabled ); ?> <?php disabled( ! $available ); ?> />
						<span class="kramar-toggle__slider"></span>
					</label>
					<?php if ( ! $available && $is_enabled ) : ?>
						<input type="hidden" name="<?php echo esc_attr( $field_name ); ?>" value="1" />
					<?php endif; ?>
				</div>
				<div class="kramar-module__info">
					<h3 class="kramar-module__name"><?php echo esc_html( $module->get_name() ); ?><?php if ( ! $available ) : ?><span class="kramar-badge"><?php esc_html_e( 'Not installed', 'kramar' ); ?></span><?php endif; ?></h3>
					<p class="kramar-module__description"><?php echo esc_html( $module->get_description() ); ?></p>
				</div>
			</div>
			<?php if ( $has_extra ) : ?>
				<div class="kramar-module__settings">
					<?php echo $extra_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}
}
