<?php
/**
 * Admin pages for MEM Connector + Live Preview.
 *
 * Single menu entry under WooCommerce with tabbed interface:
 * - Connection tab: Client ID / Client Secret, connect/disconnect
 * - Live Preview tab: Button appearance, shop URL settings
 *
 * @package Memwc_Connector
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

class Memwc_Admin {

	public function __construct() {
		add_action( 'admin_menu', [ $this, 'add_menu_page' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
		add_action( 'admin_init', [ $this, 'register_settings' ] );
		add_action( 'admin_init', [ $this, 'repair_shop_url' ] );

		// Connector AJAX — disconnect.
		add_action( 'wp_ajax_memwc_disconnect_store', [ $this, 'ajax_disconnect_store' ] );

		// Fulfillment meta box on order edit screens.
		add_action( 'add_meta_boxes', [ $this, 'register_order_meta_boxes' ] );

		// Plugin action links
		add_filter( 'plugin_action_links_' . MEMWC_CONNECTOR_BASENAME, [ $this, 'plugin_action_links' ] );
	}

	// =========================================================================
	// Menu & Assets
	// =========================================================================

	public function add_menu_page() {
		add_submenu_page(
			'woocommerce',
			__( 'My Easy Monogram', 'my-easy-monogram' ),
			__( 'My Easy Monogram', 'my-easy-monogram' ),
			'manage_woocommerce',
			'my-easy-monogram',
			[ $this, 'render_page' ]
		);
	}

	public function enqueue_assets( $hook ) {
		$is_mem_page   = ( 'woocommerce_page_my-easy-monogram' === $hook );
		$is_order_page = ( 'woocommerce_page_wc-orders' === $hook )
			|| ( 'post.php' === $hook && 'shop_order' === get_post_type() );

		if ( ! $is_mem_page && ! $is_order_page ) {
			return;
		}

		wp_enqueue_style(
			'mem-connector-admin',
			MEMWC_CONNECTOR_URL . 'assets/css/mem-admin.css',
			[ 'dashicons' ],
			MEMWC_CONNECTOR_VERSION
		);

		if ( ! $is_mem_page ) {
			return;
		}

		wp_enqueue_script(
			'mem-connector-admin',
			MEMWC_CONNECTOR_URL . 'assets/js/mem-admin.js',
			[ 'jquery' ],
			MEMWC_CONNECTOR_VERSION,
			true
		);

		wp_localize_script( 'mem-connector-admin', 'memwcConnector', [
			'ajaxUrl'         => admin_url( 'admin-ajax.php' ),
			'disconnectNonce' => wp_create_nonce( 'memwc_disconnect_store' ),
			'isConnected'     => Memwc_Connector::is_connected(),
			'i18n'            => [
				'disconnecting'     => esc_html__( 'Disconnecting...', 'my-easy-monogram' ),
				'disconnectLabel'   => esc_html__( 'Disconnect Store', 'my-easy-monogram' ),
				'confirmDisconnect' => esc_html__( 'Are you sure you want to disconnect this store from My Easy Monogram? This will remove all webhooks and API credentials.', 'my-easy-monogram' ),
				'error'             => esc_html__( 'An unexpected error occurred. Please try again.', 'my-easy-monogram' ),
			],
		] );
	}

	public function register_settings() {
		register_setting( 'memwc_live_preview_settings', 'memwc_widget_settings', [
			'type'              => 'array',
			'sanitize_callback' => [ $this, 'sanitize_widget_settings' ],
			'default'           => [],
		] );
		register_setting( 'memwc_live_preview_settings', 'memwc_shop_url', [
			'sanitize_callback' => function( $value ) {
				// The field is disabled so it won't submit with the form.
				// Preserve whatever is stored; fall back to home_url() if stored is also empty.
				if ( empty( $value ) ) {
					$stored = get_option( 'memwc_shop_url', '' );
					return ! empty( $stored ) ? esc_url_raw( $stored ) : esc_url_raw( home_url() );
				}
				return esc_url_raw( $value );
			},
		] );
	}

	/**
	 * Sanitize the widget settings array on save.
	 *
	 * Each field is validated according to its own type — fixed-choice
	 * fields against a whitelist, colors with sanitize_hex_color(), the
	 * font size as a bounded integer, and free text with sanitize_text_field().
	 * `sanitize_text_field` cannot be used as a top-level callback here because
	 * the option value is an array (it would coerce to an empty string and wipe
	 * every setting back to the defaults).
	 *
	 * Checkbox booleans (enable_live_preview, navigate_to_cart) are normalized
	 * explicitly on every save: an unchecked box is not submitted at all, so we
	 * must store 'false' for it — otherwise the value would fall back to its
	 * default and the toggle could never be turned off.
	 *
	 * @param mixed $value Raw value posted from the settings form.
	 * @return array Sanitized associative array of widget settings.
	 */
	public function sanitize_widget_settings( $value ) {
		if ( ! is_array( $value ) ) {
			$value = [];
		}

		$preview  = Memwc_Live_Preview_WooCommerce::get_instance();
		$defaults = $preview->get_default_settings();

		// Start from the current effective settings so keys not present in the
		// form (e.g. color_variant_as_image, font_style) are preserved on save.
		$clean = wp_parse_args( get_option( 'memwc_widget_settings', [] ), $defaults );

		// --- Checkbox booleans: present only when checked. ---
		$clean['enable_live_preview'] = ( isset( $value['enable_live_preview'] ) && 'true' === $value['enable_live_preview'] ) ? 'true' : 'false';
		$clean['navigate_to_cart']    = ( isset( $value['navigate_to_cart'] ) && 'true' === $value['navigate_to_cart'] ) ? 'true' : 'false';

		// --- Fixed-choice selects: whitelist, fall back to default. ---
		if ( isset( $value['widget_type'] ) ) {
			$clean['widget_type'] = in_array( $value['widget_type'], [ 'modal', 'embed' ], true )
				? $value['widget_type'] : $defaults['widget_type'];
		}
		if ( isset( $value['button_type'] ) ) {
			$clean['button_type'] = in_array( $value['button_type'], [ 'outline', 'fill', 'text' ], true )
				? $value['button_type'] : $defaults['button_type'];
		}
		if ( isset( $value['font_style'] ) ) {
			$clean['font_style'] = in_array( $value['font_style'], [ 'normal', 'bold', 'italic' ], true )
				? $value['font_style'] : $defaults['font_style'];
		}

		// --- Free text. ---
		if ( isset( $value['button_text'] ) ) {
			$clean['button_text'] = sanitize_text_field( $value['button_text'] );
		}

		// --- Number: validate as int, clamp to the UI range (10–40), then store
		// back as a string to preserve the data contract with the preview script. ---
		if ( isset( $value['button_text_size'] ) ) {
			$size = absint( $value['button_text_size'] );
			$size = max( 10, min( 40, $size ) );
			$clean['button_text_size'] = (string) $size;
		}

		// --- Hex colors: invalid input falls back to the default. ---
		foreach ( [ 'button_fill_color', 'button_outline_color', 'button_text_color' ] as $color_key ) {
			if ( isset( $value[ $color_key ] ) ) {
				$clean[ $color_key ] = $this->sanitize_hex_color_value( $value[ $color_key ], $defaults[ $color_key ] );
			}
		}

		return $clean;
	}

	/**
	 * Validate a hex color, returning a fallback when the input is invalid.
	 *
	 * Uses core's sanitize_hex_color() when available (admin/options context),
	 * with a regex fallback so the callback is safe in any context.
	 *
	 * @param string $color    Raw color value (#rrggbb expected).
	 * @param string $fallback Value to return when $color is not a valid hex.
	 * @return string Sanitized hex color or the fallback.
	 */
	private function sanitize_hex_color_value( $color, $fallback ) {
		if ( function_exists( 'sanitize_hex_color' ) ) {
			$sanitized = sanitize_hex_color( $color );
			return ( null === $sanitized || '' === $sanitized ) ? $fallback : $sanitized;
		}
		return preg_match( '/^#(?:[a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/', (string) $color ) ? $color : $fallback;
	}

	public function repair_shop_url() {
		$current = get_option( 'memwc_shop_url', '' );
		if ( empty( $current ) ) {
			update_option( 'memwc_shop_url', esc_url_raw( home_url() ), false );
		}
	}

	// =========================================================================
	// Page Router (tabs)
	// =========================================================================

	public function render_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'my-easy-monogram' ) );
		}

		// Auto-verify connection with MEM backend on every page load
		// so the UI always reflects the real-time connection state.
		$is_connected = $this->sync_connection_status();
		$current_tab  = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'connection'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page_url     = admin_url( 'admin.php?page=my-easy-monogram' );
		$logo_url     = MEMWC_CONNECTOR_URL . 'assets/images/mem-logo.png';
		?>
		<div class="wrap mem-wrap">
			<h1 class="screen-reader-text"><?php esc_html_e( 'My Easy Monogram', 'my-easy-monogram' ); ?></h1>

			<!-- Hero Header -->
			<div class="mem-hero">
				<div class="mem-hero-inner">
					<img src="<?php echo esc_url( $logo_url ); ?>" alt="My Easy Monogram" class="mem-hero-logo" width="52" height="52" />
					<div class="mem-hero-text">
						<span class="mem-hero-title"><?php esc_html_e( 'My Easy Monogram', 'my-easy-monogram' ); ?></span>
						<p><?php esc_html_e( 'Order management, production, shipping, and product personalization live preview.', 'my-easy-monogram' ); ?></p>
					</div>
				</div>
			</div>

			<hr class="wp-header-end" />

			<!-- Tabs -->
			<nav class="nav-tab-wrapper" style="margin-top:16px;">
				<a href="<?php echo esc_url( $page_url . '&tab=connection' ); ?>"
				   class="nav-tab <?php echo $current_tab === 'connection' ? 'nav-tab-active' : ''; ?>">
					<span class="dashicons dashicons-admin-links" style="margin-right:4px;"></span>
					<?php esc_html_e( 'Connection', 'my-easy-monogram' ); ?>
				</a>
				<?php if ( $is_connected ) : ?>
					<a href="<?php echo esc_url( $page_url . '&tab=live-preview' ); ?>"
					   class="nav-tab <?php echo $current_tab === 'live-preview' ? 'nav-tab-active' : ''; ?>">
						<span class="dashicons dashicons-visibility" style="margin-right:4px;"></span>
						<?php esc_html_e( 'Live Preview', 'my-easy-monogram' ); ?>
					</a>
				<?php else : ?>
					<a href="<?php echo esc_url( $page_url . '&tab=live-preview' ); ?>"
					   class="nav-tab mem-tab-disabled <?php echo $current_tab === 'live-preview' ? 'nav-tab-active' : ''; ?>"
					   style="opacity:0.5;cursor:not-allowed;">
						<span class="dashicons dashicons-lock" style="margin-right:4px;"></span>
						<?php esc_html_e( 'Live Preview', 'my-easy-monogram' ); ?>
					</a>
				<?php endif; ?>
			</nav>

			<!-- Notice -->
			<div id="mem-connector-notice" class="mem-notice" style="display:none;">
				<span class="mem-notice-icon"></span>
				<span class="mem-notice-text"></span>
			</div>

			<!-- Tab Content -->
			<div class="mem-content">
				<?php
				if ( $current_tab === 'live-preview' && $is_connected ) {
					$this->render_live_preview_tab();
				} elseif ( $current_tab === 'live-preview' && ! $is_connected ) {
					$this->render_live_preview_disconnected( $page_url );
				} else {
					$this->render_connection_tab();
				}
				?>
			</div>

			<!-- Image Lightbox (used by connection step images) -->
			<div id="mem-lightbox" class="mem-lightbox" style="display:none;">
				<div class="mem-lightbox-backdrop"></div>
				<div class="mem-lightbox-content">
					<button type="button" class="mem-lightbox-close" aria-label="<?php esc_attr_e( 'Close preview', 'my-easy-monogram' ); ?>">
						<span class="dashicons dashicons-no-alt"></span>
					</button>
					<img id="mem-lightbox-img" src="" alt="" />
				</div>
			</div>

		</div>
		<?php
	}

	/**
	 * Call the MEM API to check current connection state and sync locally.
	 *
	 * Returns the authoritative connected/disconnected status so the page
	 * renders correctly without a manual "Verify" click.
	 *
	 * @return bool True if connected, false otherwise.
	 */
	private function sync_connection_status() {
		$was_connected = Memwc_Connector::is_connected();
		$result        = Memwc_Api::verify_connection();

		if ( false === $result ) {
			update_option( 'memwc_connector_connected', false, true );
			return false;
		}

		// On first connection (or reconnection), send a full store details snapshot.
		if ( ! $was_connected && class_exists( 'Memwc_Store_Sync' ) ) {
			Memwc_Store_Sync::send_full_snapshot();
		}

		return true;
	}

	// =========================================================================
	// Tab: Connection
	// =========================================================================

	private function render_connection_tab() {
		$is_connected = Memwc_Connector::is_connected();
		if ( $is_connected ) {
			$this->render_connected_view();
		} else {
			$this->render_connection_form();
		}
	}

	private function render_connection_form() {
		$step_images = [
			'step-1' => MEMWC_CONNECTOR_URL . 'assets/images/step-1.png',
			'step-2' => MEMWC_CONNECTOR_URL . 'assets/images/step-2.png',
			'step-3' => MEMWC_CONNECTOR_URL . 'assets/images/step-3.png',
			'step-4' => MEMWC_CONNECTOR_URL . 'assets/images/step-4.png',
		];
		?>
		<div class="mem-connect-grid">

			<!-- Left: Steps -->
			<div class="mem-section mem-section-steps">
				<div class="mem-steps-card">
					<div class="mem-steps-card-header">
						<span class="dashicons dashicons-clipboard"></span>
						<div>
							<h2><?php esc_html_e( 'How to Connect Your Store', 'my-easy-monogram' ); ?></h2>
							<p><?php esc_html_e( 'Follow these steps to connect your WooCommerce store to My Easy Monogram.', 'my-easy-monogram' ); ?></p>
						</div>
					</div>
					<div class="mem-steps-list">
						<?php
					$steps = [
						[ 'title' => 'Sign Up or Log In',        'icon' => 'admin-users',  'img' => 'step-1', 'desc' => 'Click the button on the right to open My Easy Monogram. Create an account or log in.' ],
						[ 'title' => 'Connect WooCommerce',      'icon' => 'admin-links',  'img' => 'step-2', 'desc' => 'After signing up or logging in, you will be automatically redirected to the Manage Stores page. Click "Connect Store", choose WooCommerce, and enter your store URL.' ],
						[ 'title' => 'Approve & Come Back Here', 'icon' => 'yes-alt',      'img' => 'step-3', 'desc' => 'You will be redirected to your store to approve the connection. After approving, come back to this page. The connection will be verified automatically.' ],
						[ 'title' => 'Successfully Connected',   'icon' => 'yes-alt',      'img' => 'step-4', 'desc' => 'Once the connection is verified, a successfully connected screen will be displayed in My Easy Monogram. Your store is now linked and ready to go.' ],
					];
						foreach ( $steps as $i => $step ) :
						?>
						<div class="mem-step-item">
							<div class="mem-step-item-head">
								<span class="mem-step-num"><?php echo esc_html( $i + 1 ); ?></span>
								<div class="mem-step-item-title">
									<h3><?php echo esc_html( $step['title'] ); ?></h3>
									<span class="dashicons dashicons-<?php echo esc_attr( $step['icon'] ); ?> mem-step-icon"></span>
								</div>
							</div>
							<p><?php echo esc_html( $step['desc'] ); ?></p>
							<div class="mem-step-img-wrap mem-step-img-clickable">
								<img src="<?php echo esc_url( $step_images[ $step['img'] ] ); ?>" alt="<?php echo esc_attr( $step['title'] ); ?>" onerror="this.parentNode.classList.add('is-missing');" />
								<span class="mem-step-img-placeholder">
									<span class="dashicons dashicons-format-image"></span>
									<span><?php echo esc_html( $step['img'] . '.png' ); ?></span>
								</span>
							</div>
						</div>
						<?php endforeach; ?>
					</div>
				</div>
			</div>

			<!-- Right: Connect & Verify -->
			<div class="mem-section mem-section-form">
				<div class="mem-credentials-card mem-credentials-sticky">
					<div class="mem-credentials-header">
						<span class="dashicons dashicons-admin-network"></span>
						<div>
							<h2><?php esc_html_e( 'Connect Your Store', 'my-easy-monogram' ); ?></h2>
							<p><?php esc_html_e( 'Log in to My Easy Monogram and connect your store from the dashboard. Connection is verified automatically when you open this page.', 'my-easy-monogram' ); ?></p>
						</div>
					</div>
					<div class="mem-cred-form">
						<div class="mem-connect-actions-stack">
							<a href="<?php echo esc_url( Memwc_Api::get_api_url( '/login' ) ); ?>" target="_blank" rel="noopener noreferrer" class="mem-btn mem-btn-primary" id="mem-login-btn">
								<span class="dashicons dashicons-external" style="margin-right:6px;"></span>
								<span class="mem-btn-label"><?php esc_html_e( 'Connect to My Easy Monogram', 'my-easy-monogram' ); ?></span>
							</a>
							<p class="mem-form-hint" style="margin:16px 0;">
								<span class="dashicons dashicons-info"></span>
								<?php esc_html_e( 'After connecting your store in the My Easy Monogram dashboard, refresh this page to see the updated status.', 'my-easy-monogram' ); ?>
							</p>
						</div>
					</div>
				</div>
			</div>

		</div>
		<?php
	}

	private function get_active_mem_webhook_count() {
		if ( ! class_exists( 'WC_Data_Store' ) ) {
			return 0;
		}
		try {
			$data_store  = WC_Data_Store::load( 'webhook' );
			// MEM app names all its webhooks with a "MEM" prefix (e.g. "MEM - product.deleted").
			$webhook_ids = $data_store->search_webhooks( [
				'status' => 'active',
				'search' => 'MEM',
				'limit'  => -1,
			] );
			$count = is_array( $webhook_ids ) ? count( $webhook_ids ) : 0;

			// Also include any locally-stored IDs not covered by the name search.
			$stored_ids = get_option( 'memwc_connector_webhook_ids', [] );
			if ( is_array( $stored_ids ) ) {
				$extra = array_diff( array_map( 'intval', $stored_ids ), array_map( 'intval', $webhook_ids ?: [] ) );
				$count += count( $extra );
			}

			return $count;
		} catch ( Exception $e ) {
			$stored = get_option( 'memwc_connector_webhook_ids', [] );
			return is_array( $stored ) ? count( $stored ) : 0;
		}
	}

	private function render_connected_view() {
		$connected_at  = get_option( 'memwc_connector_connected_at', '' );
		$webhook_count = $this->get_active_mem_webhook_count();
		?>
		<div class="mem-connected-card">
			<div class="mem-connected-header">
				<div class="mem-connected-badge">
					<span class="mem-pulse"></span>
					<span><?php esc_html_e( 'Connected', 'my-easy-monogram' ); ?></span>
				</div>
				<h2><?php esc_html_e( 'Your Store is Connected to My Easy Monogram', 'my-easy-monogram' ); ?></h2>
				<p><?php esc_html_e( 'Orders are being forwarded automatically. Everything is working.', 'my-easy-monogram' ); ?></p>
			</div>
			<div class="mem-info-grid">
				<div class="mem-info-item">
					<span class="dashicons dashicons-admin-site-alt3 mem-info-icon"></span>
					<div class="mem-info-detail">
						<span class="mem-info-label"><?php esc_html_e( 'Store URL', 'my-easy-monogram' ); ?></span>
						<span class="mem-info-value"><code><?php echo esc_html( home_url() ); ?></code></span>
					</div>
				</div>
				<div class="mem-info-item">
					<span class="dashicons dashicons-calendar-alt mem-info-icon"></span>
					<div class="mem-info-detail">
						<span class="mem-info-label"><?php esc_html_e( 'Connected Since', 'my-easy-monogram' ); ?></span>
						<span class="mem-info-value">
							<?php echo $connected_at ? esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $connected_at ) ) ) : '—'; ?>
						</span>
					</div>
				</div>
				<div class="mem-info-item">
					<span class="dashicons dashicons-randomize mem-info-icon"></span>
					<div class="mem-info-detail">
						<span class="mem-info-label"><?php esc_html_e( 'Active Webhooks', 'my-easy-monogram' ); ?></span>
						<span class="mem-info-value">
							<?php echo esc_html( $webhook_count ); ?>
						</span>
					</div>
				</div>
				<div class="mem-info-item">
					<span class="dashicons dashicons-info mem-info-icon"></span>
					<div class="mem-info-detail">
						<span class="mem-info-label"><?php esc_html_e( 'Plugin Version', 'my-easy-monogram' ); ?></span>
						<span class="mem-info-value"><?php echo esc_html( MEMWC_CONNECTOR_VERSION ); ?></span>
					</div>
				</div>
			</div>
			<div class="mem-connected-footer">
				<button type="button" class="mem-btn mem-btn-danger-outline" id="mem-disconnect-btn">
					<span class="dashicons dashicons-dismiss"></span>
					<span class="mem-btn-label"><?php esc_html_e( 'Disconnect Store', 'my-easy-monogram' ); ?></span>
				</button>
			</div>
		</div>
		<?php
	}

	// =========================================================================
	// Tab: Live Preview (disconnected state)
	// =========================================================================

	private function render_live_preview_disconnected( $page_url ) {
		?>
		<div class="mem-connected-card" style="margin-top:16px;text-align:center;padding:60px 28px;">
			<div style="margin-bottom:20px;">
				<span class="dashicons dashicons-warning" style="font-size:48px;width:48px;height:48px;color:#d63638;"></span>
			</div>
			<h2 style="margin:0 0 12px;"><?php esc_html_e( 'Store Not Connected', 'my-easy-monogram' ); ?></h2>
			<p style="color:#646970;font-size:14px;max-width:460px;margin:0 auto 24px;">
				<?php esc_html_e( 'You need to connect your store to My Easy Monogram before you can configure the Live Preview settings. Please go to the Connection tab and enter your credentials.', 'my-easy-monogram' ); ?>
			</p>
			<a href="<?php echo esc_url( $page_url . '&tab=connection' ); ?>" class="mem-btn mem-btn-primary" style="display:inline-flex;text-decoration:none;">
				<span class="dashicons dashicons-admin-links" style="margin-right:6px;"></span>
				<span class="mem-btn-label"><?php esc_html_e( 'Go to Connection', 'my-easy-monogram' ); ?></span>
			</a>
		</div>
		<?php
	}

	// =========================================================================
	// Tab: Live Preview Settings
	// =========================================================================

	private function render_live_preview_tab() {
		$preview  = Memwc_Live_Preview_WooCommerce::get_instance();
		$settings = $preview->get_widget_settings();
		$shop_url = get_option( 'memwc_shop_url', esc_url_raw( get_site_url() ) );
		?>
		<div class="mem-connected-card" style="margin-top:16px;">
			<div class="mem-connected-header">
				<h2><?php esc_html_e( 'Live Preview Settings', 'my-easy-monogram' ); ?></h2>
				<p><?php esc_html_e( 'Configure the Personalize button appearance and behavior on your product pages.', 'my-easy-monogram' ); ?></p>
			</div>

			<form method="post" action="options.php" class="mem-lp-form">
				<?php settings_fields( 'memwc_live_preview_settings' ); ?>

				<!-- Section: General -->
				<div class="mem-settings-section">
					<div class="mem-settings-section-title">
						<span class="dashicons dashicons-admin-settings"></span>
						<?php esc_html_e( 'General', 'my-easy-monogram' ); ?>
					</div>
					<div class="mem-settings-fields">

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-enable-preview"><?php esc_html_e( 'Enable Live Preview', 'my-easy-monogram' ); ?></label>
								<p><?php esc_html_e( 'When disabled, no live preview assets or UI will be loaded on the frontend.', 'my-easy-monogram' ); ?></p>
							</div>
							<div class="mem-settings-row-control">
								<label class="mem-toggle">
									<input type="checkbox" id="mem-enable-preview" name="memwc_widget_settings[enable_live_preview]" value="true" <?php checked( $settings['enable_live_preview'] ?? 'false', 'true' ); ?> />
									<span class="mem-toggle-track"><span class="mem-toggle-thumb"></span></span>
								</label>
							</div>
						</div>

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-widget-type"><?php esc_html_e( 'Widget Type', 'my-easy-monogram' ); ?></label>
								<p><?php esc_html_e( 'Modal: opens in overlay. Embed: replaces product gallery inline.', 'my-easy-monogram' ); ?></p>
							</div>
							<div class="mem-settings-row-control">
								<select id="mem-widget-type" name="memwc_widget_settings[widget_type]" class="mem-select">
									<option value="modal" <?php selected( $settings['widget_type'] ?? 'modal', 'modal' ); ?>><?php esc_html_e( 'Modal', 'my-easy-monogram' ); ?></option>
									<option value="embed" <?php selected( $settings['widget_type'] ?? 'modal', 'embed' ); ?>><?php esc_html_e( 'Embed', 'my-easy-monogram' ); ?></option>
								</select>
							</div>
						</div>

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-shop-url"><?php esc_html_e( 'Shop URL', 'my-easy-monogram' ); ?></label>
								<p><?php esc_html_e( 'Automatically set from your store domain. Not editable.', 'my-easy-monogram' ); ?></p>
							</div>
							<div class="mem-settings-row-control">
								<input type="text" id="mem-shop-url" name="memwc_shop_url" value="<?php echo esc_attr( $shop_url ); ?>" class="mem-lp-input mem-lp-input-readonly" disabled />
							</div>
						</div>

					</div>
				</div>

				<!-- Section: Button Appearance -->
				<div class="mem-settings-section">
					<div class="mem-settings-section-title">
						<span class="dashicons dashicons-button"></span>
						<?php esc_html_e( 'Button Appearance', 'my-easy-monogram' ); ?>
					</div>
					<div class="mem-settings-fields">

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-button-text"><?php esc_html_e( 'Button Text', 'my-easy-monogram' ); ?></label>
							</div>
							<div class="mem-settings-row-control">
								<input type="text" id="mem-button-text" name="memwc_widget_settings[button_text]" value="<?php echo esc_attr( $settings['button_text'] ); ?>" class="mem-lp-input" />
							</div>
						</div>

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-button-type"><?php esc_html_e( 'Button Style', 'my-easy-monogram' ); ?></label>
							</div>
							<div class="mem-settings-row-control">
								<select id="mem-button-type" name="memwc_widget_settings[button_type]" class="mem-select">
									<option value="outline" <?php selected( $settings['button_type'], 'outline' ); ?>><?php esc_html_e( 'Outline', 'my-easy-monogram' ); ?></option>
									<option value="fill"    <?php selected( $settings['button_type'], 'fill' ); ?>><?php esc_html_e( 'Fill', 'my-easy-monogram' ); ?></option>
									<option value="text"    <?php selected( $settings['button_type'], 'text' ); ?>><?php esc_html_e( 'Text only', 'my-easy-monogram' ); ?></option>
								</select>
							</div>
						</div>

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-button-size"><?php esc_html_e( 'Font Size', 'my-easy-monogram' ); ?></label>
							</div>
							<div class="mem-settings-row-control">
								<div class="mem-settings-row-inline">
									<input type="number" id="mem-button-size" name="memwc_widget_settings[button_text_size]" value="<?php echo esc_attr( $settings['button_text_size'] ); ?>" min="10" max="40" class="mem-lp-input mem-lp-input-narrow" />
									<span class="mem-unit">px</span>
								</div>
							</div>
						</div>

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label><?php esc_html_e( 'Colors', 'my-easy-monogram' ); ?></label>
								<p><?php esc_html_e( 'Fill, outline border, and text colors for the button.', 'my-easy-monogram' ); ?></p>
							</div>
							<div class="mem-settings-row-control">
								<div class="mem-color-controls">
									<div class="mem-color-field">
										<label for="mem-btn-fill"><?php esc_html_e( 'Fill', 'my-easy-monogram' ); ?></label>
										<input type="color" id="mem-btn-fill" name="memwc_widget_settings[button_fill_color]" value="<?php echo esc_attr( $settings['button_fill_color'] ); ?>" />
									</div>
									<div class="mem-color-field">
										<label for="mem-btn-outline"><?php esc_html_e( 'Outline', 'my-easy-monogram' ); ?></label>
										<input type="color" id="mem-btn-outline" name="memwc_widget_settings[button_outline_color]" value="<?php echo esc_attr( $settings['button_outline_color'] ); ?>" />
									</div>
									<div class="mem-color-field">
										<label for="mem-btn-text-color"><?php esc_html_e( 'Text', 'my-easy-monogram' ); ?></label>
										<input type="color" id="mem-btn-text-color" name="memwc_widget_settings[button_text_color]" value="<?php echo esc_attr( $settings['button_text_color'] ); ?>" />
									</div>
								</div>
							</div>
						</div>

					</div>
				</div>

				<!-- Section: Behavior -->
				<div class="mem-settings-section">
					<div class="mem-settings-section-title">
						<span class="dashicons dashicons-cart"></span>
						<?php esc_html_e( 'Behavior', 'my-easy-monogram' ); ?>
					</div>
					<div class="mem-settings-fields">

						<div class="mem-settings-row">
							<div class="mem-settings-row-label">
								<label for="mem-navigate-cart"><?php esc_html_e( 'Navigate to Cart after Add', 'my-easy-monogram' ); ?></label>
								<p><?php esc_html_e( 'Automatically redirect the customer to the cart after adding an item.', 'my-easy-monogram' ); ?></p>
							</div>
							<div class="mem-settings-row-control">
								<label class="mem-toggle">
									<input type="checkbox" id="mem-navigate-cart" name="memwc_widget_settings[navigate_to_cart]" value="true" <?php checked( $settings['navigate_to_cart'], 'true' ); ?> />
									<span class="mem-toggle-track"><span class="mem-toggle-thumb"></span></span>
								</label>
							</div>
						</div>

					</div>
				</div>

				<!-- Footer -->
				<div class="mem-lp-form-footer">
					<?php submit_button( __( 'Save Settings', 'my-easy-monogram' ), 'primary', 'submit', false ); ?>
				</div>

			</form>
		</div>
		<?php
	}

	// =========================================================================
	// Order Meta Box: Fulfillment Details
	// =========================================================================

	/**
	 * Register the MEM fulfillment meta box on order edit screens.
	 *
	 * Registers for both the legacy `shop_order` post type and the
	 * HPOS `woocommerce_page_wc-orders` screen.
	 */
	public function register_order_meta_boxes() {
		$screens = [ 'shop_order', 'woocommerce_page_wc-orders' ];

		foreach ( $screens as $screen ) {
			add_meta_box(
				'mem-fulfillment-details',
				__( 'My Easy Monogram — Fulfillment', 'my-easy-monogram' ),
				[ $this, 'render_fulfillment_meta_box' ],
				$screen,
				'side',
				'default'
			);
		}
	}

	/**
	 * Render the fulfillment meta box content.
	 *
	 * Displays tracking number, carrier, and a clickable tracking URL
	 * when fulfillment data has been set by the MEM backend.
	 *
	 * @param WP_Post|WC_Order $post_or_order Post object (legacy) or Order object (HPOS).
	 */
	public function render_fulfillment_meta_box( $post_or_order ) {
		$order = ( $post_or_order instanceof WP_Post )
			? wc_get_order( $post_or_order->ID )
			: $post_or_order;

		if ( ! $order ) {
			return;
		}

		$tracking_number = $order->get_meta( '_mem_tracking_number' );
		$carrier         = $order->get_meta( '_mem_carrier' );
		$tracking_url    = $order->get_meta( '_mem_tracking_url' );

		if ( empty( $tracking_number ) && empty( $carrier ) && empty( $tracking_url ) ) {
			?>
			<div class="mem-fulfillment-empty">
				<span class="dashicons dashicons-clock"></span>
				<p><?php esc_html_e( 'No fulfillment data received from My Easy Monogram yet.', 'my-easy-monogram' ); ?></p>
			</div>
			<?php
			return;
		}
		?>
		<div class="mem-fulfillment-box">
			<?php if ( ! empty( $carrier ) ) : ?>
				<div class="mem-fulfillment-field">
					<span class="mem-fulfillment-label"><?php esc_html_e( 'Carrier', 'my-easy-monogram' ); ?></span>
					<span class="mem-fulfillment-value"><?php echo esc_html( $carrier ); ?></span>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $tracking_number ) ) : ?>
				<div class="mem-fulfillment-field">
					<span class="mem-fulfillment-label"><?php esc_html_e( 'Tracking Number', 'my-easy-monogram' ); ?></span>
					<code class="mem-fulfillment-value mem-fulfillment-code"><?php echo esc_html( $tracking_number ); ?></code>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $tracking_url ) ) : ?>
				<div class="mem-fulfillment-field">
					<a href="<?php echo esc_url( $tracking_url ); ?>" target="_blank" rel="noopener noreferrer" class="mem-fulfillment-track-link">
						<span class="dashicons dashicons-external"></span>
						<?php esc_html_e( 'Track Shipment', 'my-easy-monogram' ); ?>
					</a>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	// =========================================================================
	// AJAX: Disconnect
	// =========================================================================

	public function ajax_disconnect_store() {
		check_ajax_referer( 'memwc_disconnect_store', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( [ 'message' => __( 'You do not have permission to perform this action.', 'my-easy-monogram' ) ] );
		}

		if ( ! Memwc_Connector::is_connected() ) {
			wp_send_json_error( [ 'message' => __( 'This store is not currently connected to My Easy Monogram.', 'my-easy-monogram' ) ] );
		}

		$result = Memwc_Api::disconnect();

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success( [ 'message' => __( 'Store disconnected successfully.', 'my-easy-monogram' ) ] );
	}

	// =========================================================================
	// Plugin Action Links
	// =========================================================================

	public function plugin_action_links( $links ) {
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=my-easy-monogram' ) ),
			esc_html__( 'Settings', 'my-easy-monogram' )
		);
		array_unshift( $links, $settings_link );
		return $links;
	}
}
