<?php
/**
 * ERENQVP_Admin — menu, asset loading and the Quick Add screen markup.
 *
 * @package ErenLabs\QuickVariableProducts
 */

defined( 'ABSPATH' ) || exit;

class ERENQVP_Admin {

	const OPT_AUTO_SKU = 'erenqvp_auto_sku_default';
	const PREFS_META   = 'erenqvp_last_prefs';

	/**
	 * True once settings have been saved this request (rendered inline on the Settings screen).
	 *
	 * @var bool
	 */
	private static $settings_saved = false;

	/**
	 * Per-user sticky defaults (last-used tax/stock/brand choices), with sane fallbacks.
	 *
	 * @return array
	 */
	public static function get_prefs() {
		$defaults = array(
			'tax_status'        => 'taxable',
			'tax_class'         => '',
			'backorders'        => 'no',
			'shipping_class_id' => 0,
			'brand'             => '',
			'manage_stock'      => true,
			'auto_sku'          => (bool) get_option( self::OPT_AUTO_SKU, false ),
			'variation_images'  => false,
		);
		$saved = get_user_meta( get_current_user_id(), self::PREFS_META, true );
		if ( ! is_array( $saved ) ) {
			$saved = array();
		}
		return wp_parse_args( $saved, $defaults );
	}

	/**
	 * Remember the user's choices after a successful create, so the form pre-fills them next time.
	 *
	 * @param array $d Create payload.
	 * @return void
	 */
	public static function remember_prefs( array $d ) {
		$uid = get_current_user_id();
		if ( ! $uid ) {
			return;
		}
		// Whitelist enum-ish fields and bound free text: these values are echoed back into the
		// Add screen on every load, so only store what the product engine itself would accept.
		$tax_status = is_string( $d['tax_status'] ?? null ) ? $d['tax_status'] : '';
		$backorders = is_string( $d['backorders'] ?? null ) ? $d['backorders'] : '';
		$tax_class  = is_string( $d['tax_class'] ?? null ) ? sanitize_title( $d['tax_class'] ) : '';
		if ( ! in_array( $tax_class, array_merge( array( '' ), WC_Tax::get_tax_class_slugs() ), true ) ) {
			$tax_class = '';
		}
		update_user_meta(
			$uid,
			self::PREFS_META,
			array(
				'tax_status'        => in_array( $tax_status, array( 'taxable', 'shipping', 'none' ), true ) ? $tax_status : 'taxable',
				'tax_class'         => $tax_class,
				'backorders'        => in_array( $backorders, array( 'no', 'notify', 'yes' ), true ) ? $backorders : 'no',
				'shipping_class_id' => absint( $d['shipping_class_id'] ?? 0 ),
				'brand'             => is_string( $d['brand'] ?? null ) ? erenqvp_substr( sanitize_text_field( $d['brand'] ), 0, 200 ) : '',
				'manage_stock'      => ! empty( $d['manage_stock'] ),
				'auto_sku'          => ! empty( $d['auto_sku'] ),
				'variation_images'  => ! empty( $d['variation_images'] ),
			)
		);
	}

	/**
	 * Hook menu + assets.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'menu' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'assets' ) );
		add_action( 'admin_init', array( __CLASS__, 'maybe_save_settings' ) );
		add_filter( 'admin_body_class', array( __CLASS__, 'body_class' ) );
	}

	/**
	 * True on any Quick Variable Products admin screen (free Add/Settings/Upgrade or the Pro
	 * Bulk/Add-to-Existing screens) — matched by our page slug so it is locale-proof.
	 *
	 * @return bool
	 */
	private static function is_our_screen() {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}
		$screen = get_current_screen();
		if ( ! $screen ) {
			return false;
		}
		$id = (string) $screen->id;
		return false !== strpos( $id, 'erenqvp-add' )
			|| false !== strpos( $id, 'erenqvp-settings' )
			|| false !== strpos( $id, 'erenqvp-help' )
			|| false !== strpos( $id, 'erenqvp-upgrade' )
			|| false !== strpos( $id, 'erenqvpp-' );
	}

	/**
	 * Register the top-level menu and its sub-pages.
	 *
	 * @return void
	 */
	public static function menu() {
		add_menu_page(
			__( 'Quick Variable Products', 'quick-variable-products' ),
			__( 'Quick Products', 'quick-variable-products' ),
			ERENQVP_CAP,
			'erenqvp-add',
			array( __CLASS__, 'render_add' ),
			'dashicons-screenoptions',
			56
		);
		add_submenu_page(
			'erenqvp-add',
			__( 'Add Product', 'quick-variable-products' ),
			__( 'Add Product', 'quick-variable-products' ),
			ERENQVP_CAP,
			'erenqvp-add',
			array( __CLASS__, 'render_add' )
		);
		add_submenu_page(
			'erenqvp-add',
			__( 'Settings', 'quick-variable-products' ),
			__( 'Settings', 'quick-variable-products' ),
			ERENQVP_CAP,
			'erenqvp-settings',
			array( __CLASS__, 'render_settings' )
		);
		add_submenu_page(
			'erenqvp-add',
			__( 'Help & FAQ', 'quick-variable-products' ),
			__( 'Help & FAQ', 'quick-variable-products' ),
			ERENQVP_CAP,
			'erenqvp-help',
			array( __CLASS__, 'render_help' )
		);
	}

	/**
	 * Load CSS/JS + data only on our Add screen.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public static function assets( $hook ) {
		$is_add      = 'toplevel_page_erenqvp-add' === $hook;
		$is_settings = false !== strpos( (string) $hook, 'erenqvp-settings' );
		$is_help     = false !== strpos( (string) $hook, 'erenqvp-help' );
		if ( ! $is_add && ! $is_settings && ! $is_help ) {
			return;
		}
		// The Settings and Help screens share the stylesheet (same design language), nothing else.
		if ( ! $is_add ) {
			wp_enqueue_style( 'erenqvp-admin', ERENQVP_URL . 'assets/qvp-admin.css', array(), erenqvp_asset_ver( 'assets/qvp-admin.css' ) );
			return;
		}
		wp_enqueue_media();
		wp_enqueue_editor(); // TinyMCE assets for the on-demand rich description editor.
		wp_enqueue_style( 'erenqvp-admin', ERENQVP_URL . 'assets/qvp-admin.css', array(), erenqvp_asset_ver( 'assets/qvp-admin.css' ) );
		// Shared coach-mark tour engine (also used by the Pro screens). qvp-admin
		// depends on it so ErenqvpTour is defined before the Add-screen tour is wired.
		wp_enqueue_script( 'erenqvp-tour', ERENQVP_URL . 'assets/qvp-tour.js', array(), erenqvp_asset_ver( 'assets/qvp-tour.js' ), true );
		wp_enqueue_script( 'erenqvp-admin', ERENQVP_URL . 'assets/qvp-admin.js', array( 'erenqvp-tour' ), erenqvp_asset_ver( 'assets/qvp-admin.js' ), true );

		$tax_statuses = array(
			array( 'v' => 'taxable',  'label' => __( 'Taxable', 'quick-variable-products' ) ),
			array( 'v' => 'shipping', 'label' => __( 'Shipping only', 'quick-variable-products' ) ),
			array( 'v' => 'none',     'label' => __( 'None', 'quick-variable-products' ) ),
		);
		$tax_classes = array( array( 'slug' => '', 'label' => __( 'Standard', 'quick-variable-products' ) ) );
		$slugs       = WC_Tax::get_tax_class_slugs();
		$labels      = WC_Tax::get_tax_classes();
		foreach ( $labels as $i => $lbl ) {
			$tax_classes[] = array( 'slug' => isset( $slugs[ $i ] ) ? $slugs[ $i ] : sanitize_title( $lbl ), 'label' => $lbl );
		}
		$backorders = array(
			array( 'v' => 'no',     'label' => __( 'Do not allow', 'quick-variable-products' ) ),
			array( 'v' => 'notify', 'label' => __( 'Allow, but notify customer', 'quick-variable-products' ) ),
			array( 'v' => 'yes',    'label' => __( 'Allow', 'quick-variable-products' ) ),
		);
		$shipping_classes = array();
		$sc               = get_terms( array( 'taxonomy' => 'product_shipping_class', 'hide_empty' => false, 'number' => 0 ) );
		if ( is_array( $sc ) ) {
			foreach ( $sc as $t ) {
				$shipping_classes[] = array( 'id' => (int) $t->term_id, 'name' => $t->name );
			}
		}

		wp_localize_script(
			'erenqvp-admin',
			'ERENQVP',
			array(
				'ajaxurl'         => admin_url( 'admin-ajax.php' ),
				'nonce'           => wp_create_nonce( 'erenqvp_ajax' ),
				'attributes'      => ERENQVP_Attributes::all_global(),
				'categories'      => ERENQVP_Attributes::categories(),
				'taxStatuses'     => $tax_statuses,
				'taxClasses'      => $tax_classes,
				'backorders'      => $backorders,
				'shippingClasses' => $shipping_classes,
				'brands'          => ERENQVP_Attributes::brand_terms(),
				'tags'            => ERENQVP_Attributes::tag_terms(),
				'brandSupported'  => ERENQVP_Attributes::brand_supported(),
				'prefs'           => self::get_prefs(),
				'proActive'       => function_exists( 'erenqvp_is_pro' ) ? erenqvp_is_pro() : false,
				'maxVariations'   => ERENQVP_Product::max_variations(),
				'upgradeUrl'      => esc_url( function_exists( 'erenqvp_upgrade_url' ) ? erenqvp_upgrade_url() : apply_filters( 'erenqvp_upgrade_url', 'https://checkout.freemius.com/plugin/34490/plan/56756/' ) ),
				'reviewUrl'       => 'https://wordpress.org/support/plugin/quick-variable-products/reviews/#new-post',
				'i18n'            => array(
					'newAttribute'   => __( '➕ New attribute…', 'quick-variable-products' ),
					'chooseAttr'     => __( '— choose attribute —', 'quick-variable-products' ),
					'newAttrPrompt'  => __( 'New attribute name (e.g. Material):', 'quick-variable-products' ),
					'creating'       => __( 'Creating…', 'quick-variable-products' ),
					'noValues'       => __( 'Add at least one value to an axis, or leave all axes empty for a simple product.', 'quick-variable-products' ),
					'needName'       => __( 'Enter a product name.', 'quick-variable-products' ),
					'needPrice'      => __( 'Enter a valid regular price.', 'quick-variable-products' ),
					/* translators: %d: number of variations generated. */
					'matrixReady'    => __( '%d variations ready — set stock then save.', 'quick-variable-products' ),
					'simpleReady'    => __( 'Simple product — set stock then save.', 'quick-variable-products' ),
					/* translators: %d: number of variations about to be generated. */
					'hugeMatrix'     => __( '%d variations will be generated — continue?', 'quick-variable-products' ),
					/* translators: %d: number of variations the current axis values would generate. */
					'matrixTooBig'   => __( 'Too many variations (%d) — reduce the number of values on one or more axes.', 'quick-variable-products' ),
					'matrixStale'    => __( 'Attributes or values changed after the matrix was generated. Generate the matrix again before saving.', 'quick-variable-products' ),
					'sharedConfirm'  => __( 'All variations will sell from ONE shared stock pool — per-variation quantities will be ignored. Most stores do NOT need this. Continue?', 'quick-variable-products' ),
					'saving'         => __( 'Saving…', 'quick-variable-products' ),
					/* translators: 1: product name, 2: number of variations created. */
					'created'        => __( '✅ Created: %1$s (%2$d variations).', 'quick-variable-products' ),
					/* translators: %s: product name. */
					'createdSimple'  => __( '✅ Created: %s (simple product).', 'quick-variable-products' ),
					'openInWoo'      => __( 'Open in WooCommerce ↗', 'quick-variable-products' ),
					'genFailed'      => __( 'Could not create the product.', 'quick-variable-products' ),
					'netErr'         => __( 'Network error.', 'quick-variable-products' ),
					/* translators: %d: number of SKUs that were already taken and left blank. */
					'skuTaken'       => __( '%d SKU(s) were already used and left blank:', 'quick-variable-products' ),
					/* translators: %d: number of sale prices that were ignored. */
					'saleDropped'    => __( '%d sale price(s) were ignored because they were not below the regular price.', 'quick-variable-products' ),
					'dupAttr'        => __( 'That attribute is already used by another axis.', 'quick-variable-products' ),
					'removeAxis'     => __( 'Remove', 'quick-variable-products' ),
					'generate'       => __( 'Generate', 'quick-variable-products' ),
					'selectCover'    => __( 'Select cover image', 'quick-variable-products' ),
					'selectGallery'  => __( 'Add gallery images', 'quick-variable-products' ),
					/* translators: 1: current image position, 2: gallery image count. */
					'galleryPosition' => __( 'Image %1$d of %2$d. Use Left and Right Arrow keys to reorder.', 'quick-variable-products' ),
					'useImage'       => __( 'Use image', 'quick-variable-products' ),
					'remove'         => __( 'Remove', 'quick-variable-products' ),
					'richEditor'     => __( 'Rich editor', 'quick-variable-products' ),
					'plainEditor'    => __( 'Plain text', 'quick-variable-products' ),
					'varImages'      => __( 'Variation images', 'quick-variable-products' ),
					'imagesBy'       => __( 'by', 'quick-variable-products' ),
					/* translators: %s: variation attribute value. */
					'variationImageFor' => __( 'Select images for %s', 'quick-variable-products' ),
					'demoName'       => __( 'Sample T-Shirt', 'quick-variable-products' ),
					'demoColor'      => __( 'Color', 'quick-variable-products' ),
					'demoSize'       => __( 'Size', 'quick-variable-products' ),
					'demoColors'     => __( 'Red, Blue', 'quick-variable-products' ),
					'demoSizes'      => __( 'S, M, L', 'quick-variable-products' ),
					'reviewTitle'    => __( 'Creating products this fast? A quick ★★★★★ review keeps this plugin growing.', 'quick-variable-products' ),
					'reviewRate'     => __( 'Rate it', 'quick-variable-products' ),
					'reviewNo'       => __( 'No thanks', 'quick-variable-products' ),
					'axisValuesPh'   => __( 'red, blue, green', 'quick-variable-products' ),
					'setAllQty'      => __( 'Set all quantities', 'quick-variable-products' ),
					'genSku'         => __( '🔢 SKU', 'quick-variable-products' ),
					'genSkuEmpty'    => __( 'Generate SKU for empty rows', 'quick-variable-products' ),
					'singleProduct'  => __( '— single product (no variations) —', 'quick-variable-products' ),
					'qtyTitle'       => __( 'quantity', 'quick-variable-products' ),
					'skuPh'          => __( 'SKU (optional)', 'quick-variable-products' ),
					'pricePh'        => __( 'price override', 'quick-variable-products' ),
					// Onboarding coach-mark tour — Add screen steps.
					'tName_t'        => __( 'Start with the basics', 'quick-variable-products' ),
					'tName_b'        => __( 'Give the product a name and a base price. Everything else has a sensible default.', 'quick-variable-products' ),
					'tAttr_t'        => __( 'Pick what varies', 'quick-variable-products' ),
					'tAttr_b'        => __( 'Choose the attribute for this axis — Color, Size, Material… Not in the list? Type a new name and it is created for you.', 'quick-variable-products' ),
					'tVals_t'        => __( 'Type the values here', 'quick-variable-products' ),
					'tVals_b'        => __( 'This is where variants come from: type the values separated by commas — for example Red, Blue, Green. Every value becomes a variation.', 'quick-variable-products' ),
					'tAxis_t'        => __( 'Add another axis', 'quick-variable-products' ),
					'tAxis_b'        => __( 'Want combinations? Add a second axis such as Size — every pair is built for you: Red/S, Red/M, Blue/S…', 'quick-variable-products' ),
					'tGen_t'         => __( 'Build the matrix', 'quick-variable-products' ),
					'tGen_b'         => __( 'The key step: click here and every combination becomes its own row, ready to fill. Nothing is saved yet.', 'quick-variable-products' ),
					'tMatrix_t'      => __( 'Fill each variation', 'quick-variable-products' ),
					'tMatrix_b'      => __( 'Set stock, SKU and an optional price per row here. “Set all quantities” fills them at once; Enter jumps to the next row for barcode scanning.', 'quick-variable-products' ),
					'tPool_t'        => __( 'Shared stock pool (optional)', 'quick-variable-products' ),
					'tPool_b'        => __( 'Off by default. Turn it on only when all variations sell from ONE quantity — like cut-to-order fabric. Otherwise each variation tracks its own stock.', 'quick-variable-products' ),
					'tVimg_t'        => __( 'A photo per variation', 'quick-variable-products' ),
					'tVimg_b'        => __( 'Optionally give each value of one axis its own image — e.g. a different photo for each colour.', 'quick-variable-products' ),
					'tSave_t'        => __( 'Save — that is it', 'quick-variable-products' ),
					'tSave_b'        => __( 'Save publishes the product with all its variations. Tip: leave every axis empty to save a simple (non-variable) product instead.', 'quick-variable-products' ),
				),
				'tourUI'          => array(
					'next'    => __( 'Next', 'quick-variable-products' ),
					'prev'    => __( 'Back', 'quick-variable-products' ),
					'done'    => __( 'Got it', 'quick-variable-products' ),
					'skip'    => __( 'Skip', 'quick-variable-products' ),
					/* translators: %1$d: current step number, %2$d: total steps. */
					'counter' => __( '%1$d / %2$d', 'quick-variable-products' ),
					'tips'    => __( 'Tips', 'quick-variable-products' ),
				),
			)
		);
	}

	/**
	 * The Quick Add screen.
	 *
	 * @return void
	 */
	public static function render_add() {
		$cur = html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' );
		?>
		<div class="wrap qvp-wrap">
			<div class="qvp-app">
				<div class="qvp-hero">
					<div class="qvp-hero-icon">⚡</div>
					<div class="qvp-hero-txt">
						<h1><?php echo esc_html__( 'Add Variable Product', 'quick-variable-products' ); ?></h1>
						<p><?php echo esc_html__( 'Three quick steps — most products take under a minute.', 'quick-variable-products' ); ?></p>
					</div>
					<div class="qvp-steps">
						<span><b>1</b> <?php echo esc_html__( 'Basics', 'quick-variable-products' ); ?></span>
						<span><b>2</b> <?php echo esc_html__( 'Variations', 'quick-variable-products' ); ?></span>
						<span><b>3</b> <?php echo esc_html__( 'Save', 'quick-variable-products' ); ?></span>
					</div>
					<span id="qvp-tips-slot" class="qvp-hero-tools"></span>
				</div>
				<hr class="wp-header-end"><!-- WordPress relocates other plugins'/theme/core admin notices to just after this, i.e. below our hero (they stay visible — never hidden) -->

				<?php if ( ! get_user_meta( get_current_user_id(), 'erenqvp_tour_done', true ) ) : ?>
				<!-- First-run onboarding (dismisses itself after the first created product) -->
				<div class="qvp-card qvp-tour" id="erenqvp-tour">
					<div class="qvp-tour-t">👋 <?php echo esc_html__( 'New here? Create your first product in under a minute.', 'quick-variable-products' ); ?></div>
					<ol class="qvp-tour-steps">
						<li><?php echo esc_html__( 'Give the product a name and a price.', 'quick-variable-products' ); ?></li>
						<li><?php echo esc_html__( 'Add axes such as Color and Size, type their values, then press "Generate matrix".', 'quick-variable-products' ); ?></li>
						<li><?php echo esc_html__( 'Set the stock for each row and save — that is it.', 'quick-variable-products' ); ?></li>
					</ol>
					<div class="qvp-tour-actions">
						<button type="button" id="qvp-tour-start" class="qvp-btn-secondary">🧭 <?php echo esc_html__( 'Show me around', 'quick-variable-products' ); ?></button>
						<button type="button" id="qvp-tour-demo" class="qvp-btn-secondary">✨ <?php echo esc_html__( 'Fill with an example', 'quick-variable-products' ); ?></button>
						<button type="button" id="qvp-tour-skip" class="qvp-linkbtn"><?php echo esc_html__( 'Skip — I know my way around', 'quick-variable-products' ); ?></button>
					</div>
				</div>
				<?php endif; ?>

				<!-- 1 · Basics -->
				<div class="qvp-card">
					<div class="qvp-card-t"><span class="qvp-step">1</span><?php echo esc_html__( 'Basics', 'quick-variable-products' ); ?></div>
					<div class="qvp-grid">
						<label class="qvp-col-2"><?php echo esc_html__( 'Product name', 'quick-variable-products' ); ?>
							<input type="text" id="qvp-name" placeholder="<?php echo esc_attr__( 'e.g. Floral Baby Romper', 'quick-variable-products' ); ?>">
						</label>
						<div class="qvp-col-2 qvp-triple">
							<label><?php echo esc_html__( 'Regular price', 'quick-variable-products' ); ?> <span class="qvp-cur"><?php echo esc_html( $cur ); ?></span>
								<input type="number" id="qvp-price" min="0" step="0.01" placeholder="0.00">
							</label>
							<label><?php echo esc_html__( 'Sale price (optional)', 'quick-variable-products' ); ?> <span class="qvp-cur"><?php echo esc_html( $cur ); ?></span>
								<input type="number" id="qvp-sale" min="0" step="0.01">
							</label>
							<label><?php echo esc_html__( 'Cost / COGS', 'quick-variable-products' ); ?> <span class="qvp-cur"><?php echo esc_html( $cur ); ?></span>
								<input type="number" id="qvp-cost" min="0" step="0.01" placeholder="<?php echo esc_attr__( 'for profit reports', 'quick-variable-products' ); ?>">
							</label>
						</div>
						<label class="qvp-col-2"><?php echo esc_html__( 'Categories', 'quick-variable-products' ); ?>
							<select id="qvp-cats" multiple size="4"></select>
						</label>
					</div>
					<div class="qvp-mediarow">
						<div class="qvp-media-unit">
							<span class="qvp-media-lbl"><?php echo esc_html__( 'Cover', 'quick-variable-products' ); ?></span>
							<div id="qvp-cover" class="qvp-cover qvp-cover-sm" role="button" tabindex="0" aria-label="<?php echo esc_attr__( 'Select cover image', 'quick-variable-products' ); ?>" title="<?php echo esc_attr__( 'Select cover image', 'quick-variable-products' ); ?>"><span class="qvp-cover-ph">＋</span></div>
							<input type="hidden" id="qvp-img-id" value="">
						</div>
						<div class="qvp-media-unit qvp-media-grow">
							<span class="qvp-media-lbl"><?php echo esc_html__( 'Gallery', 'quick-variable-products' ); ?> <small><?php echo esc_html__( 'drag to reorder', 'quick-variable-products' ); ?></small></span>
							<div id="qvp-gallery" class="qvp-gallery" role="list" aria-label="<?php echo esc_attr__( 'Product gallery', 'quick-variable-products' ); ?>"></div>
							<button type="button" id="qvp-gallery-add" class="qvp-btn-ghost qvp-mini">＋ <?php echo esc_html__( 'Add images', 'quick-variable-products' ); ?></button>
						</div>
					</div>
				</div>

				<!-- 2 · Variations (the star) -->
				<div class="qvp-card qvp-star">
					<div class="qvp-star-head">
						<div class="qvp-card-t"><span class="qvp-step">2</span><?php echo esc_html__( 'Variations', 'quick-variable-products' ); ?></div>
						<span class="qvp-star-badge">★ <?php echo esc_html__( 'the whole point', 'quick-variable-products' ); ?></span>
					</div>
					<p class="qvp-star-lede"><?php echo esc_html__( 'Add an axis (Color, Size, Material…), type its values, then generate every combination in one click. Leave empty for a simple product.', 'quick-variable-products' ); ?></p>
					<label class="qvp-inline qvp-vimg-toggle"><input type="checkbox" id="qvp-vimg-on"> <?php echo esc_html__( 'Give each variation its own image (e.g. a photo per colour)', 'quick-variable-products' ); ?></label>
					<div id="qvp-axes"></div>
					<div class="qvp-axis-actions">
						<button type="button" id="qvp-add-axis" class="qvp-btn-ghost">＋ <?php echo esc_html__( 'Add axis', 'quick-variable-products' ); ?></button>
						<button type="button" id="qvp-genmatrix" class="qvp-btn-primary qvp-gen">⚙️ <?php echo esc_html__( 'Generate matrix', 'quick-variable-products' ); ?></button>
						<span id="qvp-tpl-slot"></span>
					</div>
				</div>

				<!-- Matrix -->
				<div class="qvp-card qvp-star" id="qvp-matrix-wrap" style="display:none">
					<div class="qvp-card-t"><span class="qvp-ic">🧬</span><?php echo esc_html__( 'Variations', 'quick-variable-products' ); ?></div>
					<div id="qvp-matrix" class="qvp-matrix"></div>
				</div>

				<!-- Optional details (collapsible) -->
				<details class="qvp-acc">
					<summary><span class="qvp-ic">📝</span><?php echo esc_html__( 'Content', 'quick-variable-products' ); ?><span class="qvp-acc-hint"><?php echo esc_html__( 'short & long description', 'quick-variable-products' ); ?></span></summary>
					<div class="qvp-acc-body">
						<label class="qvp-block"><?php echo esc_html__( 'Short description', 'quick-variable-products' ); ?>
							<textarea id="qvp-short-desc" rows="2"></textarea>
						</label>
						<div class="qvp-block">
							<div class="qvp-block-h"><label for="qvp-desc"><?php echo esc_html__( 'Description', 'quick-variable-products' ); ?></label>
								<button type="button" id="qvp-rte-toggle" class="qvp-linkbtn">✏️ <?php echo esc_html__( 'Rich editor', 'quick-variable-products' ); ?></button>
							</div>
							<textarea id="qvp-desc" rows="6"></textarea>
						</div>
					</div>
				</details>

				<details class="qvp-acc">
					<summary><span class="qvp-ic">🏷️</span><?php echo esc_html__( 'Brand & tags', 'quick-variable-products' ); ?></summary>
					<div class="qvp-acc-body qvp-grid">
						<label id="qvp-brand-wrap"><?php echo esc_html__( 'Brand', 'quick-variable-products' ); ?>
							<input type="text" id="qvp-brand" list="qvp-brand-list" autocomplete="off" placeholder="<?php echo esc_attr__( 'pick or type a brand', 'quick-variable-products' ); ?>">
							<datalist id="qvp-brand-list"></datalist>
						</label>
						<label><?php echo esc_html__( 'Tags', 'quick-variable-products' ); ?>
							<input type="text" id="qvp-tags" list="qvp-tag-list" autocomplete="off" placeholder="<?php echo esc_attr__( 'comma separated', 'quick-variable-products' ); ?>">
							<datalist id="qvp-tag-list"></datalist>
						</label>
					</div>
				</details>

				<details class="qvp-acc">
					<summary><span class="qvp-ic">🧾</span><?php echo esc_html__( 'Tax & inventory', 'quick-variable-products' ); ?><span class="qvp-acc-hint"><?php echo esc_html__( 'remembered', 'quick-variable-products' ); ?></span></summary>
					<div class="qvp-acc-body qvp-grid">
						<label><?php echo esc_html__( 'Tax status', 'quick-variable-products' ); ?><select id="qvp-tax-status"></select></label>
						<label><?php echo esc_html__( 'Tax class', 'quick-variable-products' ); ?><select id="qvp-tax-class"></select></label>
						<label><?php echo esc_html__( 'Backorders', 'quick-variable-products' ); ?><select id="qvp-backorders"></select></label>
						<div class="qvp-checks qvp-col-2">
							<label class="qvp-inline"><input type="checkbox" id="qvp-manage-stock" checked> <?php echo esc_html__( 'Track stock quantity', 'quick-variable-products' ); ?></label>
							<label class="qvp-inline"><input type="checkbox" id="qvp-auto-sku"> <?php echo esc_html__( 'Auto-generate SKU for empty rows', 'quick-variable-products' ); ?></label>
						</div>
						<div class="qvp-checks qvp-col-2" id="qvp-shared-row">
							<label class="qvp-inline"><input type="checkbox" id="qvp-shared-stock"> <?php echo esc_html__( 'Shared stock pool — all variations sell from ONE quantity (e.g. cut-to-order fabric)', 'quick-variable-products' ); ?></label>
							<label class="qvp-inline qvp-shared-qty" id="qvp-shared-qty-wrap" style="display:none" for="qvp-shared-qty">
								<?php echo esc_html__( 'Pool quantity', 'quick-variable-products' ); ?>
								<input type="number" id="qvp-shared-qty" min="0" value="0" style="width:90px">
							</label>
						</div>
					</div>
				</details>

				<details class="qvp-acc">
					<summary><span class="qvp-ic">🚚</span><?php echo esc_html__( 'Shipping', 'quick-variable-products' ); ?></summary>
					<div class="qvp-acc-body qvp-grid">
						<label><?php echo esc_html__( 'Weight', 'quick-variable-products' ); ?><input type="number" id="qvp-weight" min="0" step="0.001"></label>
						<label><?php echo esc_html__( 'Shipping class', 'quick-variable-products' ); ?><select id="qvp-ship-class"></select></label>
						<label class="qvp-col-2"><?php echo esc_html__( 'Dimensions (L × W × H)', 'quick-variable-products' ); ?>
							<span class="qvp-dims">
								<input type="number" id="qvp-length" min="0" step="0.01" placeholder="L" aria-label="<?php echo esc_attr__( 'Length', 'quick-variable-products' ); ?>">
								<input type="number" id="qvp-width" min="0" step="0.01" placeholder="W" aria-label="<?php echo esc_attr__( 'Width', 'quick-variable-products' ); ?>">
								<input type="number" id="qvp-height" min="0" step="0.01" placeholder="H" aria-label="<?php echo esc_attr__( 'Height', 'quick-variable-products' ); ?>">
							</span>
						</label>
					</div>
				</details>

				<div class="qvp-savebar">
					<button type="button" id="qvp-save" class="qvp-btn-primary"><?php echo esc_html__( '✅ Save product', 'quick-variable-products' ); ?></button>
					<label class="qvp-inline qvp-draft"><input type="checkbox" id="qvp-draft"> <?php echo esc_html__( 'Save as draft', 'quick-variable-products' ); ?></label>
					<div id="qvp-result" class="qvp-result" role="status" aria-live="polite"></div>
				</div>

				<p class="qvp-foot">
					Quick Variable Products v<?php echo esc_html( ERENQVP_VER ); ?> ·
					<a href="https://wordpress.org/support/plugin/quick-variable-products/reviews/#new-post" target="_blank" rel="noopener">⭐ <?php echo esc_html__( 'Rate this plugin', 'quick-variable-products' ); ?></a> ·
					<a href="https://wordpress.org/support/plugin/quick-variable-products/" target="_blank" rel="noopener"><?php echo esc_html__( 'Support', 'quick-variable-products' ); ?></a>
				</p>
			</div>
			<div id="qvp-toast" class="qvp-toast" aria-live="polite" aria-atomic="false"></div>
		</div>
		<?php
	}

	/**
	 * Minimal settings: default auto-SKU + SKU prefix.
	 *
	 * @return void
	 */
	public static function render_settings() {
		$prefix   = (string) get_option( ERENQVP_Barcode::OPT_PREFIX, '' );
		$auto_sku = (bool) get_option( self::OPT_AUTO_SKU, false );
		?>
		<div class="wrap qvp-wrap">
			<div class="qvp-app qvp-app-narrow">
				<div class="qvp-hero qvp-hero-sm">
					<div class="qvp-hero-icon">⚙️</div>
					<div class="qvp-hero-txt">
						<h1><?php echo esc_html__( 'Quick Variable Products — Settings', 'quick-variable-products' ); ?></h1>
						<p><?php echo esc_html__( 'Defaults for SKU generation on the Add screen.', 'quick-variable-products' ); ?></p>
					</div>
				</div>
				<hr class="wp-header-end"><!-- relocate foreign admin notices below the hero; still shown, never hidden -->

				<?php if ( self::$settings_saved ) : ?>
					<div class="qvp-saved-inline"><div class="qvp-ok">✅ <?php echo esc_html__( 'Settings saved.', 'quick-variable-products' ); ?></div></div>
				<?php endif; ?>

				<div class="qvp-card">
					<div class="qvp-card-t"><span class="qvp-ic">🔢</span><?php echo esc_html__( 'SKU generation', 'quick-variable-products' ); ?></div>
					<form method="post">
						<?php wp_nonce_field( 'erenqvp_settings_save' ); ?>
						<div class="qvp-settings-grid">
							<label class="qvp-block"><?php echo esc_html__( 'SKU prefix', 'quick-variable-products' ); ?>
								<input type="text" name="erenqvp_sku_prefix" value="<?php echo esc_attr( $prefix ); ?>" maxlength="8">
								<span class="qvp-desc"><?php echo esc_html__( 'Letters/digits only (max 8). Used when auto-generating SKUs, e.g. "ACME" → ACME7F3K2.', 'quick-variable-products' ); ?></span>
							</label>
							<label class="qvp-inline qvp-block"><input type="checkbox" name="erenqvp_auto_sku" value="1" <?php checked( $auto_sku ); ?>> <?php echo esc_html__( 'Tick the "Auto-generate SKU" box by default on the Add screen.', 'quick-variable-products' ); ?></label>
						</div>
						<p><button type="submit" name="erenqvp_save_settings" class="qvp-btn-primary"><?php echo esc_html__( 'Save', 'quick-variable-products' ); ?></button></p>
					</form>
				</div>

				<div class="qvp-card">
					<div class="qvp-card-t"><span class="qvp-ic">🌐</span><?php echo esc_html__( 'Language', 'quick-variable-products' ); ?></div>
					<form method="post">
						<?php wp_nonce_field( 'erenqvp_set_locale' ); ?>
						<div class="qvp-settings-grid">
							<label class="qvp-block"><?php echo esc_html__( 'Show this plugin in', 'quick-variable-products' ); ?>
								<select name="erenqvp_locale">
									<?php
									$erenqvp_pref = function_exists( 'erenqvp_user_locale_pref' ) ? erenqvp_user_locale_pref() : 'auto';
									foreach ( erenqvp_available_locales() as $erenqvp_loc => $erenqvp_label ) :
										?>
										<option value="<?php echo esc_attr( $erenqvp_loc ); ?>" <?php selected( $erenqvp_pref, $erenqvp_loc ); ?>><?php echo esc_html( $erenqvp_label ); ?></option>
									<?php endforeach; ?>
								</select>
								<span class="qvp-desc"><?php echo esc_html__( 'Only this plugin follows your choice — the rest of wp-admin keeps the site language.', 'quick-variable-products' ); ?></span>
							</label>
						</div>
						<p><button type="submit" name="erenqvp_save_locale" class="qvp-btn-primary"><?php echo esc_html__( 'Save', 'quick-variable-products' ); ?></button></p>
					</form>
				</div>

				<div class="qvp-foot">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=erenqvp-help' ) ); ?>"><?php echo esc_html__( 'Help & FAQ', 'quick-variable-products' ); ?></a>
					&nbsp;·&nbsp;
					← <a href="<?php echo esc_url( admin_url( 'admin.php?page=erenqvp-add' ) ); ?>"><?php echo esc_html__( 'Back to Add Product', 'quick-variable-products' ); ?></a>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Persist settings.
	 *
	 * @return void
	 */
	public static function maybe_save_settings() {
		// Per-user language preference (no special capability beyond reaching the screen).
		if ( isset( $_POST['erenqvp_save_locale'] ) && current_user_can( ERENQVP_CAP ) && check_admin_referer( 'erenqvp_set_locale' ) ) {
			$loc = isset( $_POST['erenqvp_locale'] ) ? sanitize_text_field( wp_unslash( $_POST['erenqvp_locale'] ) ) : 'auto';
			if ( function_exists( 'erenqvp_available_locales' ) && array_key_exists( $loc, erenqvp_available_locales() ) ) {
				update_user_meta( get_current_user_id(), 'erenqvp_locale', $loc );
			}
			self::$settings_saved = true;
		}
		if ( ! isset( $_POST['erenqvp_save_settings'] ) ) {
			return;
		}
		if ( ! current_user_can( ERENQVP_CAP ) || ! check_admin_referer( 'erenqvp_settings_save' ) ) {
			return;
		}
		$prefix = isset( $_POST['erenqvp_sku_prefix'] ) ? sanitize_text_field( wp_unslash( $_POST['erenqvp_sku_prefix'] ) ) : '';
		$prefix = strtoupper( preg_replace( '/[^A-Za-z0-9]/', '', $prefix ) );
		update_option( ERENQVP_Barcode::OPT_PREFIX, substr( $prefix, 0, 8 ), false );
		update_option( self::OPT_AUTO_SKU, ! empty( $_POST['erenqvp_auto_sku'] ), false );
		// Rendered inline by render_settings() so the save result stays beside the form.
		self::$settings_saved = true;
	}

	/**
	 * Add an RTL marker body class on our screens when the effective plugin language
	 * is right-to-left (Arabic). The class is a styling hook (for site CSS and for the
	 * plugin's own future RTL rules) — the shipped stylesheets do not mirror the layout
	 * yet, so Arabic currently renders RTL text in the standard LTR layout.
	 *
	 * @param string $classes Space-separated body classes.
	 * @return string
	 */
	public static function body_class( $classes ) {
		if ( self::is_our_screen() && function_exists( 'erenqvp_is_rtl_locale' ) && erenqvp_is_rtl_locale( erenqvp_effective_locale() ) ) {
			$classes .= ' qvp-locale-rtl';
		}
		return $classes;
	}

	/**
	 * Help & FAQ: the questions that generate the most support mail, plus where to
	 * reach us. Ships in both builds; the "contact" target is Pro (priority) when the
	 * SDK is present, otherwise the community forum.
	 *
	 * @return void
	 */
	public static function render_help() {
		$support = function_exists( 'erenqvp_support_url' ) ? erenqvp_support_url() : 'https://wordpress.org/support/plugin/quick-variable-products/';
		$faqs    = array(
			array(
				__( 'How do I create a variable product fast?', 'quick-variable-products' ),
				__( 'Open Quick Products → Add Product, add one or more attribute axes (e.g. Color, Size), type the values for each, and click Generate matrix. Set per-row stock, SKU and price, then Save.', 'quick-variable-products' ),
			),
			array(
				__( 'Can I make a simple (non-variable) product?', 'quick-variable-products' ),
				__( 'Yes — leave the axes empty and it saves a simple product with the price and stock you entered.', 'quick-variable-products' ),
			),
			array(
				__( 'Does it work with my existing attributes?', 'quick-variable-products' ),
				__( 'Yes. It lists every global attribute under Products → Attributes, and you can create a new one on the fly. Creating brand-new terms needs the product-term management capability.', 'quick-variable-products' ),
			),
			array(
				__( 'Is it safe with my SEO / translation / indexing plugins?', 'quick-variable-products' ),
				__( 'Yes. While writing a product it briefly detaches core post hooks so a broken third-party callback cannot leave missing variations, then re-fires the key hooks once so Yoast, Rank Math, WPML/Polylang and search indexers still process it.', 'quick-variable-products' ),
			),
			array(
				__( 'Can I undo a bulk change? (Pro)', 'quick-variable-products' ),
				__( 'Yes. Pro keeps ten recent bulk runs for 30 days. Undo restores a field only if its current value still matches what the run wrote, so a teammate’s newer edit is never overwritten.', 'quick-variable-products' ),
			),
			array(
				__( 'Change the plugin’s language', 'quick-variable-products' ),
				__( 'Open Settings and pick a language under “Show this plugin in”. Only this plugin follows your choice; the rest of wp-admin keeps the site language.', 'quick-variable-products' ),
			),
		);
		?>
		<div class="wrap qvp-wrap">
			<div class="qvp-app qvp-app-narrow">
				<div class="qvp-hero qvp-hero-sm">
					<div class="qvp-hero-icon">💬</div>
					<div class="qvp-hero-txt">
						<h1><?php echo esc_html__( 'Help &amp; FAQ', 'quick-variable-products' ); ?></h1>
						<p><?php echo esc_html__( 'Answers to the most common questions — and where to reach us if you’re still stuck.', 'quick-variable-products' ); ?></p>
					</div>
				</div>
				<hr class="wp-header-end"><!-- relocate foreign admin notices below the hero; still shown, never hidden -->
				<?php foreach ( $faqs as $erenqvp_faq ) : ?>
					<div class="qvp-card">
						<div class="qvp-card-t"><span class="qvp-ic">❓</span><?php echo esc_html( $erenqvp_faq[0] ); ?></div>
						<p class="qvp-desc"><?php echo esc_html( $erenqvp_faq[1] ); ?></p>
					</div>
				<?php endforeach; ?>
				<div class="qvp-card">
					<div class="qvp-card-t"><span class="qvp-ic">📮</span><?php echo esc_html__( 'Still need help?', 'quick-variable-products' ); ?></div>
					<p class="qvp-desc"><?php echo esc_html__( 'We’re happy to help.', 'quick-variable-products' ); ?></p>
					<p><a class="qvp-btn-primary" href="<?php echo esc_url( $support ); ?>" target="_blank" rel="noopener"><?php echo esc_html( ( function_exists( 'erenqvp_is_pro' ) && erenqvp_is_pro() ) ? __( 'Contact support (priority)', 'quick-variable-products' ) : __( 'Ask on the support forum', 'quick-variable-products' ) ); ?></a></p>
				</div>
				<div class="qvp-foot">← <a href="<?php echo esc_url( admin_url( 'admin.php?page=erenqvp-add' ) ); ?>"><?php echo esc_html__( 'Back to Add Product', 'quick-variable-products' ); ?></a></div>
			</div>
		</div>
		<?php
	}
}
